Merge pull request #1095 from arsher/cefipcserialization

CEF IPC based serialization and communication for EvaluateScriptAsync
This commit is contained in:
Alex Maitland
2015-06-29 22:22:56 +10:00
45 changed files with 853 additions and 306 deletions
@@ -8,10 +8,15 @@
#include "CefBrowserWrapper.h"
#include "CefAppUnmanagedWrapper.h"
#include "JavascriptRootObjectWrapper.h"
#include "Serialization\V8Serialization.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;
using namespace CefSharp::Internals::Serialization;
namespace CefSharp
{
@@ -32,7 +37,7 @@ namespace CefSharp
void CefAppUnmanagedWrapper::OnBrowserDestroyed(CefRefPtr<CefBrowser> browser)
{
auto wrapper = FindBrowserWrapper(browser, false);
auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), false);
if (wrapper != nullptr)
{
@@ -44,7 +49,7 @@ namespace CefSharp
void CefAppUnmanagedWrapper::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
{
auto wrapper = FindBrowserWrapper(browser, true);
auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), true);
if (wrapper->JavascriptRootObject != nullptr)
{
@@ -59,7 +64,7 @@ namespace CefSharp
void CefAppUnmanagedWrapper::OnContextReleased(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
{
auto wrapper = FindBrowserWrapper(browser, true);
auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), true);
if (wrapper->JavascriptRootObjectWrapper != nullptr)
{
@@ -68,9 +73,8 @@ namespace CefSharp
}
};
CefBrowserWrapper^ CefAppUnmanagedWrapper::FindBrowserWrapper(CefRefPtr<CefBrowser> browser, bool mustExist)
CefBrowserWrapper^ CefAppUnmanagedWrapper::FindBrowserWrapper(int browserId, bool mustExist)
{
auto browserId = browser->GetIdentifier();
CefBrowserWrapper^ wrapper = nullptr;
_browserWrappers->TryGetValue(browserId, wrapper);
@@ -81,5 +85,71 @@ namespace CefSharp
}
return wrapper;
}
bool CefAppUnmanagedWrapper::OnProcessMessageReceived(CefRefPtr<CefBrowser> browser, CefProcessId sourceProcessId, CefRefPtr<CefProcessMessage> message)
{
auto handled = false;
auto name = message->GetName();
if (name == kEvaluateJavascriptRequest)
{
auto argList = message->GetArgumentList();
auto browserId = argList->GetInt(0);
auto frameId = GetInt64(argList, 1);
auto callbackId = GetInt64(argList, 2);
auto script = argList->GetString(3);
if(browser->GetIdentifier() != browserId)
{
throw gcnew InvalidOperationException(String::Format("Request BrowserId : {0} does not match browser Id : {1}", browserId, browser->GetIdentifier()));
}
auto browserWrapper = FindBrowserWrapper(browserId, true);
auto frame = browser->GetFrame(frameId);
if (frame.get())
{
auto context = frame->GetV8Context();
if (context.get() && context->Enter())
{
try
{
CefRefPtr<CefV8Value> result;
CefRefPtr<CefV8Exception> exception;
auto success = context->Eval(script, result, exception);
auto response = CefProcessMessage::Create(kEvaluateJavascriptResponse);
auto argList = response->GetArgumentList();
argList->SetBool(0, success);
SetInt64(callbackId, argList, 1);
if (success)
{
SerializeV8Object(result, argList, 2, browserWrapper->CallbackRegistry);
}
else
{
argList->SetString(2, exception->GetMessage());
}
if (response.get())
{
browser->SendProcessMessage(sourceProcessId, response);
}
}
finally
{
context->Exit();
}
}
}
else
{
//TODO handle error
}
handled = true;
}
return handled;
};
}
@@ -19,10 +19,10 @@ namespace CefSharp
private class CefAppUnmanagedWrapper : CefApp, CefRenderProcessHandler
{
private:
gcroot<Action<CefBrowserWrapper^>^> _onBrowserCreated;
gcroot<Action<CefBrowserWrapper^>^> _onBrowserDestroyed;
gcroot<Dictionary<int, CefBrowserWrapper^>^> _browserWrappers;
CefBrowserWrapper^ FindBrowserWrapper(CefRefPtr<CefBrowser> browser, bool mustExist);
public:
CefAppUnmanagedWrapper(Action<CefBrowserWrapper^>^ onBrowserCreated, Action<CefBrowserWrapper^>^ onBrowserDestoryed)
@@ -39,11 +39,14 @@ namespace CefSharp
delete _onBrowserDestroyed;
}
CefBrowserWrapper^ FindBrowserWrapper(int browserId, bool mustExist);
virtual DECL CefRefPtr<CefRenderProcessHandler> GetRenderProcessHandler() OVERRIDE;
virtual DECL void OnBrowserCreated(CefRefPtr<CefBrowser> browser) OVERRIDE;
virtual DECL void OnBrowserDestroyed(CefRefPtr<CefBrowser> browser) OVERRIDE;
virtual DECL void OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context) OVERRIDE;
virtual DECL void OnContextReleased(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context) OVERRIDE;
virtual DECL bool OnProcessMessageReceived(CefRefPtr<CefBrowser> browser, CefProcessId sourceProcessId, CefRefPtr<CefProcessMessage> message) OVERRIDE;
IMPLEMENT_REFCOUNTING(CefAppUnmanagedWrapper);
};
@@ -31,52 +31,6 @@ namespace CefSharp
}
}
JavascriptResponse^ CefBrowserWrapper::EvaluateScriptInContext(CefRefPtr<CefV8Context> context, CefString script)
{
CefRefPtr<CefV8Value> result;
CefRefPtr<CefV8Exception> exception;
JavascriptResponse^ response = gcnew JavascriptResponse();
response->Success = context->Eval(script, result, exception);
if (response->Success)
{
if (result->IsFunction())
{
response->Result = _callbackRegistry->Register(context, result);
}
else
{
response->Result = TypeUtils::ConvertFromCef(result);
}
}
else if (exception.get())
{
response->Message = StringUtils::ToClr(exception->GetMessage());
}
return response;
}
JavascriptResponse^ CefBrowserWrapper::DoEvaluateScript(System::Int64 frameId, String^ script)
{
auto frame = _cefBrowser->GetFrame(frameId);
CefRefPtr<CefV8Context> context = frame->GetV8Context();
if (context.get() && context->Enter())
{
try
{
return EvaluateScriptInContext(context, StringUtils::ToNative(script));
}
finally
{
context->Exit();
}
}
return nullptr;
}
JavascriptResponse^ CefBrowserWrapper::DoCallback(System::Int64 callbackId, array<Object^>^ parameters)
{
return _callbackRegistry->Execute(callbackId, parameters);
@@ -87,6 +41,11 @@ namespace CefSharp
_callbackRegistry->Deregister(id);
}
JavascriptCallbackRegistry^ CefBrowserWrapper::CallbackRegistry::get()
{
return _callbackRegistry;
}
CefBrowserWrapper::!CefBrowserWrapper()
{
_cefBrowser = nullptr;
@@ -30,6 +30,12 @@ namespace CefSharp
JavascriptCallbackRegistry^ _callbackRegistry;
JavascriptRootObjectWrapper^ _javascriptRootObjectWrapper;
internal:
property JavascriptCallbackRegistry^ CallbackRegistry
{
CefSharp::Internals::JavascriptCallbackRegistry^ get();
}
public:
CefBrowserWrapper(CefRefPtr<CefBrowser> cefBrowser);
!CefBrowserWrapper();
@@ -53,10 +59,6 @@ namespace CefSharp
// The WCF proxy to the parent process.
property IBrowserProcess^ BrowserProcess;
JavascriptResponse^ EvaluateScriptInContext(CefRefPtr<CefV8Context> context, CefString script);
virtual JavascriptResponse^ DoEvaluateScript(System::Int64 frameId, String^ script);
JavascriptResponse^ DoCallback(System::Int64 callbackId, array<Object^>^ parameters);
void DestroyJavascriptCallback(Int64 id);
@@ -155,6 +155,7 @@
<ItemGroup>
<ClInclude Include="..\CefSharp.Core\Internals\MCefRefPtr.h" />
<ClInclude Include="..\CefSharp.Core\Internals\ReportUnhandledExceptions.h" />
<ClInclude Include="..\CefSharp.Core\Internals\Serialization\Primitives.h" />
<ClInclude Include="..\CefSharp.Core\Internals\StringUtils.h" />
<ClInclude Include="CefAppUnmanagedWrapper.h" />
<ClInclude Include="CefAppWrapper.h" />
@@ -171,9 +172,11 @@
<ClInclude Include="JavascriptRootObjectWrapper.h" />
<ClInclude Include="Stdafx.h" />
<ClInclude Include="TypeUtils.h" />
<ClInclude Include="Serialization\V8Serialization.h" />
<ClInclude Include="vcclr_local.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\CefSharp.Core\Internals\Serialization\Primitives.cpp" />
<ClCompile Include="..\CefSharp.Core\Internals\StringUtils.cpp" />
<ClCompile Include="AssemblyInfo.cpp" />
<ClCompile Include="CefAppUnmanagedWrapper.cpp" />
@@ -193,6 +196,7 @@
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="TypeUtils.cpp" />
<ClCompile Include="Serialization\V8Serialization.cpp" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CefSharp\CefSharp.csproj">
@@ -68,6 +68,12 @@
<ClInclude Include="..\CefSharp.Core\Internals\ReportUnhandledExceptions.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\CefSharp.Core\Internals\Serialization\Primitives.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Serialization\V8Serialization.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="AssemblyInfo.cpp">
@@ -112,6 +118,12 @@
<ClCompile Include="JavascriptCallbackWrapper.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\CefSharp.Core\Internals\Serialization\Primitives.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Serialization\V8Serialization.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
@@ -0,0 +1,85 @@
// Copyright © 2010-2015 The CefSharp Project. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#include "Stdafx.h"
#include "V8Serialization.h"
#include "JavascriptCallbackRegistry.h"
#include "../CefSharp.Core/Internals/Serialization/Primitives.h"
namespace CefSharp
{
namespace Internals
{
namespace Serialization
{
template<typename TList, typename TIndex>
void SerializeV8Object(CefRefPtr<CefV8Value> obj, CefRefPtr<TList> list, TIndex index, JavascriptCallbackRegistry^ callbackRegistry)
{
if (obj->IsNull() || obj->IsUndefined())
{
list->SetNull(index);
}
else if (obj->IsBool())
list->SetBool(index, obj->GetBoolValue());
else if (obj->IsInt())
list->SetInt(index, obj->GetIntValue());
else if (obj->IsDouble())
list->SetDouble(index, obj->GetDoubleValue());
else if (obj->IsString())
list->SetString(index, obj->GetStringValue());
else if (obj->IsDate())
SetCefTime(obj->GetDateValue(), list, index);
else if (obj->IsArray())
{
int arrLength = obj->GetArrayLength();
std::vector<CefString> keys;
if (arrLength > 0 && obj->GetKeys(keys))
{
auto array = CefListValue::Create();
for (int i = 0; i < arrLength; i++)
{
SerializeV8Object(obj->GetValue(keys[i]), array, i, callbackRegistry);
}
list->SetList(index, array);
}
else
{
list->SetNull(index);
}
}
else if (obj->IsFunction())
{
auto context = CefV8Context::GetCurrentContext();
auto jsCallback = callbackRegistry->Register(context, obj);
SetJsCallback(jsCallback, list, index);
}
else if (obj->IsObject())
{
std::vector<CefString> keys;
if (obj->GetKeys(keys) && keys.size() > 0)
{
auto result = CefDictionaryValue::Create();
for (int i = 0; i < keys.size(); i++)
{
auto p_keyStr = StringUtils::ToClr(keys[i].ToString());
if ((obj->HasValue(keys[i])) && (!p_keyStr->StartsWith("__")))
{
SerializeV8Object(obj->GetValue(keys[i]), result, keys[i], callbackRegistry);
}
}
list->SetDictionary(index, result);
}
}
else
{
list->SetNull(index);
}
}
template void SerializeV8Object(CefRefPtr<CefV8Value> value, CefRefPtr<CefListValue> list, int index, JavascriptCallbackRegistry^ callbackRegistry);
template void SerializeV8Object(CefRefPtr<CefV8Value> value, CefRefPtr<CefDictionaryValue> list, CefString index, JavascriptCallbackRegistry^ callbackRegistry);
}
}
}
@@ -0,0 +1,25 @@
// Copyright © 2010-2015 The CefSharp Project. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once
#include "include/cef_v8.h"
namespace CefSharp
{
namespace Internals
{
ref class JavascriptCallbackRegistry;
namespace Serialization
{
//Functions to sserialize data to be sent to the browser process.
//Serializes a V8 structure into a given index of a CefListValue or CefDictionaryValue
//JavascriptCallbackRegistry should be passed to save V8Values with function types
template<typename TList, typename TIndex>
void SerializeV8Object(CefRefPtr<CefV8Value> value, CefRefPtr<TList> list, TIndex index, JavascriptCallbackRegistry^ callbackRegistry);
}
}
}
@@ -113,72 +113,6 @@ namespace CefSharp.BrowserSubprocess
browser.JavascriptRootObject = null;
}
public Task<JavascriptResponse> EvaluateScriptAsync(int browserId, long frameId, string script, TimeSpan? timeout)
{
var factory = RenderThreadTaskFactory;
var browser = browsers.FirstOrDefault(x => x.BrowserId == browserId);
if (browser == null)
{
return TaskExtensions.FromResult(new JavascriptResponse
{
Success = false,
Message = string.Format("Browser with Id {0} not found in Render Sub Process.", browserId)
});
}
var task = factory.StartNew(() =>
{
try
{
var response = browser.DoEvaluateScript(frameId, script);
return response;
}
catch (Exception ex)
{
return new JavascriptResponse
{
Success = false,
Message = ex.ToString()
};
}
}, TaskCreationOptions.AttachedToParent);
return timeout.HasValue ? task.WithTimeout(timeout.Value) : task;
}
public IAsyncResult BeginEvaluateScriptAsync(int browserId, long frameId, string script, TimeSpan? timeout, AsyncCallback callback, object state)
{
var tcs = new TaskCompletionSource<JavascriptResponse>(state);
var task = EvaluateScriptAsync(browserId, frameId, script, timeout);
task.ContinueWith(t =>
{
if (t.IsFaulted)
{
tcs.TrySetException(t.Exception.InnerExceptions);
}
else if (t.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
tcs.TrySetResult(t.Result);
}
if (callback != null)
{
callback(tcs.Task);
}
});
return tcs.Task;
}
public JavascriptResponse EndEvaluateScriptAsync(IAsyncResult result)
{
return ((Task<JavascriptResponse>)result).Result;
}
public IAsyncResult BeginJavascriptCallbackAsync(int browserId, long callbackId, object[] parameters, TimeSpan? timeout, AsyncCallback callback, object state)
{
var tcs = new TaskCompletionSource<JavascriptResponse>(state);
-13
View File
@@ -33,7 +33,6 @@ namespace CefSharp
private:
static Object^ _sync;
static bool _wcfEnabled = false;
static bool _initialized = false;
static HashSet<IDisposable^>^ _disposables;
@@ -75,14 +74,6 @@ namespace CefSharp
_disposables->Remove(item);
}
static property bool WcfEnabled
{
bool get()
{
return _wcfEnabled;
}
}
/// <summary>Gets a value that indicates whether CefSharp is initialized.</summary>
/// <value>true if CefSharp is initialized; otherwise, false.</value>
static property bool IsInitialized
@@ -191,10 +182,6 @@ namespace CefSharp
}
_initialized = success;
if (success)
{
_wcfEnabled = cefSettings->WcfEnabled;
}
if (_initialized && shutdownOnProcessExit)
{
-8
View File
@@ -30,19 +30,11 @@ namespace CefSharp
BrowserSubprocessPath = "CefSharp.BrowserSubprocess.exe";
_cefCustomSchemes = gcnew List<CefCustomScheme^>();
_cefCommandLineArgs = gcnew Dictionary<String^, String^>();
WcfEnabled = true;
}
!CefSettings() { delete _cefSettings; }
~CefSettings() { delete _cefSettings; }
/// <summary>
/// WCF is used by JavascriptBinding and EvaluateScriptAsync.
/// Disabling effectively disables both of these features.
/// Defaults to true
/// </summary>
virtual property bool WcfEnabled;
virtual property IEnumerable<CefCustomScheme^>^ CefCustomSchemes
{
IEnumerable<CefCustomScheme^>^ get() { return _cefCustomSchemes; }
+5
View File
@@ -230,6 +230,8 @@
<ClCompile Include="Internals\StringVisitor.cpp" />
<ClCompile Include="ManagedCefBrowserAdapter.cpp" />
<ClCompile Include="NativeMethodWrapper.cpp" />
<ClCompile Include="Internals\Serialization\V8Serialization.cpp" />
<ClCompile Include="Internals\Serialization\Primitives.cpp" />
<ClCompile Include="ResourceHandlerWrapper.cpp" />
<ClCompile Include="Stdafx.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
@@ -265,6 +267,7 @@
<ClInclude Include="Internals\CefRequestWrapper.h" />
<ClInclude Include="Internals\CefJSDialogCallbackWrapper.h" />
<ClInclude Include="Internals\MCefRefPtr.h" />
<ClInclude Include="Internals\Messaging\Messages.h" />
<ClInclude Include="Internals\PluginVisitor.h" />
<ClInclude Include="Internals\RenderClientAdapter.h" />
<ClInclude Include="Internals\ReportUnhandledExceptions.h" />
@@ -272,9 +275,11 @@
<ClInclude Include="Internals\StringVisitor.h" />
<ClInclude Include="Internals\TypeConversion.h" />
<ClInclude Include="NativeMethodWrapper.h" />
<ClInclude Include="Internals\Serialization\V8Serialization.h" />
<ClInclude Include="PaintElementType.h" />
<ClInclude Include="ManagedCefBrowserAdapter.h" />
<ClInclude Include="CefSettings.h" />
<ClInclude Include="Internals\Serialization\Primitives.h" />
<ClInclude Include="SchemeHandlerFactoryWrapper.h" />
<ClInclude Include="ResourceHandlerWrapper.h" />
<ClInclude Include="CookieAsyncWrapper.h" />
@@ -59,6 +59,12 @@
<ClCompile Include="Internals\CefBrowserHostWrapper.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Internals\Serialization\V8Serialization.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Internals\Serialization\Primitives.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="vcclr_local.h">
@@ -181,6 +187,15 @@
<ClInclude Include="Internals\CefResponseWrapper.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Internals\Serialization\V8Serialization.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Internals\Serialization\Primitives.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Internals\Messaging\Messages.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClInclude Include="Internals\CefSharpBrowserWrapper.h">
+8 -7
View File
@@ -175,11 +175,12 @@ void CefFrameWrapper::ExecuteJavaScriptAsync(String^ code, String^ scriptUrl, in
Task<JavascriptResponse^>^ CefFrameWrapper::EvaluateScriptAsync(String^ script, Nullable<TimeSpan> timeout)
{
ThrowIfDisposed();
if (_browserAdapter == nullptr)
{
throw gcnew InvalidOperationException(gcnew String(L"IBrowserAdapter is NULL, EvaluateScriptAsync MUST NOT be called from the render process!"));
}
return _browserAdapter->EvaluateScriptAsync(_frame->GetBrowser()->GetIdentifier(), _frame->GetIdentifier(), script, timeout);
auto host = _frame->GetBrowser()->GetHost();
auto client = static_cast<ClientAdapter*>(host->GetClient().get());
return client->EvaluateScriptAsync(_frame->GetBrowser()->GetIdentifier(), _frame->GetIdentifier(), script, timeout);
}
///
@@ -242,7 +243,7 @@ IFrame^ CefFrameWrapper::Parent::get()
auto parent = _frame->GetParent();
if (parent != nullptr && _parentFrame != nullptr)
{
_parentFrame = gcnew CefFrameWrapper(parent, _browserAdapter);
_parentFrame = gcnew CefFrameWrapper(parent);
}
else if (parent == nullptr)
{
@@ -286,7 +287,7 @@ IBrowser^ CefFrameWrapper::Browser::get()
return _owningBrowser;
}
_owningBrowser = gcnew CefSharpBrowserWrapper(_frame->GetBrowser(), _browserAdapter);
_owningBrowser = gcnew CefSharpBrowserWrapper(_frame->GetBrowser());
return _owningBrowser;
}
+2 -4
View File
@@ -24,15 +24,14 @@ namespace CefSharp
{
private:
MCefRefPtr<CefFrame> _frame;
IBrowserAdapter^ _browserAdapter;
IFrame^ _parentFrame;
IBrowser^ _owningBrowser;
Object^ _syncRoot;
bool _disposed;
internal:
CefFrameWrapper::CefFrameWrapper(CefRefPtr<CefFrame> &frame, IBrowserAdapter^ browserAdapter)
: _frame(frame), _browserAdapter(browserAdapter), _disposed(false),
CefFrameWrapper::CefFrameWrapper(CefRefPtr<CefFrame> &frame)
: _frame(frame), _disposed(false),
_parentFrame(nullptr), _owningBrowser(nullptr), _syncRoot(gcnew Object())
{
}
@@ -46,7 +45,6 @@ namespace CefSharp
{
this->!CefFrameWrapper();
_browserAdapter = nullptr;
delete _parentFrame;
delete _owningBrowser;
_parentFrame = nullptr;
+1 -1
View File
@@ -45,7 +45,7 @@ namespace CefSharp
virtual void OnBeforeChildProcessLaunch(CefRefPtr<CefCommandLine> command_line) OVERRIDE
{
if (_cefSettings->WcfEnabled)
if (CefSharpSettings::WcfEnabled)
{
command_line->AppendArgument(StringUtils::ToNative(CefSharpArguments::WcfEnabledArgument));
}
@@ -154,7 +154,7 @@ IFrame^ CefSharpBrowserWrapper::MainFrame::get()
{
ThrowIfDisposed();
auto frame = _browser->GetMainFrame();
return gcnew CefFrameWrapper(frame, _browserAdapter);
return gcnew CefFrameWrapper(frame);
}
///
@@ -164,7 +164,7 @@ IFrame^ CefSharpBrowserWrapper::MainFrame::get()
IFrame^ CefSharpBrowserWrapper::FocusedFrame::get()
{
ThrowIfDisposed();
return gcnew CefFrameWrapper(_browser->GetFocusedFrame(), _browserAdapter);
return gcnew CefFrameWrapper(_browser->GetFocusedFrame());
}
///
@@ -174,7 +174,7 @@ IFrame^ CefSharpBrowserWrapper::FocusedFrame::get()
IFrame^ CefSharpBrowserWrapper::GetFrame(Int64 identifier)
{
ThrowIfDisposed();
return gcnew CefFrameWrapper(_browser->GetFrame(identifier), _browserAdapter);
return gcnew CefFrameWrapper(_browser->GetFrame(identifier));
}
///
@@ -184,7 +184,7 @@ IFrame^ CefSharpBrowserWrapper::GetFrame(Int64 identifier)
IFrame^ CefSharpBrowserWrapper::GetFrame(String^ name)
{
ThrowIfDisposed();
return gcnew CefFrameWrapper(_browser->GetFrame(StringUtils::ToNative(name)), _browserAdapter);
return gcnew CefFrameWrapper(_browser->GetFrame(StringUtils::ToNative(name)));
}
///
@@ -17,13 +17,12 @@ namespace CefSharp
{
private:
MCefRefPtr<CefBrowser> _browser;
IBrowserAdapter^ _browserAdapter;
IBrowserHost^ _browserHost;
bool _disposed;
internal:
CefSharpBrowserWrapper::CefSharpBrowserWrapper(CefRefPtr<CefBrowser> &browser, IBrowserAdapter^ browserAdapter)
: _browser(browser), _browserAdapter(browserAdapter), _disposed(false)
CefSharpBrowserWrapper::CefSharpBrowserWrapper(CefRefPtr<CefBrowser> &browser)
: _browser(browser), _disposed(false)
{
}
@@ -36,7 +35,6 @@ namespace CefSharp
~CefSharpBrowserWrapper()
{
this->!CefSharpBrowserWrapper();
_browserAdapter = nullptr;
delete _browserHost;
_browserHost = nullptr;
_disposed = true;
+81 -17
View File
@@ -18,6 +18,12 @@
#include "CefAuthCallbackWrapper.h"
#include "CefJSDialogCallbackWrapper.h"
#include "CefRequestCallbackWrapper.h"
#include "Serialization\Primitives.h"
#include "Serialization\V8Serialization.h"
#include "Messaging\Messages.h"
using namespace CefSharp::Internals::Messaging;
using namespace CefSharp::Internals::Serialization;
namespace CefSharp
{
@@ -71,7 +77,7 @@ namespace CefSharp
bool createdWrapper = false;
IBrowser^ browserWrapper = GetBrowserWrapper(browser->GetIdentifier(), browser->IsPopup());
CefFrameWrapper frameWrapper(frame, _browserAdapter);
CefFrameWrapper frameWrapper(frame);
auto result = handler->OnBeforePopup(
_browserControl, browserWrapper,
%frameWrapper, StringUtils::ToClr(target_url),
@@ -83,7 +89,7 @@ namespace CefSharp
{
if (browser->IsPopup())
{
auto browserWrapper = gcnew CefSharpBrowserWrapper(browser, _browserAdapter);
auto browserWrapper = gcnew CefSharpBrowserWrapper(browser);
// Add to the list of popup browsers.
_popupBrowsers->Add(browser->GetIdentifier(), browserWrapper);
auto handler = _browserControl->PopupHandler;
@@ -100,6 +106,9 @@ namespace CefSharp
if (static_cast<IBrowserAdapter^>(_browserAdapter) != nullptr)
{
_browserAdapter->OnAfterBrowserCreated(browser->GetIdentifier());
//save callback factory for this browser
//it's only going to be present after browseradapter is initialized
_javascriptCallbackFactories->Add(browser->GetIdentifier(), _browserAdapter->JavascriptCallbackFactory);
}
}
}
@@ -312,14 +321,14 @@ namespace CefSharp
if (popupHandler != nullptr)
{
IBrowser^ browserWrapper = GetBrowserWrapper(browser->GetIdentifier(), true);
CefFrameWrapper frameWrapper(frame, _browserAdapter);
CefFrameWrapper frameWrapper(frame);
popupHandler->OnFrameLoadStart(_browserControl, gcnew FrameLoadStartEventArgs(browserWrapper, %frameWrapper));
}
}
else
{
IBrowser^ browserWrapper = GetBrowserWrapper(browser->GetIdentifier(), false);
CefFrameWrapper frameWrapper(frame, _browserAdapter);
CefFrameWrapper frameWrapper(frame);
_browserControl->OnFrameLoadStart(gcnew FrameLoadStartEventArgs(browserWrapper, %frameWrapper));
}
}
@@ -333,13 +342,13 @@ namespace CefSharp
{
IBrowser^ browserWrapper = GetBrowserWrapper(browser->GetIdentifier(), true);
CefFrameWrapper frameWrapper(frame, _browserAdapter);
CefFrameWrapper frameWrapper(frame);
popupHandler->OnFrameLoadEnd(_browserControl, gcnew FrameLoadEndEventArgs(browserWrapper, %frameWrapper, httpStatusCode));
}
}
else
{
CefFrameWrapper frameWrapper(frame, _browserAdapter);
CefFrameWrapper frameWrapper(frame);
auto browserWrapper = GetBrowserWrapper(browser->GetIdentifier(), false);
_browserControl->OnFrameLoadEnd(gcnew FrameLoadEndEventArgs(browserWrapper, %frameWrapper, httpStatusCode));
}
@@ -353,14 +362,14 @@ namespace CefSharp
if (popupHandler != nullptr)
{
IBrowser^ browserWrapper = GetBrowserWrapper(browser->GetIdentifier(), true);
CefFrameWrapper frameWrapper(frame, _browserAdapter);
CefFrameWrapper frameWrapper(frame);
popupHandler->OnLoadError(_browserControl, browserWrapper,
gcnew LoadErrorEventArgs(%frameWrapper, static_cast<CefErrorCode>(errorCode), StringUtils::ToClr(errorText), StringUtils::ToClr(failedUrl)));
}
}
else
{
CefFrameWrapper frameWrapper(frame, _browserAdapter);
CefFrameWrapper frameWrapper(frame);
_browserControl->OnLoadError(%frameWrapper, (CefErrorCode)errorCode, StringUtils::ToClr(errorText), StringUtils::ToClr(failedUrl));
}
}
@@ -377,7 +386,7 @@ namespace CefSharp
IBrowser^ browserWrapper = GetBrowserWrapper(browser->GetIdentifier(), true);
CefFrameWrapper frameWrapper(frame, _browserAdapter);
CefFrameWrapper frameWrapper(frame);
CefRequestWrapper requestWrapper(request);
return popupHandler->OnBeforeBrowse(_browserControl, browserWrapper, %requestWrapper, isRedirect, %frameWrapper);
}
@@ -390,7 +399,7 @@ namespace CefSharp
}
IBrowser^ browserWrapper = GetBrowserWrapper(browser->GetIdentifier(), false);
CefFrameWrapper frameWrapper(frame, _browserAdapter);
CefFrameWrapper frameWrapper(frame);
CefRequestWrapper requestWrapper(request);
return handler->OnBeforeBrowse(_browserControl, browserWrapper, %frameWrapper, %requestWrapper, isRedirect);
@@ -485,7 +494,7 @@ namespace CefSharp
{
auto managedNewUrl = StringUtils::ToClr(newUrl);
IBrowser^ browserWrapper = GetBrowserWrapper(browser->GetIdentifier(), true);;
CefFrameWrapper frameWrapper(frame, _browserAdapter);
CefFrameWrapper frameWrapper(frame);
popupHandler->OnResourceRedirect(_browserControl, browserWrapper, %frameWrapper, managedNewUrl);
@@ -498,7 +507,7 @@ namespace CefSharp
if (handler != nullptr)
{
auto managedNewUrl = StringUtils::ToClr(newUrl);
CefFrameWrapper frameWrapper(frame, _browserAdapter);
CefFrameWrapper frameWrapper(frame);
handler->OnResourceRedirect(_browserControl, %frameWrapper, managedNewUrl);
@@ -533,7 +542,7 @@ namespace CefSharp
}
IBrowser^ browserWrapper = GetBrowserWrapper(browser->GetIdentifier(), browser->IsPopup());
auto frameWrapper = gcnew CefFrameWrapper(frame, _browserAdapter);
auto frameWrapper = gcnew CefFrameWrapper(frame);
auto requestWrapper = gcnew CefRequestWrapper(request);
auto resourceHandler = factory->GetResourceHandler(_browserControl, browserWrapper, frameWrapper, requestWrapper);
@@ -567,7 +576,7 @@ namespace CefSharp
auto popupHandler = _browserControl->PopupHandler;
if (popupHandler != nullptr)
{
auto frameWrapper = gcnew CefFrameWrapper(frame, _browserAdapter);
auto frameWrapper = gcnew CefFrameWrapper(frame);
auto requestWrapper = gcnew CefRequestWrapper(request);
IBrowser^ browserWrapper = GetBrowserWrapper(browser->GetIdentifier(), true);
@@ -578,7 +587,7 @@ namespace CefSharp
}
else
{
auto frameWrapper = gcnew CefFrameWrapper(frame, _browserAdapter);
auto frameWrapper = gcnew CefFrameWrapper(frame);
auto browserWrapper = GetBrowserWrapper(browser->GetIdentifier(), false);
auto requestWrapper = gcnew CefRequestWrapper(request);
auto requestCallback = gcnew CefRequestCallbackWrapper(callback, frameWrapper, requestWrapper);
@@ -598,7 +607,7 @@ namespace CefSharp
}
auto browserWrapper = GetBrowserWrapper(browser->GetIdentifier(), browser->IsPopup());
auto frameWrapper = gcnew CefFrameWrapper(frame, _browserAdapter);
auto frameWrapper = gcnew CefFrameWrapper(frame);
auto callbackWrapper = gcnew CefAuthCallbackWrapper(callback, frameWrapper);
return handler->GetAuthCredentials(
@@ -615,7 +624,7 @@ namespace CefSharp
// Context menu params
CefContextMenuParamsWrapper contextMenuParamsWrapper(params);
CefFrameWrapper frameWrapper(frame, _browserAdapter);
CefFrameWrapper frameWrapper(frame);
auto result = handler->OnBeforeContextMenu(_browserControl, %frameWrapper, %contextMenuParamsWrapper);
if (!result)
{
@@ -798,5 +807,60 @@ namespace CefSharp
handler->OnDownloadUpdated(browserWrapper, TypeConversion::FromNative(download_item), callbackWrapper);
}
}
bool ClientAdapter::OnProcessMessageReceived(CefRefPtr<CefBrowser> browser, CefProcessId source_process, CefRefPtr<CefProcessMessage> message)
{
auto handled = false;
auto name = message->GetName();
if (name == kEvaluateJavascriptResponse)
{
auto argList = message->GetArgumentList();
auto success = argList->GetBool(0);
auto callbackId = GetInt64(argList, 1);
IJavascriptCallbackFactory^ callbackFactory;
_javascriptCallbackFactories->TryGetValue(browser->GetIdentifier(), callbackFactory);
auto pendingTask = _pendingTaskRepository->RemovePendingTask(callbackId);
if (pendingTask != nullptr)
{
auto response = gcnew JavascriptResponse();
response->Success = success;
if (success)
{
response->Result = DeserializeV8Object(argList, 2, callbackFactory);
}
else
{
response->Message = StringUtils::ToClr(argList->GetString(2));
}
pendingTask->SetResult(response);
}
handled = true;
}
return handled;
}
Task<JavascriptResponse^>^ ClientAdapter::EvaluateScriptAsync(int browserId, int64 frameId, String^ script, Nullable<TimeSpan> timeout)
{
//create a new taskcompletionsource
auto idAndComplectionSource = _pendingTaskRepository->CreatePendingTask(timeout);
auto message = CefProcessMessage::Create(kEvaluateJavascriptRequest);
auto argList = message->GetArgumentList();
argList->SetInt(0, browserId);
SetInt64(frameId, argList, 1);
SetInt64(idAndComplectionSource.Key, argList, 2);
argList->SetString(3, StringUtils::ToNative(script));
_cefBrowser->SendProcessMessage(CefProcessId::PID_RENDERER, message);
return idAndComplectionSource.Value->Task;
}
}
}
+17
View File
@@ -35,9 +35,14 @@ namespace CefSharp
gcroot<IWebBrowserInternal^> _browserControl;
HWND _browserHwnd;
CefRefPtr<CefBrowser> _cefBrowser;
gcroot<Dictionary<int, IBrowser^>^> _popupBrowsers;
gcroot<String^> _tooltip;
gcroot<IBrowserAdapter^> _browserAdapter;
//contains in-progress eval script tasks
gcroot<PendingTaskRepository<JavascriptResponse^>^> _pendingTaskRepository;
//contains js callback factories for each browser
gcroot<Dictionary<int, IJavascriptCallbackFactory^>^> _javascriptCallbackFactories;
void ThrowUnknownPopupBrowser(String^ context)
{
@@ -50,13 +55,20 @@ namespace CefSharp
ClientAdapter(IWebBrowserInternal^ browserControl, IBrowserAdapter^ browserAdapter) :
_browserControl(browserControl),
_popupBrowsers(gcnew Dictionary<int, IBrowser^>()),
_pendingTaskRepository(gcnew PendingTaskRepository<JavascriptResponse^>()),
_javascriptCallbackFactories(gcnew Dictionary<int, IJavascriptCallbackFactory^>()),
_browserAdapter(browserAdapter)
{
}
~ClientAdapter()
{
CloseAllPopups(true);
//this will dispose the repository and cancel all pending tasks
delete _pendingTaskRepository;
_browserControl = nullptr;
_browserHwnd = nullptr;
_cefBrowser = NULL;
@@ -82,6 +94,8 @@ namespace CefSharp
virtual DECL CefRefPtr<CefDialogHandler> GetDialogHandler() OVERRIDE { return this; }
virtual DECL CefRefPtr<CefDragHandler> GetDragHandler() OVERRIDE { return this; }
virtual DECL CefRefPtr<CefGeolocationHandler> GetGeolocationHandler() OVERRIDE { return this; }
virtual DECL bool OnProcessMessageReceived(CefRefPtr<CefBrowser> browser, CefProcessId source_process, CefRefPtr<CefProcessMessage> message) OVERRIDE;
// CefLifeSpanHandler
virtual DECL bool OnBeforePopup(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame,
@@ -158,6 +172,9 @@ namespace CefSharp
virtual void OnDownloadUpdated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefDownloadItem> download_item,
CefRefPtr<CefDownloadItemCallback> callback) OVERRIDE;
//sends out an eval script request to the render process
Task<JavascriptResponse^>^ EvaluateScriptAsync(int browserId, int64 frameId, String^ script, Nullable<TimeSpan> timeout);
IMPLEMENT_REFCOUNTING(ClientAdapter);
};
}
@@ -0,0 +1,23 @@
// Copyright © 2010-2015 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.
#pragma once
#include "include/cef_base.h"
namespace CefSharp
{
namespace Internals
{
namespace Messaging
{
//contains process message names for all handled messages
//Message containing a script to be evaluated
const CefString kEvaluateJavascriptRequest = "EvaluateJavascriptRequest";
//Message containing the result for a given evaluation
const CefString kEvaluateJavascriptResponse = "EvaluateJavascriptDoneResponse";
}
}
}
@@ -0,0 +1,155 @@
// Copyright © 2010-2015 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.
#include "Stdafx.h"
#include "Primitives.h"
#include "include/cef_app.h"
using namespace std;
namespace CefSharp
{
namespace Internals
{
namespace Serialization
{
enum class PrimitiveType : unsigned char
{
INT64,
CEFTIME,
JSCALLBACK
};
template<typename TList, typename TIndex>
bool IsType(PrimitiveType type, CefRefPtr<TList> list, TIndex index)
{
auto result = list->GetType(index) == VTYPE_BINARY;
if (result)
{
underlying_type<PrimitiveType>::type typeRead;
auto binaryValue = list->GetBinary(index);
binaryValue->GetData(&typeRead, sizeof(underlying_type<PrimitiveType>::type), 0);
result = typeRead == static_cast<underlying_type<PrimitiveType>::type>(type);
}
return result;
}
template<typename TList, typename TIndex>
void SetInt64(const int64 &value, CefRefPtr<TList> list, TIndex index)
{
unsigned char mem[1 + sizeof(int64)];
mem[0] = static_cast<unsigned char>(PrimitiveType::INT64);
memcpy(reinterpret_cast<void*>(mem + 1), &value, sizeof(int64));
auto binaryValue = CefBinaryValue::Create(mem, sizeof(mem));
list->SetBinary(index, binaryValue);
}
template<typename TList, typename TIndex>
int64 GetInt64(CefRefPtr<TList> list, TIndex index)
{
int64 result;
auto binaryValue = list->GetBinary(index);
binaryValue->GetData(&result, sizeof(int64), 1);
return result;
}
template<typename TList, typename TIndex>
bool IsInt64(CefRefPtr<TList> list, TIndex index)
{
return IsType(PrimitiveType::INT64, list, index);
}
template<typename TList, typename TIndex>
void SetCefTime(const CefTime &value, CefRefPtr<TList> list, TIndex index)
{
auto doubleT = value.GetDoubleT();
unsigned char mem[1 + sizeof(double)];
mem[0] = static_cast<unsigned char>(PrimitiveType::CEFTIME);
memcpy(reinterpret_cast<void*>(mem + 1), &doubleT, sizeof(double));
auto binaryValue = CefBinaryValue::Create(mem, sizeof(mem));
list->SetBinary(index, binaryValue);
}
template<typename TList, typename TIndex>
CefTime GetCefTime(CefRefPtr<TList> list, TIndex index)
{
double doubleT;
auto binaryValue = list->GetBinary(index);
binaryValue->GetData(&doubleT, sizeof(double), 1);
return CefTime(doubleT);
}
template<typename TList, typename TIndex>
bool IsCefTime(CefRefPtr<TList> list, TIndex index)
{
return IsType(PrimitiveType::CEFTIME, list, index);
}
template<typename TList, typename TIndex>
void SetJsCallback(JavascriptCallback^ value, CefRefPtr<TList> list, TIndex index)
{
auto id = value->Id;
auto browserId = value->BrowserId;
unsigned char mem[1 + sizeof(int) + sizeof(int64)];
mem[0] = static_cast<unsigned char>(PrimitiveType::JSCALLBACK);
memcpy(reinterpret_cast<void*>(mem + 1), &browserId, sizeof(int));
memcpy(reinterpret_cast<void*>(mem + 1 + sizeof(int)), &id, sizeof(int64));
auto binaryValue = CefBinaryValue::Create(mem, sizeof(mem));
list->SetBinary(index, binaryValue);
}
template<typename TList, typename TIndex>
JavascriptCallback^ GetJsCallback(CefRefPtr<TList> list, TIndex index)
{
auto result = gcnew JavascriptCallback();
int64 id;
int browserId;
auto binaryValue = list->GetBinary(index);
binaryValue->GetData(&browserId, sizeof(int), 1);
binaryValue->GetData(&id, sizeof(int64), 1 + sizeof(int));
result->Id = id;
result->BrowserId = browserId;
return result;
}
template<typename TList, typename TIndex>
bool IsJsCallback(CefRefPtr<TList> list, TIndex index)
{
return IsType(PrimitiveType::JSCALLBACK, list, index);
}
template void SetInt64(const int64 &value, CefRefPtr<CefListValue> list, int index);
template void SetInt64(const int64 &value, CefRefPtr<CefDictionaryValue> list, CefString index);
template int64 GetInt64(CefRefPtr<CefListValue> list, int index);
template int64 GetInt64(CefRefPtr<CefDictionaryValue> list, CefString index);
template bool IsInt64(CefRefPtr<CefListValue> list, int index);
template bool IsInt64(CefRefPtr<CefDictionaryValue> list, CefString index);
template void SetCefTime(const CefTime &value, CefRefPtr<CefListValue> list, int index);
template void SetCefTime(const CefTime &value, CefRefPtr<CefDictionaryValue> list, CefString index);
template CefTime GetCefTime(CefRefPtr<CefListValue> list, int index);
template CefTime GetCefTime(CefRefPtr<CefDictionaryValue> list, CefString index);
template bool IsCefTime(CefRefPtr<CefListValue> list, int index);
template bool IsCefTime(CefRefPtr<CefDictionaryValue> list, CefString index);
template void SetJsCallback(JavascriptCallback^ value, CefRefPtr<CefListValue> list, int index);
template void SetJsCallback(JavascriptCallback^ value, CefRefPtr<CefDictionaryValue> list, CefString index);
template JavascriptCallback^ GetJsCallback(CefRefPtr<CefListValue> list, int index);
template JavascriptCallback^ GetJsCallback(CefRefPtr<CefDictionaryValue> list, CefString index);
template bool IsJsCallback(CefRefPtr<CefListValue> list, int index);
template bool IsJsCallback(CefRefPtr<CefDictionaryValue> list, CefString index);
}
}
}
@@ -0,0 +1,37 @@
// Copyright © 2010-2015 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.
#pragma once
namespace CefSharp
{
namespace Internals
{
namespace Serialization
{
//Functions to serialize/deserialize specific types into CefBinaryValue
template<typename TList, typename TIndex>
void SetInt64(const int64 &value, CefRefPtr<TList> list, TIndex index);
template<typename TList, typename TIndex>
int64 GetInt64(CefRefPtr<TList> list, TIndex index);
template<typename TList, typename TIndex>
bool IsInt64(CefRefPtr<TList> list, TIndex index);
template<typename TList, typename TIndex>
void SetCefTime(const CefTime &value, CefRefPtr<TList> list, TIndex index);
template<typename TList, typename TIndex>
CefTime GetCefTime(CefRefPtr<TList> list, TIndex index);
template<typename TList, typename TIndex>
bool IsCefTime(CefRefPtr<TList> list, TIndex index);
template<typename TList, typename TIndex>
void SetJsCallback(JavascriptCallback^ value, CefRefPtr<TList> list, TIndex index);
template<typename TList, typename TIndex>
JavascriptCallback^ GetJsCallback(CefRefPtr<TList> list, TIndex index);
template<typename TList, typename TIndex>
bool IsJsCallback(CefRefPtr<TList> list, TIndex index);
}
}
}
@@ -0,0 +1,93 @@
// Copyright © 2010-2015 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.
#include "Stdafx.h"
#include "V8Serialization.h"
#include "Primitives.h"
namespace CefSharp
{
namespace Internals
{
namespace Serialization
{
template<typename TList, typename TIndex>
Object^ DeserializeV8Object(CefRefPtr<TList> list, TIndex index, IJavascriptCallbackFactory^ javascriptCallbackFactory)
{
Object^ result = nullptr;
auto type = list->GetType(index);
if (type == VTYPE_BOOL)
{
result = list->GetBool(index);
}
else if (type == VTYPE_INT)
{
result = list->GetInt(index);
}
else if (IsInt64(list, index))
{
result = GetInt64(list, index);
}
else if (IsCefTime(list, index))
{
auto cefTime = GetCefTime(list, index);
result = ConvertCefTimeToDateTime(cefTime);
}
else if (IsJsCallback(list, index) && javascriptCallbackFactory != nullptr)
{
auto jsCallbackDto = GetJsCallback(list, index);
result = javascriptCallbackFactory->Create(jsCallbackDto);
}
else if (type == VTYPE_DOUBLE)
{
result = list->GetDouble(index);
}
else if (type == VTYPE_STRING)
{
result = StringUtils::ToClr(list->GetString(index));
}
else if (type == VTYPE_LIST)
{
auto subList = list->GetList(index);
auto array = gcnew List<Object^>(subList->GetSize());
for (auto i = 0; i < subList->GetSize(); i++)
{
array->Add(DeserializeV8Object(subList, i, javascriptCallbackFactory));
}
result = array;
}
else if (type == VTYPE_DICTIONARY)
{
auto dict = gcnew Dictionary<String^, Object^>();
auto subDict = list->GetDictionary(index);
std::vector<CefString> keys;
subDict->GetKeys(keys);
for (auto i = 0; i < keys.size(); i++)
{
dict->Add(StringUtils::ToClr(keys[i]), DeserializeV8Object(subDict, keys[i], javascriptCallbackFactory));
}
result = dict;
}
return result;
}
DateTime ConvertCefTimeToDateTime(CefTime time)
{
auto epoch = time.GetDoubleT();
if (epoch == 0)
{
return DateTime::MinValue;
}
return DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(epoch).ToLocalTime();
}
template Object^ DeserializeV8Object(CefRefPtr<CefListValue> list, int index, IJavascriptCallbackFactory^ javascriptCallbackFactory);
template Object^ DeserializeV8Object(CefRefPtr<CefDictionaryValue> list, CefString index, IJavascriptCallbackFactory^ javascriptCallbackFactory);
}
}
}
@@ -0,0 +1,24 @@
// Copyright © 2010-2015 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.
#pragma once
namespace CefSharp
{
namespace Internals
{
namespace Serialization
{
//Functions to deserialize data returned from the render process.
//Deserializes data into Object from a given index of a CefListValue or CefDictionaryValue
//IJavascriptCallbackFactory implementation should be passed to allow creation of valid javascript callbacks
template<typename TList, typename TIndex>
Object^ DeserializeV8Object(CefRefPtr<TList> list, TIndex index, IJavascriptCallbackFactory^ javascriptCallbackFactory);
//Converts CefTime to DateTime
DateTime ConvertCefTimeToDateTime(CefTime time);
}
}
}
+17 -53
View File
@@ -39,9 +39,7 @@ void ManagedCefBrowserAdapter::LoadUrl(String^ address)
void ManagedCefBrowserAdapter::OnAfterBrowserCreated(int browserId)
{
_wcfEnabled = Cef::WcfEnabled;
if (_wcfEnabled)
if (CefSharpSettings::WcfEnabled)
{
_browserProcessServiceHost = gcnew BrowserProcessServiceHost(_javaScriptObjectRepository, Process::GetCurrentProcess()->Id, browserId);
//NOTE: Attempt to solve timing issue where browser is opened and rapidly disposed. In some cases a call to Open throws
@@ -56,7 +54,7 @@ void ManagedCefBrowserAdapter::OnAfterBrowserCreated(int browserId)
auto browser = _clientAdapter->GetCefBrowser();
if (browser != nullptr)
{
_browserWrapper = gcnew CefSharpBrowserWrapper(browser, this);
_browserWrapper = gcnew CefSharpBrowserWrapper(browser);
}
if (_webBrowserInternal != nullptr)
@@ -284,50 +282,6 @@ void ManagedCefBrowserAdapter::OnMouseWheel(int x, int y, int deltaX, int deltaY
}
}
Task<JavascriptResponse^>^ ManagedCefBrowserAdapter::EvaluateScriptAsync(int browserId, Int64 frameId, String^ script, Nullable<TimeSpan> timeout)
{
if (timeout.HasValue && timeout.Value.TotalMilliseconds > UInt32::MaxValue)
{
throw gcnew ArgumentOutOfRangeException("timeout", "Timeout greater than Maximum allowable value of " + UInt32::MaxValue);
}
if (!_wcfEnabled)
{
throw gcnew InvalidOperationException("To wait for javascript code set WcfEnabled true in CefSettings during initialization.");
}
return _browserProcessServiceHost->EvaluateScriptAsync(browserId, frameId, script, timeout);
}
Task<JavascriptResponse^>^ ManagedCefBrowserAdapter::EvaluateScriptAsync(String^ script, Nullable<TimeSpan> timeout)
{
if (timeout.HasValue && timeout.Value.TotalMilliseconds > UInt32::MaxValue)
{
throw gcnew ArgumentOutOfRangeException("timeout", "Timeout greater than Maximum allowable value of " + UInt32::MaxValue);
}
if (!_wcfEnabled)
{
throw gcnew InvalidOperationException("To wait for javascript code set WcfEnabled true in CefSettings during initialization.");
}
auto browser = _clientAdapter->GetCefBrowser();
if (_browserProcessServiceHost == nullptr || browser == nullptr)
{
return nullptr;
}
auto frame = browser->GetMainFrame();
if (frame == nullptr)
{
return nullptr;
}
return _browserProcessServiceHost->EvaluateScriptAsync(browser->GetIdentifier(), frame->GetIdentifier(), script, timeout);
}
void ManagedCefBrowserAdapter::CreateBrowser(BrowserSettings^ browserSettings, IntPtr sourceHandle, String^ address)
{
HWND hwnd = static_cast<HWND>(sourceHandle.ToPointer());
@@ -381,7 +335,7 @@ void ManagedCefBrowserAdapter::NotifyScreenInfoChanged()
void ManagedCefBrowserAdapter::RegisterJsObject(String^ name, Object^ object, bool lowerCaseJavascriptNames)
{
if (!_wcfEnabled)
if (!CefSharpSettings::WcfEnabled)
{
throw gcnew InvalidOperationException("To enable synchronous JS bindings set WcfEnabled true in CefSettings during initialization.");
}
@@ -505,7 +459,7 @@ IFrame^ ManagedCefBrowserAdapter::GetMainFrame()
{
return nullptr;
}
return gcnew CefFrameWrapper(browser->GetMainFrame(), this);
return gcnew CefFrameWrapper(browser->GetMainFrame());
}
///
@@ -520,7 +474,7 @@ IFrame^ ManagedCefBrowserAdapter::GetFocusedFrame()
return nullptr;
}
return gcnew CefFrameWrapper(browser->GetFocusedFrame(), this);
return gcnew CefFrameWrapper(browser->GetFocusedFrame());
}
///
@@ -540,7 +494,7 @@ IFrame^ ManagedCefBrowserAdapter::GetFrame(System::Int64 identifier)
return nullptr;
}
return gcnew CefFrameWrapper(result, this);
return gcnew CefFrameWrapper(result);
}
///
@@ -560,7 +514,7 @@ IFrame^ ManagedCefBrowserAdapter::GetFrame(String^ name)
return nullptr;
}
return gcnew CefFrameWrapper(result, this);
return gcnew CefFrameWrapper(result);
}
/// <summary>
@@ -571,3 +525,13 @@ IBrowser^ ManagedCefBrowserAdapter::GetBrowser()
{
return _browserWrapper;
}
IJavascriptCallbackFactory^ ManagedCefBrowserAdapter::JavascriptCallbackFactory::get()
{
IJavascriptCallbackFactory^ result = nullptr;
if (_browserProcessServiceHost != nullptr)
{
result = _browserProcessServiceHost->JavascriptCallbackFactory;
}
return result;
}
+6 -4
View File
@@ -34,7 +34,6 @@ namespace CefSharp
JavascriptObjectRepository^ _javaScriptObjectRepository;
IBrowser^ _browserWrapper;
bool _isDisposed;
bool _wcfEnabled;
private:
// Private keyboard functions:
@@ -79,7 +78,7 @@ namespace CefSharp
delete _browserWrapper;
_browserWrapper = nullptr;
if (_wcfEnabled)
if (CefSharpSettings::WcfEnabled)
{
_browserProcessServiceHost->Close();
_browserProcessServiceHost = nullptr;
@@ -108,8 +107,6 @@ namespace CefSharp
void OnMouseMove(int x, int y, bool mouseLeave, CefEventFlags modifiers);
void OnMouseButton(int x, int y, int mouseButtonType, bool mouseUp, int clickCount, CefEventFlags modifiers);
void OnMouseWheel(int x, int y, int deltaX, int deltaY);
virtual Task<JavascriptResponse^>^ EvaluateScriptAsync(int browserId, Int64 frameId, String^ script, Nullable<TimeSpan> timeout);
virtual Task<JavascriptResponse^>^ EvaluateScriptAsync(String^ script, Nullable<TimeSpan> timeout);
void Resize(int width, int height);
void NotifyMoveOrResizeStarted();
void NotifyScreenInfoChanged();
@@ -165,5 +162,10 @@ namespace CefSharp
/// </summary>
/// <returns>Gets the current instance or null</returns>
virtual IBrowser^ GetBrowser();
virtual property IJavascriptCallbackFactory^ JavascriptCallbackFactory
{
CefSharp::Internals::IJavascriptCallbackFactory^ get();
}
};
}
+2 -2
View File
@@ -32,8 +32,8 @@ namespace CefSharp
// NOTE: NOT supplying a browser adapter here means they currently
// can't issue a JavaScript ExecuteScriptAsync call from any IFrame generated via browserWrapper
// and IFrame itself.
auto browserWrapper = gcnew CefSharpBrowserWrapper(browser, nullptr);
auto frameWrapper = gcnew CefFrameWrapper(frame, nullptr);
auto browserWrapper = gcnew CefSharpBrowserWrapper(browser);
auto frameWrapper = gcnew CefFrameWrapper(frame);
auto requestWrapper = gcnew CefRequestWrapper(request);
auto handler = _factory->Create(browserWrapper, frameWrapper, StringUtils::ToClr(schemeName), requestWrapper);
+1 -1
View File
@@ -29,7 +29,7 @@ namespace CefSharp.Example
var settings = new CefSettings();
settings.RemoteDebuggingPort = 8088;
//This will disable WCF (Effectively disabling JavascriptBinding and EvaluateScriptAsync)
//settings.WcfEnabled = false;
//CefSharpSettings.WcfEnabled = false;
//The location where cache data will be stored on disk. If empty an in-memory cache will be used for some features and a temporary disk cache for others.
//HTML5 databases such as localStorage will only persist across sessions if a cache path is specified.
settings.CachePath = "cache";
-5
View File
@@ -228,11 +228,6 @@ namespace CefSharp.OffScreen
return completionSource.Task;
}
public Task<JavascriptResponse> EvaluateScriptAsync(string script, TimeSpan? timeout = null)
{
return managedCefBrowserAdapter.EvaluateScriptAsync(script, timeout);
}
public void Load(string url)
{
Address = url;
-10
View File
@@ -155,16 +155,6 @@ namespace CefSharp.WinForms
managedCefBrowserAdapter.RegisterJsObject(name, objectToBind, camelCaseJavascriptNames);
}
public Task<JavascriptResponse> EvaluateScriptAsync(string script)
{
return EvaluateScriptAsync(script, timeout: null);
}
public Task<JavascriptResponse> EvaluateScriptAsync(string script, TimeSpan? timeout)
{
return managedCefBrowserAdapter.EvaluateScriptAsync(script, timeout);
}
public void SendMouseWheelEvent(int x, int y, int deltaX, int deltaY)
{
managedCefBrowserAdapter.OnMouseWheel(x, y, deltaX, deltaY);
@@ -15,7 +15,7 @@ namespace CefSharp.Wpf.Example.Views
InitializeComponent();
browser.RequestHandler = new RequestHandler();
if (Cef.WcfEnabled)
if (CefSharpSettings.WcfEnabled)
{
browser.RegisterJsObject("bound", new BoundObject());
}
-10
View File
@@ -1292,16 +1292,6 @@ namespace CefSharp.Wpf
managedCefBrowserAdapter.RegisterJsObject(name, objectToBind, camelCaseJavascriptNames);
}
public Task<JavascriptResponse> EvaluateScriptAsync(string script)
{
return EvaluateScriptAsync(script, timeout: null);
}
public Task<JavascriptResponse> EvaluateScriptAsync(string script, TimeSpan? timeout)
{
return managedCefBrowserAdapter.EvaluateScriptAsync(script, timeout);
}
/// <summary>
/// Raises Rendering event
/// </summary>
+4
View File
@@ -92,6 +92,7 @@
<Compile Include="CefFileDialogMode.cs" />
<Compile Include="CefJsDialogType.cs" />
<Compile Include="CefReturnValue.cs" />
<Compile Include="CefSharpSettings.cs" />
<Compile Include="CefThreadIds.cs" />
<Compile Include="Cookie.cs" />
<Compile Include="IAuthCallback.cs" />
@@ -112,11 +113,14 @@
<SubType>Code</SubType>
</Compile>
<Compile Include="CefCursorType.cs" />
<Compile Include="Internals\IJavascriptCallbackFactory.cs" />
<Compile Include="Internals\IntPtrExtensions.cs" />
<Compile Include="Internals\JavascriptCallbackFactory.cs" />
<Compile Include="Internals\JavascriptCallbackProxy.cs" />
<Compile Include="Internals\JavascriptCallback.cs" />
<Compile Include="Internals\JavascriptCallbackEndpointBehavior.cs" />
<Compile Include="Internals\JavascriptCallbackSurrogate.cs" />
<Compile Include="Internals\PendingTaskRepository.cs" />
<Compile Include="Internals\ReflectionUtils.cs" />
<Compile Include="IPopupHandler.cs" />
<Compile Include="IRequestCallback.cs" />
+21
View File
@@ -0,0 +1,21 @@
// Copyright © 2010-2015 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.
namespace CefSharp
{
public static class CefSharpSettings
{
static CefSharpSettings()
{
WcfEnabled = true;
}
/// <summary>
/// WCF is used by JavascriptBinding and EvaluateScriptAsync.
/// Disabling effectively disables both of these features.
/// Defaults to true
/// </summary>
public static bool WcfEnabled { get; set; }
}
}
-10
View File
@@ -3,7 +3,6 @@
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Threading.Tasks;
namespace CefSharp
{
@@ -60,15 +59,6 @@ namespace CefSharp
/// <param name="camelCaseJavascriptNames">camel case the javascript names of properties/methods, defaults to true</param>
void RegisterJsObject(string name, object objectToBind, bool camelCaseJavascriptNames = true);
/// <summary>
/// Execute some Javascript code in the context of this WebBrowser, and return the result of the evaluation
/// in an Async fashion
/// </summary>
/// <param name="script">The Javascript code that should be executed.</param>
/// <param name="timeout">The timeout after which the Javascript code execution should be aborted.</param>
/// <returns>A Task that can be awaited to perform the script execution</returns>
Task<JavascriptResponse> EvaluateScriptAsync(string script, TimeSpan? timeout = null);
/// <summary>
/// Implement <see cref="IDialogHandler"/> and assign to handle dialog events.
/// </summary>
@@ -15,6 +15,7 @@ namespace CefSharp.Internals
{
private const long OneHundredAndTwentyEightMegaBytesInBytes = 128*1024*1024;
public IJavascriptCallbackFactory JavascriptCallbackFactory { get; private set; }
public JavascriptObjectRepository JavascriptObjectRepository { get; private set; }
private TaskCompletionSource<OperationContext> operationContextTaskCompletionSource = new TaskCompletionSource<OperationContext>();
@@ -22,6 +23,7 @@ namespace CefSharp.Internals
: base(typeof(BrowserProcessService), new Uri[0])
{
JavascriptObjectRepository = javascriptObjectRepository;
JavascriptCallbackFactory = new JavascriptCallbackFactory(new WeakReference(this));
var serviceName = RenderprocessClientFactory.GetServiceName(parentProcessId, browserId);
@@ -49,20 +51,6 @@ namespace CefSharp.Internals
operationContextTaskCompletionSource.SetResult(operationContext);
}
public Task<JavascriptResponse> EvaluateScriptAsync(int browserId, long frameId, string script, TimeSpan? timeout)
{
var operationContextTask = operationContextTaskCompletionSource.Task;
// Use TaskScheduler.Default to ensure that the work occurs
// on a background thread.
return operationContextTask.ContinueWith(t =>
{
var context = t.Result;
var renderProcess = context.GetCallbackChannel<IRenderProcess>();
var asyncResult = renderProcess.BeginEvaluateScriptAsync(browserId, frameId, script, timeout, null, null);
return Task.Factory.FromAsync<JavascriptResponse>(asyncResult, renderProcess.EndEvaluateScriptAsync);
}, TaskScheduler.Default).Unwrap();
}
protected override void OnClose(TimeSpan timeout)
{
var task = operationContextTaskCompletionSource.Task;
+1 -5
View File
@@ -2,9 +2,6 @@
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Threading.Tasks;
namespace CefSharp.Internals
{
/// <summary>
@@ -13,8 +10,7 @@ namespace CefSharp.Internals
/// </summary>
public interface IBrowserAdapter
{
Task<JavascriptResponse> EvaluateScriptAsync(string script, TimeSpan? timeout);
Task<JavascriptResponse> EvaluateScriptAsync(int browserId, Int64 frameId, string script, TimeSpan? timeout);
IJavascriptCallbackFactory JavascriptCallbackFactory { get; }
void OnAfterBrowserCreated(int browserId);
IBrowser GetBrowser();
}
@@ -0,0 +1,14 @@
// Copyright © 2010-2015 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.
namespace CefSharp.Internals
{
/// <summary>
/// Interface to convert a JavascriptCallback dto to a callable implementation.
/// </summary>
public interface IJavascriptCallbackFactory
{
IJavascriptCallback Create(JavascriptCallback callback);
}
}
-5
View File
@@ -11,11 +11,6 @@ namespace CefSharp.Internals
[ServiceContract]
public interface IRenderProcess
{
[OperationContract(AsyncPattern=true)]
IAsyncResult BeginEvaluateScriptAsync(int browserId, long frameId, string script, TimeSpan? timeout, AsyncCallback callback, object state);
JavascriptResponse EndEvaluateScriptAsync(IAsyncResult result);
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginJavascriptCallbackAsync(int browserId, long callbackId, object[] parameters, TimeSpan? timeout, AsyncCallback callback, object state);
@@ -16,7 +16,6 @@ namespace CefSharp.Internals
private static readonly List<string> Methods = new List<string>
{
ReflectionUtils.GetMethodName<IBrowserProcess>(p => p.CallMethod(0, null, null)),
ReflectionUtils.GetMethodName<IRenderProcess>(p => p.BeginEvaluateScriptAsync(0, 0, null, null, null, null)).Substring(5),
ReflectionUtils.GetMethodName<IRenderProcess>(p => p.BeginJavascriptCallbackAsync(0, 0, null, null, null, null)).Substring(5),
};
@@ -0,0 +1,19 @@
using System;
namespace CefSharp.Internals
{
public class JavascriptCallbackFactory : IJavascriptCallbackFactory
{
private readonly WeakReference browserProcessServiceHost;
public JavascriptCallbackFactory(WeakReference browserProcessServiceHost)
{
this.browserProcessServiceHost = browserProcessServiceHost;
}
public IJavascriptCallback Create(JavascriptCallback callback)
{
return new JavascriptCallbackProxy(callback.Id, callback.BrowserId, browserProcessServiceHost);
}
}
}
@@ -10,13 +10,11 @@ using System.Runtime.Serialization;
namespace CefSharp.Internals
{
internal sealed class JavascriptCallbackSurrogate : IDataContractSurrogate
internal sealed class JavascriptCallbackSurrogate : JavascriptCallbackFactory, IDataContractSurrogate
{
private readonly WeakReference browserProcessWeakReference;
public JavascriptCallbackSurrogate(WeakReference browserProcessWeakReference)
:base(browserProcessWeakReference)
{
this.browserProcessWeakReference = browserProcessWeakReference;
}
public Type GetDataContractType(Type type)
@@ -39,7 +37,7 @@ namespace CefSharp.Internals
var dto = obj as JavascriptCallback;
if (dto != null)
{
result = new JavascriptCallbackProxy(dto.Id, dto.BrowserId, browserProcessWeakReference);
result = Create(dto);
}
return result;
}
@@ -0,0 +1,64 @@
// Copyright © 2010-2015 The CefSharp Project. 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.Threading;
using System.Threading.Tasks;
namespace CefSharp.Internals
{
/// <summary>
/// Class to store TaskCompletionSources indexed by a unique id.
/// </summary>
/// <typeparam name="TResult">The type of the result produced by the tasks held.</typeparam>
public sealed class PendingTaskRepository<TResult>
{
private readonly ConcurrentDictionary<long, TaskCompletionSource<TResult>> pendingTasks =
new ConcurrentDictionary<long, TaskCompletionSource<TResult>>();
//should only be accessed by Interlocked.Increment
private long lastId;
/// <summary>
/// Creates a new pending task with a timeout.
/// </summary>
/// <param name="timeout">The maximum running time of the task.</param>
/// <returns>The unique id of the newly created pending task and the newly created <see cref="TaskCompletionSource{TResult}"/>.</returns>
public KeyValuePair<long, TaskCompletionSource<TResult>> CreatePendingTask(TimeSpan? timeout = null)
{
var taskCompletionSource = new TaskCompletionSource<TResult>();
var id = Interlocked.Increment(ref lastId);
pendingTasks.TryAdd(id, taskCompletionSource);
if (timeout.HasValue)
{
Timer timer = null;
timer = new Timer(state =>
{
timer.Dispose();
RemovePendingTask(id);
taskCompletionSource.TrySetCanceled();
}, null, timeout.Value, TimeSpan.FromMilliseconds(-1));
}
return new KeyValuePair<long, TaskCompletionSource<TResult>>(id, taskCompletionSource);
}
/// <summary>
/// Gets and removed pending task by id.
/// </summary>
/// <param name="id">Unique id of the pending task.</param>
/// <returns>
/// The <see cref="TaskCompletionSource{TResult}"/> associated with the given id.
/// </returns>
public TaskCompletionSource<TResult> RemovePendingTask(long id)
{
TaskCompletionSource<TResult> result;
pendingTasks.TryRemove(id, out result);
return result;
}
}
}
+15
View File
@@ -538,6 +538,21 @@ namespace CefSharp
cefBrowser.AddWordToDictionary(word);
}
public static Task<JavascriptResponse> EvaluateScriptAsync(this IWebBrowser browser, string script, TimeSpan? timeout = null)
{
if (timeout.HasValue && timeout.Value.TotalMilliseconds > UInt32.MaxValue)
{
throw new ArgumentOutOfRangeException("timeout", "Timeout greater than Maximum allowable value of " + UInt32.MaxValue);
}
using (var frame = browser.GetMainFrame())
{
ThrowExceptionIfFrameNull(frame);
return frame.EvaluateScriptAsync(script, timeout);
}
}
private static void ThrowExceptionIfFrameNull(IFrame frame)
{
if (frame == null)