Files
cefsharp/CefSharp.Core/Internals/JavascriptCallbackImpl.cpp
T

96 lines
3.4 KiB
C++

// 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 "JavascriptCallbackImpl.h"
#include "Messaging/Messages.h"
#include "Serialization/Primitives.h"
#include "Serialization/V8Serialization.h"
namespace CefSharp
{
namespace Internals
{
using namespace Messaging;
using namespace Serialization;
JavascriptCallbackImpl::JavascriptCallbackImpl(JavascriptCallback^ callback, PendingTaskRepository<JavascriptResponse^>^ pendingTasks, WeakReference^ browserWrapper)
:_callback(callback), _pendingTasks(pendingTasks)
{
_browserWrapper = browserWrapper;
}
Task<JavascriptResponse^>^ JavascriptCallbackImpl::ExecuteAsync(array<Object^>^ parameters)
{
auto browser = GetBrowser();
if (browser.get())
{
auto doneCallback = _pendingTasks->CreatePendingTask(Nullable<TimeSpan>());
auto callbackMessage = CreateCallMessage(doneCallback.Key, parameters);
browser->SendProcessMessage(CefProcessId::PID_RENDERER, callbackMessage);
return doneCallback.Value->Task;
}
else
{
throw gcnew InvalidOperationException("Browser instance is null.");
}
}
CefRefPtr<CefProcessMessage> JavascriptCallbackImpl::CreateCallMessage(int64 doneCallbackId, array<Object^>^ parameters)
{
auto result = CefProcessMessage::Create(kJavascriptCallbackRequest);
auto browser = GetBrowser();
auto argList = result->GetArgumentList();
argList->SetInt(0, browser->GetIdentifier());
SetInt64(_callback->Id, argList, 1);
SetInt64(doneCallbackId, argList, 2);
auto paramList = CefListValue::Create();
for (int i = 0; i < parameters->Length; i++)
{
auto param = parameters[i];
SerializeV8Object(param, paramList, i);
}
argList->SetList(3, paramList);
return result;
}
CefRefPtr<CefProcessMessage> JavascriptCallbackImpl::CreateDestroyMessage()
{
auto result = CefProcessMessage::Create(kJavascriptCallbackDestroyRequest);
auto argList = result->GetArgumentList();
SetInt64(_callback->Id, argList, 0);
return result;
}
CefRefPtr<CefBrowser> JavascriptCallbackImpl::GetBrowser()
{
CefRefPtr<CefBrowser> result;
if (_browserWrapper->IsAlive)
{
auto wrapper = static_cast<CefSharpBrowserWrapper^>(_browserWrapper->Target);
result = wrapper == nullptr ? nullptr : wrapper->Browser.get();
}
return result;
}
void JavascriptCallbackImpl::DisposedGuard()
{
if (_disposed)
{
throw gcnew ObjectDisposedException("JavascriptCallbackImpl");
}
}
JavascriptCallbackImpl::!JavascriptCallbackImpl()
{
auto browser = GetBrowser();
if (browser.get())
{
browser->SendProcessMessage(CefProcessId::PID_RENDERER, CreateDestroyMessage());
}
_disposed = true;
}
}
}