Bug 1732219 - Add API for fetching the preview image. r=geckoview-reviewers,agi,mconley
[gecko.git] / dom / workers / ChromeWorkerScope.cpp
blob7e8f375a4669d6c2a830eabb353d375d414f71e4
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
5 * You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "ChromeWorkerScope.h"
9 #include "jsapi.h"
10 #include "js/PropertyAndElement.h" // JS_GetProperty
11 #include "js/experimental/CTypes.h" // JS::InitCTypesClass, JS::CTypesCallbacks, JS::SetCTypesCallbacks
12 #include "js/MemoryFunctions.h"
14 #include "nsNativeCharsetUtils.h"
15 #include "nsString.h"
17 namespace mozilla {
18 namespace dom {
20 namespace {
22 #ifdef BUILD_CTYPES
24 char* UnicodeToNative(JSContext* aCx, const char16_t* aSource,
25 size_t aSourceLen) {
26 nsDependentSubstring unicode(aSource, aSourceLen);
28 nsAutoCString native;
29 if (NS_FAILED(NS_CopyUnicodeToNative(unicode, native))) {
30 JS_ReportErrorASCII(aCx, "Could not convert string to native charset!");
31 return nullptr;
34 char* result = static_cast<char*>(JS_malloc(aCx, native.Length() + 1));
35 if (!result) {
36 return nullptr;
39 memcpy(result, native.get(), native.Length());
40 result[native.Length()] = 0;
41 return result;
44 #endif // BUILD_CTYPES
46 } // namespace
48 bool DefineChromeWorkerFunctions(JSContext* aCx,
49 JS::Handle<JSObject*> aGlobal) {
50 // Currently ctypes is the only special property given to ChromeWorkers.
51 #ifdef BUILD_CTYPES
53 JS::Rooted<JS::Value> ctypes(aCx);
54 if (!JS::InitCTypesClass(aCx, aGlobal) ||
55 !JS_GetProperty(aCx, aGlobal, "ctypes", &ctypes)) {
56 return false;
59 static const JS::CTypesCallbacks callbacks = {UnicodeToNative};
61 JS::SetCTypesCallbacks(ctypes.toObjectOrNull(), &callbacks);
63 #endif // BUILD_CTYPES
65 return true;
68 } // namespace dom
69 } // namespace mozilla