6#include <Ultralight/CAPI/CAPI_JSAPI.h>
7#include <Ultralight/CAPI/CAPI_JSRuntime.h>
8#include <Ultralight/CAPI/CAPI_JSValue.h>
9#include <Ultralight/CAPI/CAPI_String.h>
11#include <Ultralight/detail/Exceptions.h>
21#include <initializer_list>
56 size_t index =
static_cast<size_t>(type);
127 : ctx_(other.ctx_), callback_(other.callback_), user_data_(other.user_data_) {
135 if (
this != &other) {
138 callback_ = other.callback_;
139 user_data_ = other.user_data_;
154 ulDestroyJSContext(ctx_);
161 explicit operator bool()
const {
return ctx_ !=
nullptr; }
170 : ctx_(ctx), callback_(callback), user_data_(user_data) {}
177 ulJSContextRemoveDestroyedCallback(ctx_, callback_, user_data_);
184 user_data_ =
nullptr;
188 ULJSContextDestroyedCallback callback_ =
nullptr;
189 void* user_data_ =
nullptr;
279 explicit Context(
View* view) : handle_(view ? view->GetJSContext() : nullptr) {}
288 : handle_(value.
raw() ? ulJSValueGetContext(value.
raw()) : nullptr) {}
313 return Context(handle ? ulCreateJSContextRef(handle) :
nullptr);
320 : handle_(other.handle_ ? ulCreateJSContextRef(other.handle_) : nullptr) {}
325 Context(
Context&& other) noexcept : handle_(other.handle_) { other.handle_ =
nullptr; }
331 std::swap(handle_, other.handle_);
343 explicit operator bool()
const {
return handle_ && ulJSContextIsAlive(handle_); }
348 bool IsEmpty()
const {
return handle_ ==
nullptr; }
356 bool IsAlive()
const {
return handle_ && ulJSContextIsAlive(handle_); }
369 const char* source_url =
nullptr)
const {
371 return detail::EmptyHandleError();
372 ULString source = ulCreateStringUTF8(script.data(), script.size());
373 ULJSValue exception =
nullptr;
374 ULJSValue result = ulJSContextEvaluate(handle_, source, source_url, &exception);
375 ulDestroyString(source);
399 template <
typename T>
402 const char* source_url =
nullptr)
const {
405 return Unexpected<Error>(std::move(completion).error());
406 return completion.value().To<T>();
415 return Value::Adopt(ulJSContextGetGlobalObject(handle_));
436 ref.source_gone_ = handle_ && global.
IsEmpty();
450 template <
typename T>
452 using U = std::decay_t<T>;
453 detail::AssertInteropHeader<U>();
455 "no js::TypeTraits for T: use a supported built-in, make it a plain "
456 "aggregate struct, or specialize js::TypeTraits for it");
479 std::vector<ULJSValue>
raw(count);
480 for (
size_t i = 0; i < count; i++)
481 raw[i] = elements[i].
raw();
482 return Value::Adopt(ulCreateJSArray(handle_, count ?
raw.data() :
nullptr, count));
493 return MakeArray(elements.begin(), elements.size());
504 return MakeArray(elements.data(), elements.size());
521 return detail::EmptyHandleError();
522 ULString text = ulCreateStringUTF8(json.data(), json.length());
523 ULJSValue exception =
nullptr;
524 ULJSValue result = ulCreateJSValueFromJSON(handle_, text, &exception);
525 ulDestroyString(text);
555 template <
typename F>
557 using Fn = std::decay_t<F>;
558 static_assert(std::is_invocable_v<Fn&> || std::is_invocable_v<Fn&, Context&>,
559 "js::Context::PostTask takes a callable invocable with nothing or with "
561 ulJSContextPostTask(handle_, &TaskThunk<Fn>,
new Fn(std::forward<F>(task)),
562 &DeleteCallable<Fn>);
579 ULJSPromiseResolver
raw =
nullptr;
580 ULJSValue promise = handle_ ? ulCreateJSPromise(handle_, &
raw) :
nullptr;
602 Value::Adopt(detail::WrapBufferThrough(handle_, buffer, [&](ULBuffer shared) {
603 return ulCreateJSArrayBufferFromBuffer(handle_, shared);
629 template <
typename T>
632 Value::Adopt(ulCreateJSTypedArray(handle_, detail::kTypedArrayTypeOf<T>, length)));
647 template <
typename T>
652 Value::Adopt(detail::WrapBufferThrough(handle_, buffer, [&](ULBuffer shared) {
653 return ulCreateJSTypedArrayFromBuffer(handle_, detail::kTypedArrayTypeOf<T>, shared);
681 template <
typename Fn>
683 using F = std::decay_t<Fn>;
684 using Traits = detail::CallableTraits<F>;
685 using Shape = detail::ParamShape<typename Traits::Params>;
686 static_assert(!Shape::kHasResolver
687 && !detail::kIsAsyncReturn<typename Traits::Return>,
688 "MakeFunction binds synchronous callables; bind async forms (js::Task, "
689 "trailing js::Resolver) through js::API");
690 [&]<
size_t... Is>(std::index_sequence<Is...>) {
691 (detail::ValidateParam<std::tuple_element_t<Is, typename Shape::Converted>>(), ...);
692 }(std::make_index_sequence<Shape::kCount> {});
695 auto* bound =
new detail::BoundCallable<F> { std::forward<Fn>(fn),
696 std::string(name ? name :
""), {}, {} };
697 return Value::Adopt(ulCreateJSFunction(handle_, name, &detail::SyncTrampoline<F>, bound,
698 &detail::DestroyBoundCallable<F>));
717 return Value::Adopt(handle_ ? ulCreateJSDate(handle_, ms_since_epoch) :
nullptr);
748 template <
typename F>
750 using Fn = std::decay_t<F>;
751 static_assert(std::is_invocable_v<Fn&> || std::is_invocable_v<Fn&, Context&>,
752 "js::Context::OnDestroyed takes a callable invocable with nothing or with "
754 if (!handle_ || !ulJSContextIsAlive(handle_))
756 auto* callable =
new Fn(std::forward<F>(fn));
759 ulJSContextAddDestroyedCallback(handle_, &DestroyedThunk<Fn>, callable,
760 &DeleteCallable<Fn>);
761 return DestroyedGuard(ulCreateJSContextRef(handle_), &DestroyedThunk<Fn>, callable);
775 ULJSHandleStats raw_stats = {};
776 if (handle_ && ulJSContextGetHandleStats(handle_, &raw_stats)) {
778 for (
size_t i = 0; i < kULJSType_Count; i++)
808 template <
typename Fn>
809 static void InvokeWithContext(
void* user_data,
ULJSContext ctx,
const char* where) {
810 Fn& fn = *
static_cast<Fn*
>(user_data);
811 ultralight::detail::CallCatchingExceptions(
813 if constexpr (std::is_invocable_v<Fn&, Context&>) {
820 [where](
const char* what) { detail::LogNativeException(where, what); });
823 template <
typename Fn>
824 static void TaskThunk(
void* user_data,
ULJSContext ctx) {
825 InvokeWithContext<Fn>(user_data, ctx,
"js::Context::PostTask");
828 template <
typename Fn>
829 static void DestroyedThunk(
void* user_data,
ULJSContext ctx) {
830 InvokeWithContext<Fn>(user_data, ctx,
"js::Context::OnDestroyed");
833 template <
typename Fn>
834 static void DeleteCallable(
void* user_data) {
835 delete static_cast<Fn*
>(user_data);
struct C_JSContext * ULJSContext
Opaque handle to a JavaScript execution context (one page's script world in one View).
Definition View.h:25
A nullable smart pointer.
Definition RefPtr.h:126
Web-page container rendered to an offscreen surface.
Definition View.h:483
Handle to a JavaScript ArrayBuffer for sharing raw binary memory with the page.
Definition Buffer.h:88
ArrayBuffer()=default
Create an empty ArrayBuffer wrapper.
Context context() const
Get the calling context, to create values in it or to keep it after the call:
Definition Context.h:841
JavaScript execution environment for a page.
Definition Context.h:263
Value::Ref operator[](const char *name) const
Access a property of the global object (ctx["fn"](args) is the same as ctx.GlobalObject()["fn"](args)...
Definition Context.h:432
Value MakeArray(std::span< const Value > elements) const
Create a new JavaScript Array from a range (eg, a std::vector<js::Value>).
Definition Context.h:503
TypedArray< T > MakeTypedArray(const RefPtr< ultralight::Buffer > &buffer) const
Create a typed array of elements of type T that shares a Buffer's bytes with JavaScript without copyi...
Definition Context.h:648
Value Make(T &&value) const
Convert a C++ value to a JavaScript value through js::TypeTraits.
Definition Context.h:451
Value GlobalObject() const
Get the global object.
Definition Context.h:414
ArrayBuffer MakeArrayBuffer(const RefPtr< ultralight::Buffer > &buffer) const
Create an ArrayBuffer that shares a Buffer's bytes with JavaScript without copying.
Definition Context.h:598
Value MakeArray(const Value *elements, size_t count) const
Create a new JavaScript Array.
Definition Context.h:476
Result< Value > Evaluate(std::string_view script, const char *source_url=nullptr) const
Run a script and get its completion value.
Definition Context.h:368
Value MakeArray(std::initializer_list< Value > elements) const
Create a new JavaScript Array from a brace list (eg, ctx.MakeArray({ a, b })).
Definition Context.h:492
Context(const Context &other)
Copy constructor (refers to the same context).
Definition Context.h:319
ULJSContext raw() const
Get the C API handle without transferring ownership.
Definition Context.h:790
Context()=default
Create an empty Context.
Context & operator=(Context other) noexcept
Assignment (copies or moves other into this Context).
Definition Context.h:330
Context(Context &&other) noexcept
Move constructor (other becomes empty).
Definition Context.h:325
static Context Adopt(ULJSContext handle)
Take ownership of a context handle from the C API.
Definition Context.h:302
bool IsEmpty() const
Whether or not this Context holds nothing.
Definition Context.h:348
bool IsAlive() const
Whether or not this Context's page is still alive (the same test as operator bool).
Definition Context.h:356
HandleStats GetHandleStats() const
Count the live handles on this context, for finding leaks.
Definition Context.h:773
Value MakeObject() const
Create a new empty JavaScript object.
Definition Context.h:465
PendingPromise MakePromise() const
Create a pending Promise and the Resolver that settles it, to hand a Promise to the page outside a bo...
Definition Context.h:578
Context(View *view)
Get the context of a View's main frame.
Definition Context.h:279
Value MakeFunction(const char *name, Fn &&fn) const
Create a JavaScript function backed by a C++ callable, to hand to the page (eg, as a callback).
Definition Context.h:682
Context(const Value &value)
Get the context a value belongs to.
Definition Context.h:287
Value MakeDate(double ms_since_epoch) const
Create a JavaScript Date (like new Date(ms_since_epoch)).
Definition Context.h:716
~Context()
Destructor (releases this handle).
Definition Context.h:338
void PostTask(F &&task) const
Run a function with this context during a later Renderer::Update().
Definition Context.h:556
DestroyedGuard OnDestroyed(F &&fn) const
Run a function when this context goes away, to clear anything you keep per page.
Definition Context.h:749
Result< T > Evaluate(std::string_view script, const char *source_url=nullptr) const
Run a script and convert its completion value to a C++ type (see Value::To()).
Definition Context.h:401
Result< Value > MakeFromJSON(std::string_view json) const
Create a value from JSON text (the reverse of Value::ToJSON()):
Definition Context.h:519
static Context FromBorrowed(ULJSContext handle)
Add a reference to a context handle the library owns (eg, the context a C API callback receives) so y...
Definition Context.h:312
ArrayBuffer MakeArrayBuffer(const void *bytes, size_t length) const
Create an ArrayBuffer holding a copy of the given bytes.
Definition Context.h:617
ULJSContext LeakRef()
Give up ownership of the C API handle and return it.
Definition Context.h:797
TypedArray< T > MakeTypedArray(size_t length) const
Create a typed array of zero-filled elements of type T (eg, MakeTypedArray<float>(4) creates a Float3...
Definition Context.h:630
A callback registered with Context::OnDestroyed(), tied to a C++ object's lifetime.
Definition Context.h:111
DestroyedGuard(DestroyedGuard &&other) noexcept
Move constructor (other becomes unarmed).
Definition Context.h:126
DestroyedGuard & operator=(DestroyedGuard &&other) noexcept
Move assignment (removes the current callback first if armed, and other becomes unarmed).
Definition Context.h:134
void Release()
Disarm the guard without removing the callback (it still runs when the context goes away).
Definition Context.h:153
DestroyedGuard(const DestroyedGuard &)=delete
friend class Context
Definition Context.h:164
~DestroyedGuard()
Destructor (removes the callback if the guard is armed).
Definition Context.h:121
DestroyedGuard & operator=(const DestroyedGuard &)=delete
DestroyedGuard()=default
Create an unarmed guard (removes nothing).
static Error AdoptException(ULJSValue exception)
Create an error from a JavaScript exception, taking ownership of the handle.
Definition Error.h:131
static Error PageGone()
Create a page-gone error (is_page_gone() returns true).
Definition Error.h:122
A handle that settles a JavaScript Promise.
Definition Resolver.h:97
static Resolver Adopt(ULJSPromiseResolver handle)
Take ownership of a resolver handle from the C API.
Definition Resolver.h:120
Handle to a JavaScript typed array on a page.
Definition Buffer.h:203
TypedArray()=default
Create an empty TypedArray wrapper.
A reference to a property of a Value (returned by Value::operator[]).
Definition Value.h:1419
A handle to a live JavaScript value.
Definition Value.h:276
static Value Adopt(ULJSValue handle)
Take ownership of a handle from the C API without adding a reference.
Definition Value.h:1242
bool IsEmpty() const
Whether or not this Value holds nothing (see "Handle States" above).
Definition Value.h:315
Value()
Create an empty Value.
Definition Value.h:281
Whether or not js::TypeTraits can convert T (ignoring const, volatile, and references).
Definition TypeTraits.h:279
Type-checked JavaScript bridge between C++ and web pages.
Definition JSInterop.h:141
Type
The type of a JavaScript value.
Definition Value.h:97
@ Symbol
Definition Value.h:104
@ String
Definition Value.h:103
@ Object
Definition Value.h:106
@ BigInt
Definition Value.h:105
Expected< T, Error > Result
The result of a JavaScript operation that can fail: a T or a js::Error.
Definition Error.h:520
Root namespace for every public Ultralight type, function, and enumeration.
Counts of the live handles on one context, for finding leaks (see Context::GetHandleStats()).
Definition Context.h:43
size_t weak_refs
Live weak references (0 once the context is gone).
Definition Context.h:46
size_t count(Type type) const
Get the number of live value handles of one type.
Definition Context.h:55
size_t ProtectedEstimate() const
Count the value handles that keep something from being garbage collected (strings,...
Definition Context.h:66
size_t total_values
Live value handles.
Definition Context.h:44
size_t values_by_type[kULJSType_Count]
Live value handles by js::Type (see count()).
Definition Context.h:45
A new pending Promise and the Resolver that settles it (see Context::MakePromise()).
Definition Context.h:75
Value promise
The Promise to hand to the page.
Definition Context.h:76
Resolver resolver
Settles promise (from any thread).
Definition Context.h:77
Type conversions between C++ and JavaScript across the bridge.
Definition TypeTraits.h:244