This commit is contained in:
ImVexed 2019-09-26 15:33:10 -05:00
commit a74a62b04d
73 changed files with 22959 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
go.sum
webfiles/ab0x.go
.vscode/

80
b0x.yml Normal file
View File

@ -0,0 +1,80 @@
# all folders and files are relative to the path
# where fileb0x was run at!
# default: main
pkg: webfiles
# destination
dest: "./webfiles/"
# gofmt
# type: bool
# default: false
fmt: true
# compress files
# at the moment, only supports gzip
#
# type: object
compression:
# activates the compression
#
# type: bool
# default: false
compress: true
# valid values are:
# -> "NoCompression"
# -> "BestSpeed"
# -> "BestCompression"
# -> "DefaultCompression" or ""
#
# type: string
# default: "DefaultCompression" # when: Compress == true && Method == ""
method: "BestCompression"
# true = do it yourself (the file is written as gzip compressed file into the memory file system)
# false = decompress files at run time (while writing file into memory file system)
#
# type: bool
# default: false
keep: false
# ---------------
# -- DANGEROUS --
# ---------------
#
# cleans the destination folder (only b0xfiles)
# you should use this when using the spread function
# type: bool
# default: false
clean: false
# default: ab0x.go
output: "ab0x.go"
# [unexporTed] builds non-exporTed functions, variables and types...
# type: bool
# default: false
unexporTed: false
# [spread] means it will make a file to hold all fileb0x data
# and each file into a separaTed .go file
#
# example:
# theres 2 files in the folder assets, they're: hello.json and world.txt
# when spread is activaTed, fileb0x will make a file:
# b0x.go or [output]'s data, assets_hello.json.go and assets_world.txt.go
#
#
# type: bool
# default: false
spread: false
# [lcf] log changed files when spread is active
lcf: true
custom:
- files:
- "./public/build/"
base: "public/build/"

21
fileserver/fileserver.go Normal file
View File

@ -0,0 +1,21 @@
package fileserver
import (
"log"
"net"
"net/http"
"test/webfiles"
)
func Serve() (string, error) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return "", err
}
go func() {
log.Fatal(http.Serve(ln, http.FileServer(webfiles.HTTP)))
}()
return "http://" + ln.Addr().String(), nil
}

5
go.mod Normal file
View File

@ -0,0 +1,5 @@
module test
go 1.12
require golang.org/x/net v0.0.0-20190926025831-c00fd9afed17

120
include/AppCore/App.h Normal file
View File

@ -0,0 +1,120 @@
///
/// @file App.h
///
/// @brief The header for the App class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include "Defines.h"
#include <Ultralight/RefPtr.h>
#include <Ultralight/Renderer.h>
namespace ultralight {
class Monitor;
class Window;
///
/// Interface for all App-related events. @see App::set_listener
///
class AExport AppListener {
public:
virtual ~AppListener() {}
///
/// Called whenever the App updates. You should update all app logic here.
///
/// @note This event is fired right before the run loop calls
/// Renderer::Update and Renderer::Render.
///
virtual void OnUpdate() {}
};
///
/// Main application class.
///
class AExport App : public RefCounted {
public:
///
/// Create the App singleton.
///
/// @note You should only create one of these per application lifetime.
///
/// App maintains its own Renderer instance, make sure to set your
/// Config before creating App. (@see Platform::set_config)
///
static Ref<App> Create();
///
/// Get the App singleton.
///
static App* instance();
///
/// Set the main window. You must set this before calling Run.
///
/// @param window The window to use for all rendering.
///
/// @note We currently only support one Window per App, this will change
/// later once we add support for multiple driver instances.
///
virtual void set_window(Ref<Window> window) = 0;
///
/// Get the main window.
///
virtual RefPtr<Window> window() = 0;
///
/// Set an AppListener to receive callbacks for app-related events.
///
/// @note Ownership remains with the caller.
///
virtual void set_listener(AppListener* listener) = 0;
///
/// Get the AppListener, if any.
///
virtual AppListener* listener() = 0;
///
/// Whether or not the App is running.
///
virtual bool is_running() const = 0;
///
/// Get the main monitor (this is never NULL).
///
/// @note We'll add monitor enumeration later.
///
virtual Monitor* main_monitor() = 0;
///
/// Get the underlying Renderer instance.
///
virtual Ref<Renderer> renderer() = 0;
///
/// Run the main loop.
///
/// @note Make sure to call set_window before calling this.
///
virtual void Run() = 0;
///
/// Quit the application.
///
virtual void Quit() = 0;
protected:
virtual ~App();
};
} // namespace ultralight

View File

@ -0,0 +1,5 @@
#include <AppCore/App.h>
#include <AppCore/Monitor.h>
#include <AppCore/Window.h>
#include <AppCore/Overlay.h>
#include <AppCore/JSHelpers.h>

325
include/AppCore/CAPI.h Normal file
View File

@ -0,0 +1,325 @@
///
/// @file CAPI.h
///
/// @brief The C-language API for AppCore
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#ifndef APPCORE_CAPI_H
#define APPCORE_CAPI_H
#include <Ultralight/CAPI.h>
#if defined(__WIN32__) || defined(_WIN32)
# if defined(APPCORE_IMPLEMENTATION)
# define AExport __declspec(dllexport)
# else
# define AExport __declspec(dllimport)
# endif
#else
# define AExport __attribute__((visibility("default")))
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef struct C_App* ULApp;
typedef struct C_Window* ULWindow;
typedef struct C_Monitor* ULMonitor;
typedef struct C_Overlay* ULOverlay;
///
/// Window creation flags. @see Window::Create
///
typedef enum {
kWindowFlags_Borderless = 1 << 0,
kWindowFlags_Titled = 1 << 1,
kWindowFlags_Resizable = 1 << 2,
kWindowFlags_Maximizable = 1 << 3,
} ULWindowFlags;
///
/// Create the App singleton.
///
/// @param config Configuration settings to use.
///
/// @note You should only create one of these per application lifetime.
///
/// App maintains its own Renderer instance, make sure to set your
/// Config before creating App. (@see Platform::set_config)
///
AExport ULApp ulCreateApp(ULConfig config);
///
/// Destroy the App instance.
///
AExport void ulDestroyApp(ULApp app);
///
/// Set the main window. You must set this before calling ulAppRun.
///
/// @param window The window to use for all rendering.
///
/// @note We currently only support one Window per App, this will change
/// later once we add support for multiple driver instances.
///
AExport void ulAppSetWindow(ULApp app, ULWindow window);
///
/// Get the main window.
///
AExport ULWindow ulAppGetWindow(ULApp app);
typedef void
(*ULUpdateCallback) (void* user_data);
///
/// Set a callback for whenever the App updates. You should update all app
/// logic here.
///
/// @note This event is fired right before the run loop calls
/// Renderer::Update and Renderer::Render.
///
AExport void ulAppSetUpdateCallback(ULApp app, ULUpdateCallback callback,
void* user_data);
///
/// Whether or not the App is running.
///
AExport bool ulAppIsRunning(ULApp app);
///
/// Get the main monitor (this is never NULL).
///
/// @note We'll add monitor enumeration later.
///
AExport ULMonitor ulAppGetMainMonitor(ULApp app);
///
/// Get the underlying Renderer instance.
///
AExport ULRenderer ulAppGetRenderer(ULApp app);
///
/// Run the main loop.
///
/// @note Make sure to call ulAppSetWindow before calling this.
///
AExport void ulAppRun(ULApp app);
///
/// Quit the application.
///
AExport void ulAppQuit(ULApp app);
///
/// Get the monitor's DPI scale (1.0 = 100%).
///
AExport double ulMonitorGetScale(ULMonitor monitor);
///
/// Get the width of the monitor (in device coordinates)
///
AExport unsigned int ulMonitorGetWidth(ULMonitor monitor);
///
/// Get the height of the monitor (in device coordinates)
///
AExport unsigned int ulMonitorGetHeight(ULMonitor monitor);
///
/// Create a new Window.
///
/// @param monitor The monitor to create the Window on.
///
/// @param width The width (in device coordinates).
///
/// @param height The height (in device coordinates).
///
/// @param fullscreen Whether or not the window is fullscreen.
///
/// @param window_flags Various window flags.
///
AExport ULWindow ulCreateWindow(ULMonitor monitor, unsigned int width,
unsigned int height, bool fullscreen,
unsigned int window_flags);
///
/// Destroy a Window.
///
AExport void ulDestroyWindow(ULWindow window);
typedef void
(*ULCloseCallback) (void* user_data);
///
/// Set a callback to be notified when a window closes.
///
AExport void ulWindowSetCloseCallback(ULWindow window,
ULCloseCallback callback,
void* user_data);
typedef void
(*ULResizeCallback) (void* user_data, unsigned int width, unsigned int height);
///
/// Set a callback to be notified when a window resizes
/// (parameters are passed back in device coordinates).
///
AExport void ulWindowSetResizeCallback(ULWindow window,
ULResizeCallback callback,
void* user_data);
///
/// Get window width (in device coordinates).
///
AExport unsigned int ulWindowGetWidth(ULWindow window);
///
/// Get window height (in device coordinates).
///
AExport unsigned int ulWindowGetHeight(ULWindow window);
///
/// Get whether or not a window is fullscreen.
///
AExport bool ulWindowIsFullscreen(ULWindow window);
///
/// Get the DPI scale of a window.
///
AExport double ulWindowGetScale(ULWindow window);
///
/// Set the window title.
///
AExport void ulWindowSetTitle(ULWindow window, const char* title);
///
/// Set the cursor for a window.
///
AExport void ulWindowSetCursor(ULWindow window, ULCursor cursor);
///
/// Close a window.
///
AExport void ulWindowClose(ULWindow window);
///
/// Convert device coordinates to pixels using the current DPI scale.
///
AExport int ulWindowDeviceToPixel(ULWindow window, int val);
///
/// Convert pixels to device coordinates using the current DPI scale.
///
AExport int ulWindowPixelsToDevice(ULWindow window, int val);
///
/// Create a new Overlay.
///
/// @param window The window to create the Overlay in. (we currently only
/// support one window per application)
///
/// @param width The width in device coordinates.
///
/// @param height The height in device coordinates.
///
/// @param x The x-position (offset from the left of the Window), in
/// device coordinates.
///
/// @param y The y-position (offset from the top of the Window), in
/// device coordinates.
///
/// @note Each Overlay is essentially a View and an on-screen quad. You should
/// create the Overlay then load content into the underlying View.
///
AExport ULOverlay ulCreateOverlay(ULWindow window, unsigned int width,
unsigned int height, int x, int y);
///
/// Destroy an overlay.
///
AExport void ulDestroyOverlay(ULOverlay overlay);
///
/// Get the underlying View.
///
AExport ULView ulOverlayGetView(ULOverlay overlay);
///
/// Get the width (in device coordinates).
///
AExport unsigned int ulOverlayGetWidth(ULOverlay overlay);
///
/// Get the height (in device coordinates).
///
AExport unsigned int ulOverlayGetHeight(ULOverlay overlay);
///
/// Get the x-position (offset from the left of the Window), in device
/// coordinates.
///
AExport int ulOverlayGetX(ULOverlay overlay);
///
/// Get the y-position (offset from the top of the Window), in device
/// coordinates.
///
AExport int ulOverlayGetY(ULOverlay overlay);
///
/// Move the overlay to a new position (in device coordinates).
///
AExport void ulOverlayMoveTo(ULOverlay overlay, int x, int y);
///
/// Resize the overlay (and underlying View), dimensions should be
/// specified in device coordinates.
///
AExport void ulOverlayResize(ULOverlay overlay, unsigned int width,
unsigned int height);
///
/// Whether or not the overlay is hidden (not drawn).
///
AExport bool ulOverlayIsHidden(ULOverlay overlay);
///
/// Hide the overlay (will no longer be drawn)
///
AExport void ulOverlayHide(ULOverlay overlay);
///
/// Show the overlay.
///
AExport void ulOverlayShow(ULOverlay overlay);
///
/// Whether or not an overlay has keyboard focus.
///
AExport bool ulOverlayHasFocus(ULOverlay overlay);
///
/// Grant this overlay exclusive keyboard focus.
///
AExport void ulOverlayFocus(ULOverlay overlay);
///
/// Remove keyboard focus.
///
AExport void ulOverlayUnfocus(ULOverlay overlay);
#ifdef __cplusplus
}
#endif
#endif // APPCORE_CAPI_H

42
include/AppCore/Defines.h Normal file
View File

@ -0,0 +1,42 @@
// Copyright 2018 Ultralight, Inc. All rights reserved.
#pragma once
// Needed for limit defines, like INTMAX_MAX, which is used by the std C++ library
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#include <cstdint>
#include <cstddef>
#include <limits.h>
#ifdef SWIG
#define AExport
#else
// Require C++11 Support
#if defined(_MSC_VER)
# if _MSC_VER < 1800
# error This project needs at least Visual Studio 2013 to build
# endif
#elif __cplusplus <= 199711L
# error This project can only be compiled with a compiler that supports C++11
#endif
#if defined(__WIN32__) || defined(_WIN32)
# if defined(APPCORE_IMPLEMENTATION)
# define AExport __declspec(dllexport)
# else
# define AExport __declspec(dllimport)
# endif
#define _thread_local __declspec(thread)
#ifndef _NATIVE_WCHAR_T_DEFINED
#define DISABLE_NATIVE_WCHAR_T
#endif
#else
# define AExport __attribute__((visibility("default")))
#define _thread_local __thread
#endif
#endif

415
include/AppCore/JSHelpers.h Normal file
View File

@ -0,0 +1,415 @@
#pragma once
#include <AppCore/Defines.h>
#include <JavaScriptCore/JavaScript.h>
#include <JavaScriptCore/JSStringRef.h>
#include <Ultralight/String.h>
#include <functional>
#include <memory>
/**
* This is a set of common JavaScriptCore Helper functions
* to simplify sample code.
*/
namespace ultralight {
/**
* Set the current JSContext.
*
* NOTE: You MUST set this before using most of the classes/functions below.
*
* The only things you can create without a JSContext are JSString's and
* the empty JSFunction constructor.
*/
void AExport SetJSContext(JSContextRef ctx);
/**
* Get the current JSContext.
*/
JSContextRef AExport GetJSContext();
/**
* JSString wrapper that automatically manages lifetime
* and provides helpful conversions.
*/
class AExport JSString {
public:
// Create empty string
JSString();
// Create from C-string
JSString(const char* str);
// Create from Ultralight String
JSString(const String& str);
// Take ownership of existing JSStringRef
JSString(JSStringRef str);
// Copy constructor
JSString(const JSString& other);
~JSString();
// Assignment operator
JSString& operator=(const JSString& other);
// Cast to String
operator String();
// Cast to JSStringRef
operator JSStringRef() const { return instance_; }
protected:
JSStringRef instance_;
};
class JSArray;
class JSObject;
class JSFunction;
// Used with the JSValue constructor to create "Null" types
struct AExport JSValueNullTag {};
// Used with the JSValue constructor to create "Undefined" types
struct AExport JSValueUndefinedTag {};
/**
* JSValue wrapper that automatically manages lifetime and
* provides helpful conversions.
*/
class AExport JSValue {
public:
// Create null (empty) JSValue
JSValue();
// Create null JSValue explicitly
JSValue(JSValueNullTag);
// Create undefined JSValue
JSValue(JSValueUndefinedTag);
// Create boolean JSValue
JSValue(bool val);
// Create unsigned integer JSValue (aka, Number) [will be cast to double]
JSValue(uint32_t val);
// Create integer JSValue (aka, Number) [will be cast to double]
JSValue(int32_t val);
// Create unsigned integer JSValue (aka, Number) [will be cast to double]
JSValue(uint64_t val);
// Create integer JSValue (aka, Number) [will be cast to double]
JSValue(int64_t val);
// Create double JSValue (aka, Number)
JSValue(double val);
// Create string JSValue
JSValue(const char* val);
// Create string JSValue
JSValue(const String& val);
// Create string JSValue
JSValue(JSString val);
// Create from existing JSValueRef
JSValue(JSValueRef val);
// Create object JSValue
JSValue(JSObjectRef obj);
// Copy constructor, a shallow copy is made, will end up pointing to same instance
JSValue(const JSValue& other);
virtual ~JSValue();
// A shallow copy is made, will end up pointing to same instance
virtual JSValue& operator=(const JSValue& other);
bool IsNull() const;
bool IsUndefined() const;
bool IsBoolean() const;
bool IsNumber() const;
bool IsString() const;
bool IsObject() const;
bool IsArray() const;
bool IsFunction() const;
// Convert to Boolean
bool ToBoolean() const;
// Convert to Number (Double)
double ToNumber() const;
// Convert to Number (Integer)
int64_t ToInteger() const { return static_cast<int64_t>(ToNumber()); }
// Convert to String
JSString ToString() const;
// Convert to Object (will debug assert if not an Object)
JSObject ToObject() const;
// Convert to Array (will debug asset if not an Array)
JSArray ToArray() const;
// Convert to Function (will debug asset if not a Function)
JSFunction ToFunction() const;
operator bool() const { return ToBoolean(); }
operator double() const { return ToNumber(); }
operator uint32_t() const { return static_cast<uint32_t>(ToNumber()); }
operator int32_t() const { return static_cast<uint32_t>(ToNumber()); }
operator uint64_t() const { return static_cast<uint64_t>(ToNumber()); }
operator int64_t() const { return ToInteger(); }
operator String() const { return ToString(); }
operator JSString() const { return ToString(); }
operator JSObject() const;
operator JSObjectRef() const;
operator JSArray() const;
operator JSFunction() const;
// Get the underlying JSValueRef
operator JSValueRef() const { return instance(); }
protected:
JSValue(JSContextRef ctx);
JSValue(JSContextRef ctx, JSValueRef val);
virtual JSValueRef instance() const;
JSContextRef ctx_;
JSValueRef instance_ = nullptr;
friend class JSFunction;
};
/**
* A vector of JSValues, used for passing around arguments in JSCallback.
* We don't expose std::vector directly because of ABI concerns.
*/
class AExport JSArgs {
public:
JSArgs();
JSArgs(const std::initializer_list<JSValue>& values);
JSArgs(const JSArgs& other);
~JSArgs();
JSArgs& operator=(const JSArgs& other);
JSValue operator[](size_t pos);
const JSValue operator[](size_t pos) const;
bool empty() const;
size_t size() const;
void clear();
void push_back(const JSValue& val);
void pop_back();
JSValue* data();
const JSValue* data() const;
protected:
void* instance_;
};
typedef std::function<void(const JSObject&, const JSArgs&)> JSCallback;
typedef std::function<JSValue(const JSObject&, const JSArgs&)> JSCallbackWithRetval;
// Macro to help bind JSCallback member function to JSPropertyValue
#define BindJSCallback(fn) (JSCallback)std::bind(fn, this, std::placeholders::_1, std::placeholders::_2)
#define BindJSCallbackWithRetval(fn) (JSCallbackWithRetval)std::bind(fn, this, std::placeholders::_1, std::placeholders::_2)
/**
* Wrapper for JSObject property value (JSValue subclass). Allows new value assignment
* to object property, binding C++ callbacks to object properties via function objects,
* as well as value query via the JSValue interface.
*/
class AExport JSPropertyValue : public JSValue {
public:
virtual ~JSPropertyValue();
// Assign a new value to the property (internally calls JSObjectSetProperty)
virtual JSPropertyValue& operator=(const JSValue& value);
// Bind to native C++ callback (creates a Function object that can be called from JS)
JSPropertyValue& operator=(const JSCallback& callback);
// Bind to native C++ callback with return value (creates a Function object that can be called from JS)
JSPropertyValue& operator=(const JSCallbackWithRetval& callback);
protected:
virtual JSValueRef instance() const;
JSPropertyValue(JSContextRef ctx, JSObjectRef proxy_obj, unsigned idx);
JSPropertyValue(JSContextRef ctx, JSObjectRef proxy_obj, JSString idx);
JSPropertyValue(const JSPropertyValue&) = default;
JSPropertyValue& operator=(const JSPropertyValue&) = delete;
JSObject* proxyObj_;
bool using_numeric_idx_;
unsigned numeric_idx_;
JSString string_idx_;
friend class JSArray;
friend class JSObject;
};
/**
* JSArray wrapper that automatically manages lifetime and provides
* convenient access to indices and Array functions.
*/
class AExport JSArray {
public:
// Create empty Array
JSArray();
// Create Array from list of JSValues
JSArray(const std::initializer_list<JSValue>& values);
// Create Array from existing JSObjectRef (JavaScriptCore C API)
JSArray(JSObjectRef array_obj);
// Copy constructor (shallow copy, will point to same instance)
JSArray(const JSArray& other);
~JSArray();
// Assignment (shallow assignment, will point to same instance)
JSArray& operator=(const JSArray& other);
// Get number of elements in the Array
unsigned length();
// Push an element to back of Array
void push(const JSValue& val);
// Find the index (location) of a certain value, will return -1 if not found
int indexOf(const JSValue& val, int start = 0) const;
// Get a property by array index (numbering starts at 0)
JSPropertyValue operator[](unsigned idx) const;
// Get the underlying JSObjectRef (JavaScriptCore C API)
operator JSObjectRef() const { return instance_; }
protected:
JSArray(JSContextRef ctx, JSValueRef val);
JSContextRef ctx_;
JSObjectRef instance_;
friend class JSValue;
};
/**
* JSObject wrapper that automatically manages lifetime and provides
* convenient access to properties.
*/
class AExport JSObject {
public:
// Create empty Object
JSObject();
// Create from existing JSObjectRef from JavaScriptCore C API
JSObject(JSObjectRef obj);
// Copy constructor (shallow copy, will point to same instance)
JSObject(const JSObject& other);
~JSObject();
// Assignment (shallow assignment, will point to same instance)
JSObject& operator=(const JSObject& other);
// Get a property by name
JSPropertyValue operator[](JSString propertyName) const;
// Check if a property exists
bool HasProperty(JSString propertyName) const;
// Remove a property
bool DeleteProperty(JSString propertyName);
// Get the underlying JSObjectRef (JavaScriptCore C API)
operator JSObjectRef() const { return instance_; }
protected:
JSObject(JSContextRef ctx, JSValueRef val);
JSObject(JSContextRef ctx, JSObjectRef obj);
JSContextRef ctx_;
JSObjectRef instance_;
friend class JSValue;
friend class JSPropertyValue;
};
/**
* JSFunction wrapper that automatically manages lifetime and provides
* convenient function invocation operators.
*/
class AExport JSFunction {
public:
// Create an empty Function.
// NOTE: It is OKAY to create this without calling SetJSContext() first.
JSFunction();
// Copy constructor (shallow copy, will point to same instance)
JSFunction(const JSFunction& other);
~JSFunction();
// Assignment (shallow assignment, will point to same instance)
JSFunction& operator=(const JSFunction& other);
// Whether or not this is a valid, callable Function object.
bool IsValid() const;
// Call function (using Global Object for 'this') and return the result.
JSValue operator()(const JSArgs& args);
// Call function (with explicit object for 'this') and return the result
JSValue operator()(const JSObject& thisObject, const JSArgs& args);
// Get the underlying JSObjectRef (JavaScriptCore C API)
operator JSObjectRef() const { return instance_; }
protected:
JSFunction(JSContextRef ctx, JSValueRef val);
JSContextRef ctx_;
JSObjectRef instance_;
friend class JSValue;
};
/**
* Get the Global Object for the current JSContext.
* In JavaScript, this would be equivalent to the "window" object.
*/
JSObject AExport JSGlobalObject();
/**
* Evaluate a string of JavaScript and return a result.
*/
JSValue AExport JSEval(const JSString& str);
} // namespace ultralight

41
include/AppCore/Monitor.h Normal file
View File

@ -0,0 +1,41 @@
///
/// @file Monitor.h
///
/// @brief The header for the Monitor class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include "Defines.h"
namespace ultralight {
///
/// Monitor class, represents a platform monitor.
///
class AExport Monitor {
public:
virtual ~Monitor() {}
///
/// Get the DPI scale (1.0 = 100%)
///
virtual double scale() const = 0;
///
/// Get the width of the monitor.
///
virtual uint32_t width() const = 0;
/// Get the height of the monitor.
///
virtual uint32_t height() const = 0;
};
} // namespace ultralight

137
include/AppCore/Overlay.h Normal file
View File

@ -0,0 +1,137 @@
///
/// @file Overlay.h
///
/// @brief The header for the Overlay class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include "Window.h"
#include <Ultralight/View.h>
namespace ultralight {
///
/// Web-content overlay. Displays a web-page within an area of the main window.
///
/// @note Each Overlay is essentially a View and an on-screen quad. You should
/// create the Overlay then load content into the underlying View.
///
class AExport Overlay : public RefCounted {
public:
///
/// Create a new Overlay.
///
/// @param window The window to create the Overlay in. (we currently only
/// support one window per application)
///
/// @param width The width in device coordinates.
///
/// @param height The height in device coordinates.
///
/// @param x The x-position (offset from the left of the Window), in
/// device coordinates.
///
/// @param y The y-position (offset from the top of the Window), in
/// device coordinates.
///
static Ref<Overlay> Create(Ref<Window> window, uint32_t width,
uint32_t height, int x, int y);
///
/// Create a new Overlay, wrapping an existing View.
///
/// @param window The window to create the Overlay in. (we currently only
/// support one window per application)
///
/// @param view The View to wrap (will use its width and height).
///
/// @param x The x-position (offset from the left of the Window), in
/// device coordinates.
///
/// @param y The y-position (offset from the top of the Window), in
/// device coordinates.
///
static Ref<Overlay> Create(Ref<Window> window, Ref<View> view, int x, int y);
///
/// Get the underlying View.
///
virtual ultralight::Ref<ultralight::View> view() = 0;
///
/// Get the width (in device coordinates).
///
virtual uint32_t width() const = 0;
///
/// Get the height (in device coordinates).
///
virtual uint32_t height() const = 0;
///
/// Get the x-position (offset from the left of the Window), in device
/// coordinates.
///
virtual int x() const = 0;
///
/// Get the y-position (offset from the top of the Window), in device
/// coordinates.
///
virtual int y() const = 0;
///
/// Whether or not the overlay is hidden (not drawn).
///
virtual bool is_hidden() const = 0;
///
/// Hide the overlay (will no longer be drawn)
///
virtual void Hide() = 0;
///
/// Show the overlay.
///
virtual void Show() = 0;
///
/// Whether or not this overlay has keyboard focus.
///
virtual bool has_focus() const = 0;
///
/// Grant this overlay exclusive keyboard focus.
///
virtual void Focus() = 0;
///
/// Remove keyboard focus.
///
virtual void Unfocus() = 0;
///
/// Move the overlay to a new position (in device coordinates).
///
virtual void MoveTo(int x, int y) = 0;
///
/// Resize the overlay (and underlying View), dimensions should be
/// specified in device coordinates.
///
virtual void Resize(uint32_t width, uint32_t height) = 0;
protected:
virtual ~Overlay();
virtual void Draw() = 0;
friend class OverlayManager;
};
} // namespace framework

141
include/AppCore/Window.h Normal file
View File

@ -0,0 +1,141 @@
///
/// @file Window.h
///
/// @brief The header for the Window class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include "Defines.h"
#include <Ultralight/RefPtr.h>
#include <Ultralight/Listener.h>
namespace ultralight {
class Monitor;
class OverlayManager;
///
/// Interface for all Window-related events. @see Window::set_listener
///
class WindowListener {
public:
virtual ~WindowListener() {}
///
/// Called when the Window is closed.
///
virtual void OnClose() = 0;
///
/// Called when the Window is resized.
///
/// @param width The new width (in device coordinates).
///
/// @param height The new height (in device coordinates).
///
virtual void OnResize(uint32_t width, uint32_t height) = 0;
};
///
/// Window creation flags. @see Window::Create
///
enum WindowFlags : uint8_t {
kWindowFlags_Borderless = 1 << 0,
kWindowFlags_Titled = 1 << 1,
kWindowFlags_Resizable = 1 << 2,
kWindowFlags_Maximizable = 1 << 3,
};
///
/// Window class, represents a platform window.
///
class AExport Window : public RefCounted {
public:
///
/// Create a new Window.
///
/// @param monitor The monitor to create the Window on.
///
/// @param width The width (in device coordinates).
///
/// @param height The height (in device coordinates).
///
/// @param fullscreen Whether or not the window is fullscreen.
///
/// @param window_flags Various window flags.
///
static Ref<Window> Create(Monitor* monitor, uint32_t width, uint32_t height,
bool fullscreen, unsigned int window_flags);
///
/// Set a WindowListener to receive callbacks for window-related events.
///
/// @note Ownership remains with the caller.
///
virtual void set_listener(WindowListener* listener) = 0;
///
/// Get the WindowListener, if any.
///
virtual WindowListener* listener() = 0;
///
/// Get the window width (in device coordinates).
///
virtual uint32_t width() const = 0;
///
/// Get the window height (in device coordinates).
///
virtual uint32_t height() const = 0;
///
/// Whether or not the window is fullscreen.
///
virtual bool is_fullscreen() const = 0;
///
/// The DPI scale of the window.
///
virtual double scale() const = 0;
///
/// Set the window title.
///
virtual void SetTitle(const char* title) = 0;
///
/// Set the cursor.
///
virtual void SetCursor(ultralight::Cursor cursor) = 0;
///
/// Close the window.
///
virtual void Close() = 0;
///
/// Convert device coordinates to pixels using the current DPI scale.
///
virtual int DeviceToPixels(int val) const = 0;
///
/// Convert pixels to device coordinates using the current DPI scale.
///
virtual int PixelsToDevice(int val) const = 0;
protected:
virtual ~Window();
virtual OverlayManager* overlay_manager() const = 0;
friend class OverlayImpl;
};
} // namespace ultralight

View File

@ -0,0 +1,144 @@
/*
* Copyright (C) 2006 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSBase_h
#define JSBase_h
#ifndef __cplusplus
#include <stdbool.h>
#endif
#ifdef __OBJC__
#import <Foundation/Foundation.h>
#endif
/* JavaScript engine interface */
/*! @typedef JSContextGroupRef A group that associates JavaScript contexts with one another. Contexts in the same group may share and exchange JavaScript objects. */
typedef const struct OpaqueJSContextGroup* JSContextGroupRef;
/*! @typedef JSContextRef A JavaScript execution context. Holds the global object and other execution state. */
typedef const struct OpaqueJSContext* JSContextRef;
/*! @typedef JSGlobalContextRef A global JavaScript execution context. A JSGlobalContext is a JSContext. */
typedef struct OpaqueJSContext* JSGlobalContextRef;
/*! @typedef JSStringRef A UTF16 character buffer. The fundamental string representation in JavaScript. */
typedef struct OpaqueJSString* JSStringRef;
/*! @typedef JSClassRef A JavaScript class. Used with JSObjectMake to construct objects with custom behavior. */
typedef struct OpaqueJSClass* JSClassRef;
/*! @typedef JSPropertyNameArrayRef An array of JavaScript property names. */
typedef struct OpaqueJSPropertyNameArray* JSPropertyNameArrayRef;
/*! @typedef JSPropertyNameAccumulatorRef An ordered set used to collect the names of a JavaScript object's properties. */
typedef struct OpaqueJSPropertyNameAccumulator* JSPropertyNameAccumulatorRef;
/*! @typedef JSTypedArrayBytesDeallocator A function used to deallocate bytes passed to a Typed Array constructor. The function should take two arguments. The first is a pointer to the bytes that were originally passed to the Typed Array constructor. The second is a pointer to additional information desired at the time the bytes are to be freed. */
typedef void (*JSTypedArrayBytesDeallocator)(void* bytes, void* deallocatorContext);
/* JavaScript data types */
/*! @typedef JSValueRef A JavaScript value. The base type for all JavaScript values, and polymorphic functions on them. */
typedef const struct OpaqueJSValue* JSValueRef;
/*! @typedef JSObjectRef A JavaScript object. A JSObject is a JSValue. */
typedef struct OpaqueJSValue* JSObjectRef;
/* JavaScript symbol exports */
/* These rules should stay the same as in WebKit2/Shared/API/c/WKBase.h */
#undef JS_EXPORT
#if defined(JS_NO_EXPORT)
#define JS_EXPORT
#elif defined(__GNUC__) && !defined(__CC_ARM) && !defined(__ARMCC__)
#define JS_EXPORT __attribute__((visibility("default")))
#elif defined(WIN32) || defined(_WIN32) || defined(_WIN32_WCE) || defined(__CC_ARM) || defined(__ARMCC__)
#if defined(BUILDING_JavaScriptCore) || defined(STATICALLY_LINKED_WITH_JavaScriptCore)
#define JS_EXPORT __declspec(dllexport)
#else
#define JS_EXPORT __declspec(dllimport)
#endif
#else /* !defined(JS_NO_EXPORT) */
#define JS_EXPORT
#endif /* defined(JS_NO_EXPORT) */
#ifdef __cplusplus
extern "C" {
#endif
/* Script Evaluation */
/*!
@function JSEvaluateScript
@abstract Evaluates a string of JavaScript.
@param ctx The execution context to use.
@param script A JSString containing the script to evaluate.
@param thisObject The object to use as "this," or NULL to use the global object as "this."
@param sourceURL A JSString containing a URL for the script's source file. This is used by debuggers and when reporting exceptions. Pass NULL if you do not care to include source file information.
@param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions. The value is one-based, so the first line is line 1 and invalid values are clamped to 1.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The JSValue that results from evaluating script, or NULL if an exception is thrown.
*/
JS_EXPORT JSValueRef JSEvaluateScript(JSContextRef ctx, JSStringRef script, JSObjectRef thisObject, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception);
/*!
@function JSCheckScriptSyntax
@abstract Checks for syntax errors in a string of JavaScript.
@param ctx The execution context to use.
@param script A JSString containing the script to check for syntax errors.
@param sourceURL A JSString containing a URL for the script's source file. This is only used when reporting exceptions. Pass NULL if you do not care to include source file information in exceptions.
@param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions. The value is one-based, so the first line is line 1 and invalid values are clamped to 1.
@param exception A pointer to a JSValueRef in which to store a syntax error exception, if any. Pass NULL if you do not care to store a syntax error exception.
@result true if the script is syntactically correct, otherwise false.
*/
JS_EXPORT bool JSCheckScriptSyntax(JSContextRef ctx, JSStringRef script, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception);
/*!
@function JSGarbageCollect
@abstract Performs a JavaScript garbage collection.
@param ctx The execution context to use.
@discussion JavaScript values that are on the machine stack, in a register,
protected by JSValueProtect, set as the global object of an execution context,
or reachable from any such value will not be collected.
During JavaScript execution, you are not required to call this function; the
JavaScript engine will garbage collect as needed. JavaScript values created
within a context group are automatically destroyed when the last reference
to the context group is released.
*/
JS_EXPORT void JSGarbageCollect(JSContextRef ctx);
#ifdef __cplusplus
}
#endif
/* Enable the Objective-C API for platforms with a modern runtime. */
#if !defined(JSC_OBJC_API_ENABLED)
#define JSC_OBJC_API_ENABLED (defined(__clang__) && defined(__APPLE__) && ((defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && !defined(__i386__)) || (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)))
#endif
#endif /* JSBase_h */

View File

@ -0,0 +1,158 @@
/*
* Copyright (C) 2006 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSContextRef_h
#define JSContextRef_h
#include <JavaScriptCore/JSObjectRef.h>
#include <JavaScriptCore/JSValueRef.h>
#include <JavaScriptCore/WebKitAvailability.h>
#ifndef __cplusplus
#include <stdbool.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
/*!
@function
@abstract Creates a JavaScript context group.
@discussion A JSContextGroup associates JavaScript contexts with one another.
Contexts in the same group may share and exchange JavaScript objects. Sharing and/or exchanging
JavaScript objects between contexts in different groups will produce undefined behavior.
When objects from the same context group are used in multiple threads, explicit
synchronization is required.
@result The created JSContextGroup.
*/
JS_EXPORT JSContextGroupRef JSContextGroupCreate(void) CF_AVAILABLE(10_6, 7_0);
/*!
@function
@abstract Retains a JavaScript context group.
@param group The JSContextGroup to retain.
@result A JSContextGroup that is the same as group.
*/
JS_EXPORT JSContextGroupRef JSContextGroupRetain(JSContextGroupRef group) CF_AVAILABLE(10_6, 7_0);
/*!
@function
@abstract Releases a JavaScript context group.
@param group The JSContextGroup to release.
*/
JS_EXPORT void JSContextGroupRelease(JSContextGroupRef group) CF_AVAILABLE(10_6, 7_0);
/*!
@function
@abstract Creates a global JavaScript execution context.
@discussion JSGlobalContextCreate allocates a global object and populates it with all the
built-in JavaScript objects, such as Object, Function, String, and Array.
In WebKit version 4.0 and later, the context is created in a unique context group.
Therefore, scripts may execute in it concurrently with scripts executing in other contexts.
However, you may not use values created in the context in other contexts.
@param globalObjectClass The class to use when creating the global object. Pass
NULL to use the default object class.
@result A JSGlobalContext with a global object of class globalObjectClass.
*/
JS_EXPORT JSGlobalContextRef JSGlobalContextCreate(JSClassRef globalObjectClass) CF_AVAILABLE(10_5, 7_0);
/*!
@function
@abstract Creates a global JavaScript execution context in the context group provided.
@discussion JSGlobalContextCreateInGroup allocates a global object and populates it with
all the built-in JavaScript objects, such as Object, Function, String, and Array.
@param globalObjectClass The class to use when creating the global object. Pass
NULL to use the default object class.
@param group The context group to use. The created global context retains the group.
Pass NULL to create a unique group for the context.
@result A JSGlobalContext with a global object of class globalObjectClass and a context
group equal to group.
*/
JS_EXPORT JSGlobalContextRef JSGlobalContextCreateInGroup(JSContextGroupRef group, JSClassRef globalObjectClass) CF_AVAILABLE(10_6, 7_0);
/*!
@function
@abstract Retains a global JavaScript execution context.
@param ctx The JSGlobalContext to retain.
@result A JSGlobalContext that is the same as ctx.
*/
JS_EXPORT JSGlobalContextRef JSGlobalContextRetain(JSGlobalContextRef ctx);
/*!
@function
@abstract Releases a global JavaScript execution context.
@param ctx The JSGlobalContext to release.
*/
JS_EXPORT void JSGlobalContextRelease(JSGlobalContextRef ctx);
/*!
@function
@abstract Gets the global object of a JavaScript execution context.
@param ctx The JSContext whose global object you want to get.
@result ctx's global object.
*/
JS_EXPORT JSObjectRef JSContextGetGlobalObject(JSContextRef ctx);
/*!
@function
@abstract Gets the context group to which a JavaScript execution context belongs.
@param ctx The JSContext whose group you want to get.
@result ctx's group.
*/
JS_EXPORT JSContextGroupRef JSContextGetGroup(JSContextRef ctx) CF_AVAILABLE(10_6, 7_0);
/*!
@function
@abstract Gets the global context of a JavaScript execution context.
@param ctx The JSContext whose global context you want to get.
@result ctx's global context.
*/
JS_EXPORT JSGlobalContextRef JSContextGetGlobalContext(JSContextRef ctx) CF_AVAILABLE(10_7, 7_0);
/*!
@function
@abstract Gets a copy of the name of a context.
@param ctx The JSGlobalContext whose name you want to get.
@result The name for ctx.
@discussion A JSGlobalContext's name is exposed for remote debugging to make it
easier to identify the context you would like to attach to.
*/
JS_EXPORT JSStringRef JSGlobalContextCopyName(JSGlobalContextRef ctx) CF_AVAILABLE(10_10, 8_0);
/*!
@function
@abstract Sets the remote debugging name for a context.
@param ctx The JSGlobalContext that you want to name.
@param name The remote debugging name to set on ctx.
*/
JS_EXPORT void JSGlobalContextSetName(JSGlobalContextRef ctx, JSStringRef name) CF_AVAILABLE(10_10, 8_0);
#ifdef __cplusplus
}
#endif
#endif /* JSContextRef_h */

View File

@ -0,0 +1,694 @@
/*
* Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
* Copyright (C) 2008 Kelvin W Sherlock (ksherlock@gmail.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSObjectRef_h
#define JSObjectRef_h
#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/JSValueRef.h>
#include <JavaScriptCore/WebKitAvailability.h>
#ifndef __cplusplus
#include <stdbool.h>
#endif
#include <stddef.h> /* for size_t */
#ifdef __cplusplus
extern "C" {
#endif
/*!
@enum JSPropertyAttribute
@constant kJSPropertyAttributeNone Specifies that a property has no special attributes.
@constant kJSPropertyAttributeReadOnly Specifies that a property is read-only.
@constant kJSPropertyAttributeDontEnum Specifies that a property should not be enumerated by JSPropertyEnumerators and JavaScript for...in loops.
@constant kJSPropertyAttributeDontDelete Specifies that the delete operation should fail on a property.
*/
enum {
kJSPropertyAttributeNone = 0,
kJSPropertyAttributeReadOnly = 1 << 1,
kJSPropertyAttributeDontEnum = 1 << 2,
kJSPropertyAttributeDontDelete = 1 << 3
};
/*!
@typedef JSPropertyAttributes
@abstract A set of JSPropertyAttributes. Combine multiple attributes by logically ORing them together.
*/
typedef unsigned JSPropertyAttributes;
/*!
@enum JSClassAttribute
@constant kJSClassAttributeNone Specifies that a class has no special attributes.
@constant kJSClassAttributeNoAutomaticPrototype Specifies that a class should not automatically generate a shared prototype for its instance objects. Use kJSClassAttributeNoAutomaticPrototype in combination with JSObjectSetPrototype to manage prototypes manually.
*/
enum {
kJSClassAttributeNone = 0,
kJSClassAttributeNoAutomaticPrototype = 1 << 1
};
/*!
@typedef JSClassAttributes
@abstract A set of JSClassAttributes. Combine multiple attributes by logically ORing them together.
*/
typedef unsigned JSClassAttributes;
/*!
@typedef JSObjectInitializeCallback
@abstract The callback invoked when an object is first created.
@param ctx The execution context to use.
@param object The JSObject being created.
@discussion If you named your function Initialize, you would declare it like this:
void Initialize(JSContextRef ctx, JSObjectRef object);
Unlike the other object callbacks, the initialize callback is called on the least
derived class (the parent class) first, and the most derived class last.
*/
typedef void
(*JSObjectInitializeCallback) (JSContextRef ctx, JSObjectRef object);
/*!
@typedef JSObjectFinalizeCallback
@abstract The callback invoked when an object is finalized (prepared for garbage collection). An object may be finalized on any thread.
@param object The JSObject being finalized.
@discussion If you named your function Finalize, you would declare it like this:
void Finalize(JSObjectRef object);
The finalize callback is called on the most derived class first, and the least
derived class (the parent class) last.
You must not call any function that may cause a garbage collection or an allocation
of a garbage collected object from within a JSObjectFinalizeCallback. This includes
all functions that have a JSContextRef parameter.
*/
typedef void
(*JSObjectFinalizeCallback) (JSObjectRef object);
/*!
@typedef JSObjectHasPropertyCallback
@abstract The callback invoked when determining whether an object has a property.
@param ctx The execution context to use.
@param object The JSObject to search for the property.
@param propertyName A JSString containing the name of the property look up.
@result true if object has the property, otherwise false.
@discussion If you named your function HasProperty, you would declare it like this:
bool HasProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
If this function returns false, the hasProperty request forwards to object's statically declared properties, then its parent class chain (which includes the default object class), then its prototype chain.
This callback enables optimization in cases where only a property's existence needs to be known, not its value, and computing its value would be expensive.
If this callback is NULL, the getProperty callback will be used to service hasProperty requests.
*/
typedef bool
(*JSObjectHasPropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
/*!
@typedef JSObjectGetPropertyCallback
@abstract The callback invoked when getting a property's value.
@param ctx The execution context to use.
@param object The JSObject to search for the property.
@param propertyName A JSString containing the name of the property to get.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result The property's value if object has the property, otherwise NULL.
@discussion If you named your function GetProperty, you would declare it like this:
JSValueRef GetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
If this function returns NULL, the get request forwards to object's statically declared properties, then its parent class chain (which includes the default object class), then its prototype chain.
*/
typedef JSValueRef
(*JSObjectGetPropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
/*!
@typedef JSObjectSetPropertyCallback
@abstract The callback invoked when setting a property's value.
@param ctx The execution context to use.
@param object The JSObject on which to set the property's value.
@param propertyName A JSString containing the name of the property to set.
@param value A JSValue to use as the property's value.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result true if the property was set, otherwise false.
@discussion If you named your function SetProperty, you would declare it like this:
bool SetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception);
If this function returns false, the set request forwards to object's statically declared properties, then its parent class chain (which includes the default object class).
*/
typedef bool
(*JSObjectSetPropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception);
/*!
@typedef JSObjectDeletePropertyCallback
@abstract The callback invoked when deleting a property.
@param ctx The execution context to use.
@param object The JSObject in which to delete the property.
@param propertyName A JSString containing the name of the property to delete.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result true if propertyName was successfully deleted, otherwise false.
@discussion If you named your function DeleteProperty, you would declare it like this:
bool DeleteProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
If this function returns false, the delete request forwards to object's statically declared properties, then its parent class chain (which includes the default object class).
*/
typedef bool
(*JSObjectDeletePropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
/*!
@typedef JSObjectGetPropertyNamesCallback
@abstract The callback invoked when collecting the names of an object's properties.
@param ctx The execution context to use.
@param object The JSObject whose property names are being collected.
@param propertyNames A JavaScript property name accumulator in which to accumulate the names of object's properties.
@discussion If you named your function GetPropertyNames, you would declare it like this:
void GetPropertyNames(JSContextRef ctx, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames);
Property name accumulators are used by JSObjectCopyPropertyNames and JavaScript for...in loops.
Use JSPropertyNameAccumulatorAddName to add property names to accumulator. A class's getPropertyNames callback only needs to provide the names of properties that the class vends through a custom getProperty or setProperty callback. Other properties, including statically declared properties, properties vended by other classes, and properties belonging to object's prototype, are added independently.
*/
typedef void
(*JSObjectGetPropertyNamesCallback) (JSContextRef ctx, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames);
/*!
@typedef JSObjectCallAsFunctionCallback
@abstract The callback invoked when an object is called as a function.
@param ctx The execution context to use.
@param function A JSObject that is the function being called.
@param thisObject A JSObject that is the 'this' variable in the function's scope.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of the arguments passed to the function.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result A JSValue that is the function's return value.
@discussion If you named your function CallAsFunction, you would declare it like this:
JSValueRef CallAsFunction(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
If your callback were invoked by the JavaScript expression 'myObject.myFunction()', function would be set to myFunction, and thisObject would be set to myObject.
If this callback is NULL, calling your object as a function will throw an exception.
*/
typedef JSValueRef
(*JSObjectCallAsFunctionCallback) (JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
/*!
@typedef JSObjectCallAsConstructorCallback
@abstract The callback invoked when an object is used as a constructor in a 'new' expression.
@param ctx The execution context to use.
@param constructor A JSObject that is the constructor being called.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of the arguments passed to the function.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result A JSObject that is the constructor's return value.
@discussion If you named your function CallAsConstructor, you would declare it like this:
JSObjectRef CallAsConstructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
If your callback were invoked by the JavaScript expression 'new myConstructor()', constructor would be set to myConstructor.
If this callback is NULL, using your object as a constructor in a 'new' expression will throw an exception.
*/
typedef JSObjectRef
(*JSObjectCallAsConstructorCallback) (JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
/*!
@typedef JSObjectHasInstanceCallback
@abstract hasInstance The callback invoked when an object is used as the target of an 'instanceof' expression.
@param ctx The execution context to use.
@param constructor The JSObject that is the target of the 'instanceof' expression.
@param possibleInstance The JSValue being tested to determine if it is an instance of constructor.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result true if possibleInstance is an instance of constructor, otherwise false.
@discussion If you named your function HasInstance, you would declare it like this:
bool HasInstance(JSContextRef ctx, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception);
If your callback were invoked by the JavaScript expression 'someValue instanceof myObject', constructor would be set to myObject and possibleInstance would be set to someValue.
If this callback is NULL, 'instanceof' expressions that target your object will return false.
Standard JavaScript practice calls for objects that implement the callAsConstructor callback to implement the hasInstance callback as well.
*/
typedef bool
(*JSObjectHasInstanceCallback) (JSContextRef ctx, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception);
/*!
@typedef JSObjectConvertToTypeCallback
@abstract The callback invoked when converting an object to a particular JavaScript type.
@param ctx The execution context to use.
@param object The JSObject to convert.
@param type A JSType specifying the JavaScript type to convert to.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result The objects's converted value, or NULL if the object was not converted.
@discussion If you named your function ConvertToType, you would declare it like this:
JSValueRef ConvertToType(JSContextRef ctx, JSObjectRef object, JSType type, JSValueRef* exception);
If this function returns false, the conversion request forwards to object's parent class chain (which includes the default object class).
This function is only invoked when converting an object to number or string. An object converted to boolean is 'true.' An object converted to object is itself.
*/
typedef JSValueRef
(*JSObjectConvertToTypeCallback) (JSContextRef ctx, JSObjectRef object, JSType type, JSValueRef* exception);
/*!
@struct JSStaticValue
@abstract This structure describes a statically declared value property.
@field name A null-terminated UTF8 string containing the property's name.
@field getProperty A JSObjectGetPropertyCallback to invoke when getting the property's value.
@field setProperty A JSObjectSetPropertyCallback to invoke when setting the property's value. May be NULL if the ReadOnly attribute is set.
@field attributes A logically ORed set of JSPropertyAttributes to give to the property.
*/
typedef struct {
const char* name;
JSObjectGetPropertyCallback getProperty;
JSObjectSetPropertyCallback setProperty;
JSPropertyAttributes attributes;
} JSStaticValue;
/*!
@struct JSStaticFunction
@abstract This structure describes a statically declared function property.
@field name A null-terminated UTF8 string containing the property's name.
@field callAsFunction A JSObjectCallAsFunctionCallback to invoke when the property is called as a function.
@field attributes A logically ORed set of JSPropertyAttributes to give to the property.
*/
typedef struct {
const char* name;
JSObjectCallAsFunctionCallback callAsFunction;
JSPropertyAttributes attributes;
} JSStaticFunction;
/*!
@struct JSClassDefinition
@abstract This structure contains properties and callbacks that define a type of object. All fields other than the version field are optional. Any pointer may be NULL.
@field version The version number of this structure. The current version is 0.
@field attributes A logically ORed set of JSClassAttributes to give to the class.
@field className A null-terminated UTF8 string containing the class's name.
@field parentClass A JSClass to set as the class's parent class. Pass NULL use the default object class.
@field staticValues A JSStaticValue array containing the class's statically declared value properties. Pass NULL to specify no statically declared value properties. The array must be terminated by a JSStaticValue whose name field is NULL.
@field staticFunctions A JSStaticFunction array containing the class's statically declared function properties. Pass NULL to specify no statically declared function properties. The array must be terminated by a JSStaticFunction whose name field is NULL.
@field initialize The callback invoked when an object is first created. Use this callback to initialize the object.
@field finalize The callback invoked when an object is finalized (prepared for garbage collection). Use this callback to release resources allocated for the object, and perform other cleanup.
@field hasProperty The callback invoked when determining whether an object has a property. If this field is NULL, getProperty is called instead. The hasProperty callback enables optimization in cases where only a property's existence needs to be known, not its value, and computing its value is expensive.
@field getProperty The callback invoked when getting a property's value.
@field setProperty The callback invoked when setting a property's value.
@field deleteProperty The callback invoked when deleting a property.
@field getPropertyNames The callback invoked when collecting the names of an object's properties.
@field callAsFunction The callback invoked when an object is called as a function.
@field hasInstance The callback invoked when an object is used as the target of an 'instanceof' expression.
@field callAsConstructor The callback invoked when an object is used as a constructor in a 'new' expression.
@field convertToType The callback invoked when converting an object to a particular JavaScript type.
@discussion The staticValues and staticFunctions arrays are the simplest and most efficient means for vending custom properties. Statically declared properties autmatically service requests like getProperty, setProperty, and getPropertyNames. Property access callbacks are required only to implement unusual properties, like array indexes, whose names are not known at compile-time.
If you named your getter function "GetX" and your setter function "SetX", you would declare a JSStaticValue array containing "X" like this:
JSStaticValue StaticValueArray[] = {
{ "X", GetX, SetX, kJSPropertyAttributeNone },
{ 0, 0, 0, 0 }
};
Standard JavaScript practice calls for storing function objects in prototypes, so they can be shared. The default JSClass created by JSClassCreate follows this idiom, instantiating objects with a shared, automatically generating prototype containing the class's function objects. The kJSClassAttributeNoAutomaticPrototype attribute specifies that a JSClass should not automatically generate such a prototype. The resulting JSClass instantiates objects with the default object prototype, and gives each instance object its own copy of the class's function objects.
A NULL callback specifies that the default object callback should substitute, except in the case of hasProperty, where it specifies that getProperty should substitute.
*/
typedef struct {
int version; /* current (and only) version is 0 */
JSClassAttributes attributes;
const char* className;
JSClassRef parentClass;
const JSStaticValue* staticValues;
const JSStaticFunction* staticFunctions;
JSObjectInitializeCallback initialize;
JSObjectFinalizeCallback finalize;
JSObjectHasPropertyCallback hasProperty;
JSObjectGetPropertyCallback getProperty;
JSObjectSetPropertyCallback setProperty;
JSObjectDeletePropertyCallback deleteProperty;
JSObjectGetPropertyNamesCallback getPropertyNames;
JSObjectCallAsFunctionCallback callAsFunction;
JSObjectCallAsConstructorCallback callAsConstructor;
JSObjectHasInstanceCallback hasInstance;
JSObjectConvertToTypeCallback convertToType;
} JSClassDefinition;
/*!
@const kJSClassDefinitionEmpty
@abstract A JSClassDefinition structure of the current version, filled with NULL pointers and having no attributes.
@discussion Use this constant as a convenience when creating class definitions. For example, to create a class definition with only a finalize method:
JSClassDefinition definition = kJSClassDefinitionEmpty;
definition.finalize = Finalize;
*/
JS_EXPORT extern const JSClassDefinition kJSClassDefinitionEmpty;
/*!
@function
@abstract Creates a JavaScript class suitable for use with JSObjectMake.
@param definition A JSClassDefinition that defines the class.
@result A JSClass with the given definition. Ownership follows the Create Rule.
*/
JS_EXPORT JSClassRef JSClassCreate(const JSClassDefinition* definition);
/*!
@function
@abstract Retains a JavaScript class.
@param jsClass The JSClass to retain.
@result A JSClass that is the same as jsClass.
*/
JS_EXPORT JSClassRef JSClassRetain(JSClassRef jsClass);
/*!
@function
@abstract Releases a JavaScript class.
@param jsClass The JSClass to release.
*/
JS_EXPORT void JSClassRelease(JSClassRef jsClass);
/*!
@function
@abstract Creates a JavaScript object.
@param ctx The execution context to use.
@param jsClass The JSClass to assign to the object. Pass NULL to use the default object class.
@param data A void* to set as the object's private data. Pass NULL to specify no private data.
@result A JSObject with the given class and private data.
@discussion The default object class does not allocate storage for private data, so you must provide a non-NULL jsClass to JSObjectMake if you want your object to be able to store private data.
data is set on the created object before the intialize methods in its class chain are called. This enables the initialize methods to retrieve and manipulate data through JSObjectGetPrivate.
*/
JS_EXPORT JSObjectRef JSObjectMake(JSContextRef ctx, JSClassRef jsClass, void* data);
/*!
@function
@abstract Convenience method for creating a JavaScript function with a given callback as its implementation.
@param ctx The execution context to use.
@param name A JSString containing the function's name. This will be used when converting the function to string. Pass NULL to create an anonymous function.
@param callAsFunction The JSObjectCallAsFunctionCallback to invoke when the function is called.
@result A JSObject that is a function. The object's prototype will be the default function prototype.
*/
JS_EXPORT JSObjectRef JSObjectMakeFunctionWithCallback(JSContextRef ctx, JSStringRef name, JSObjectCallAsFunctionCallback callAsFunction);
/*!
@function
@abstract Convenience method for creating a JavaScript constructor.
@param ctx The execution context to use.
@param jsClass A JSClass that is the class your constructor will assign to the objects its constructs. jsClass will be used to set the constructor's .prototype property, and to evaluate 'instanceof' expressions. Pass NULL to use the default object class.
@param callAsConstructor A JSObjectCallAsConstructorCallback to invoke when your constructor is used in a 'new' expression. Pass NULL to use the default object constructor.
@result A JSObject that is a constructor. The object's prototype will be the default object prototype.
@discussion The default object constructor takes no arguments and constructs an object of class jsClass with no private data.
*/
JS_EXPORT JSObjectRef JSObjectMakeConstructor(JSContextRef ctx, JSClassRef jsClass, JSObjectCallAsConstructorCallback callAsConstructor);
/*!
@function
@abstract Creates a JavaScript Array object.
@param ctx The execution context to use.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of data to populate the Array with. Pass NULL if argumentCount is 0.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObject that is an Array.
@discussion The behavior of this function does not exactly match the behavior of the built-in Array constructor. Specifically, if one argument
is supplied, this function returns an array with one element.
*/
JS_EXPORT JSObjectRef JSObjectMakeArray(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) CF_AVAILABLE(10_6, 7_0);
/*!
@function
@abstract Creates a JavaScript Date object, as if by invoking the built-in Date constructor.
@param ctx The execution context to use.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of arguments to pass to the Date Constructor. Pass NULL if argumentCount is 0.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObject that is a Date.
*/
JS_EXPORT JSObjectRef JSObjectMakeDate(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) CF_AVAILABLE(10_6, 7_0);
/*!
@function
@abstract Creates a JavaScript Error object, as if by invoking the built-in Error constructor.
@param ctx The execution context to use.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of arguments to pass to the Error Constructor. Pass NULL if argumentCount is 0.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObject that is a Error.
*/
JS_EXPORT JSObjectRef JSObjectMakeError(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) CF_AVAILABLE(10_6, 7_0);
/*!
@function
@abstract Creates a JavaScript RegExp object, as if by invoking the built-in RegExp constructor.
@param ctx The execution context to use.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of arguments to pass to the RegExp Constructor. Pass NULL if argumentCount is 0.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObject that is a RegExp.
*/
JS_EXPORT JSObjectRef JSObjectMakeRegExp(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) CF_AVAILABLE(10_6, 7_0);
/*!
@function
@abstract Creates a function with a given script as its body.
@param ctx The execution context to use.
@param name A JSString containing the function's name. This will be used when converting the function to string. Pass NULL to create an anonymous function.
@param parameterCount An integer count of the number of parameter names in parameterNames.
@param parameterNames A JSString array containing the names of the function's parameters. Pass NULL if parameterCount is 0.
@param body A JSString containing the script to use as the function's body.
@param sourceURL A JSString containing a URL for the script's source file. This is only used when reporting exceptions. Pass NULL if you do not care to include source file information in exceptions.
@param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions. The value is one-based, so the first line is line 1 and invalid values are clamped to 1.
@param exception A pointer to a JSValueRef in which to store a syntax error exception, if any. Pass NULL if you do not care to store a syntax error exception.
@result A JSObject that is a function, or NULL if either body or parameterNames contains a syntax error. The object's prototype will be the default function prototype.
@discussion Use this method when you want to execute a script repeatedly, to avoid the cost of re-parsing the script before each execution.
*/
JS_EXPORT JSObjectRef JSObjectMakeFunction(JSContextRef ctx, JSStringRef name, unsigned parameterCount, const JSStringRef parameterNames[], JSStringRef body, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception);
/*!
@function
@abstract Gets an object's prototype.
@param ctx The execution context to use.
@param object A JSObject whose prototype you want to get.
@result A JSValue that is the object's prototype.
*/
JS_EXPORT JSValueRef JSObjectGetPrototype(JSContextRef ctx, JSObjectRef object);
/*!
@function
@abstract Sets an object's prototype.
@param ctx The execution context to use.
@param object The JSObject whose prototype you want to set.
@param value A JSValue to set as the object's prototype.
*/
JS_EXPORT void JSObjectSetPrototype(JSContextRef ctx, JSObjectRef object, JSValueRef value);
/*!
@function
@abstract Tests whether an object has a given property.
@param object The JSObject to test.
@param propertyName A JSString containing the property's name.
@result true if the object has a property whose name matches propertyName, otherwise false.
*/
JS_EXPORT bool JSObjectHasProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
/*!
@function
@abstract Gets a property from an object.
@param ctx The execution context to use.
@param object The JSObject whose property you want to get.
@param propertyName A JSString containing the property's name.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The property's value if object has the property, otherwise the undefined value.
*/
JS_EXPORT JSValueRef JSObjectGetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
/*!
@function
@abstract Sets a property on an object.
@param ctx The execution context to use.
@param object The JSObject whose property you want to set.
@param propertyName A JSString containing the property's name.
@param value A JSValue to use as the property's value.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@param attributes A logically ORed set of JSPropertyAttributes to give to the property.
*/
JS_EXPORT void JSObjectSetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSPropertyAttributes attributes, JSValueRef* exception);
/*!
@function
@abstract Deletes a property from an object.
@param ctx The execution context to use.
@param object The JSObject whose property you want to delete.
@param propertyName A JSString containing the property's name.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result true if the delete operation succeeds, otherwise false (for example, if the property has the kJSPropertyAttributeDontDelete attribute set).
*/
JS_EXPORT bool JSObjectDeleteProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
/*!
@function
@abstract Gets a property from an object by numeric index.
@param ctx The execution context to use.
@param object The JSObject whose property you want to get.
@param propertyIndex An integer value that is the property's name.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The property's value if object has the property, otherwise the undefined value.
@discussion Calling JSObjectGetPropertyAtIndex is equivalent to calling JSObjectGetProperty with a string containing propertyIndex, but JSObjectGetPropertyAtIndex provides optimized access to numeric properties.
*/
JS_EXPORT JSValueRef JSObjectGetPropertyAtIndex(JSContextRef ctx, JSObjectRef object, unsigned propertyIndex, JSValueRef* exception);
/*!
@function
@abstract Sets a property on an object by numeric index.
@param ctx The execution context to use.
@param object The JSObject whose property you want to set.
@param propertyIndex The property's name as a number.
@param value A JSValue to use as the property's value.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@discussion Calling JSObjectSetPropertyAtIndex is equivalent to calling JSObjectSetProperty with a string containing propertyIndex, but JSObjectSetPropertyAtIndex provides optimized access to numeric properties.
*/
JS_EXPORT void JSObjectSetPropertyAtIndex(JSContextRef ctx, JSObjectRef object, unsigned propertyIndex, JSValueRef value, JSValueRef* exception);
/*!
@function
@abstract Gets an object's private data.
@param object A JSObject whose private data you want to get.
@result A void* that is the object's private data, if the object has private data, otherwise NULL.
*/
JS_EXPORT void* JSObjectGetPrivate(JSObjectRef object);
/*!
@function
@abstract Sets a pointer to private data on an object.
@param object The JSObject whose private data you want to set.
@param data A void* to set as the object's private data.
@result true if object can store private data, otherwise false.
@discussion The default object class does not allocate storage for private data. Only objects created with a non-NULL JSClass can store private data.
*/
JS_EXPORT bool JSObjectSetPrivate(JSObjectRef object, void* data);
/*!
@function
@abstract Tests whether an object can be called as a function.
@param ctx The execution context to use.
@param object The JSObject to test.
@result true if the object can be called as a function, otherwise false.
*/
JS_EXPORT bool JSObjectIsFunction(JSContextRef ctx, JSObjectRef object);
/*!
@function
@abstract Calls an object as a function.
@param ctx The execution context to use.
@param object The JSObject to call as a function.
@param thisObject The object to use as "this," or NULL to use the global object as "this."
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of arguments to pass to the function. Pass NULL if argumentCount is 0.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The JSValue that results from calling object as a function, or NULL if an exception is thrown or object is not a function.
*/
JS_EXPORT JSValueRef JSObjectCallAsFunction(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
/*!
@function
@abstract Tests whether an object can be called as a constructor.
@param ctx The execution context to use.
@param object The JSObject to test.
@result true if the object can be called as a constructor, otherwise false.
*/
JS_EXPORT bool JSObjectIsConstructor(JSContextRef ctx, JSObjectRef object);
/*!
@function
@abstract Calls an object as a constructor.
@param ctx The execution context to use.
@param object The JSObject to call as a constructor.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of arguments to pass to the constructor. Pass NULL if argumentCount is 0.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The JSObject that results from calling object as a constructor, or NULL if an exception is thrown or object is not a constructor.
*/
JS_EXPORT JSObjectRef JSObjectCallAsConstructor(JSContextRef ctx, JSObjectRef object, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
/*!
@function
@abstract Gets the names of an object's enumerable properties.
@param ctx The execution context to use.
@param object The object whose property names you want to get.
@result A JSPropertyNameArray containing the names object's enumerable properties. Ownership follows the Create Rule.
*/
JS_EXPORT JSPropertyNameArrayRef JSObjectCopyPropertyNames(JSContextRef ctx, JSObjectRef object);
/*!
@function
@abstract Retains a JavaScript property name array.
@param array The JSPropertyNameArray to retain.
@result A JSPropertyNameArray that is the same as array.
*/
JS_EXPORT JSPropertyNameArrayRef JSPropertyNameArrayRetain(JSPropertyNameArrayRef array);
/*!
@function
@abstract Releases a JavaScript property name array.
@param array The JSPropetyNameArray to release.
*/
JS_EXPORT void JSPropertyNameArrayRelease(JSPropertyNameArrayRef array);
/*!
@function
@abstract Gets a count of the number of items in a JavaScript property name array.
@param array The array from which to retrieve the count.
@result An integer count of the number of names in array.
*/
JS_EXPORT size_t JSPropertyNameArrayGetCount(JSPropertyNameArrayRef array);
/*!
@function
@abstract Gets a property name at a given index in a JavaScript property name array.
@param array The array from which to retrieve the property name.
@param index The index of the property name to retrieve.
@result A JSStringRef containing the property name.
*/
JS_EXPORT JSStringRef JSPropertyNameArrayGetNameAtIndex(JSPropertyNameArrayRef array, size_t index);
/*!
@function
@abstract Adds a property name to a JavaScript property name accumulator.
@param accumulator The accumulator object to which to add the property name.
@param propertyName The property name to add.
*/
JS_EXPORT void JSPropertyNameAccumulatorAddName(JSPropertyNameAccumulatorRef accumulator, JSStringRef propertyName);
#ifdef __cplusplus
}
#endif
#endif /* JSObjectRef_h */

View File

@ -0,0 +1,74 @@
/*
* Copyright (C) 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSObjectRefPrivate_h
#define JSObjectRefPrivate_h
#include <JavaScriptCore/JSObjectRef.h>
#ifdef __cplusplus
extern "C" {
#endif
/*!
@function
@abstract Sets a private property on an object. This private property cannot be accessed from within JavaScript.
@param ctx The execution context to use.
@param object The JSObject whose private property you want to set.
@param propertyName A JSString containing the property's name.
@param value A JSValue to use as the property's value. This may be NULL.
@result true if object can store private data, otherwise false.
@discussion This API allows you to store JS values directly an object in a way that will be ensure that they are kept alive without exposing them to JavaScript code and without introducing the reference cycles that may occur when using JSValueProtect.
The default object class does not allocate storage for private data. Only objects created with a non-NULL JSClass can store private properties.
*/
JS_EXPORT bool JSObjectSetPrivateProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value);
/*!
@function
@abstract Gets a private property from an object.
@param ctx The execution context to use.
@param object The JSObject whose private property you want to get.
@param propertyName A JSString containing the property's name.
@result The property's value if object has the property, otherwise NULL.
*/
JS_EXPORT JSValueRef JSObjectGetPrivateProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
/*!
@function
@abstract Deletes a private property from an object.
@param ctx The execution context to use.
@param object The JSObject whose private property you want to delete.
@param propertyName A JSString containing the property's name.
@result true if object can store private data, otherwise false.
@discussion The default object class does not allocate storage for private data. Only objects created with a non-NULL JSClass can store private data.
*/
JS_EXPORT bool JSObjectDeletePrivateProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
#ifdef __cplusplus
}
#endif
#endif // JSObjectRefPrivate_h

View File

@ -0,0 +1,215 @@
/*
* Copyright (C) 2005, 2006, 2007, 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSRetainPtr_h
#define JSRetainPtr_h
#include <JavaScriptCore/JSContextRef.h>
#include <JavaScriptCore/JSStringRef.h>
#include <algorithm>
inline void JSRetain(JSStringRef string) { JSStringRetain(string); }
inline void JSRelease(JSStringRef string) { JSStringRelease(string); }
inline void JSRetain(JSGlobalContextRef context) { JSGlobalContextRetain(context); }
inline void JSRelease(JSGlobalContextRef context) { JSGlobalContextRelease(context); }
enum AdoptTag { Adopt };
template<typename T> class JSRetainPtr {
public:
JSRetainPtr() : m_ptr(0) { }
JSRetainPtr(T ptr) : m_ptr(ptr) { if (ptr) JSRetain(ptr); }
JSRetainPtr(AdoptTag, T ptr) : m_ptr(ptr) { }
JSRetainPtr(const JSRetainPtr&);
template<typename U> JSRetainPtr(const JSRetainPtr<U>&);
~JSRetainPtr();
T get() const { return m_ptr; }
void clear();
T leakRef();
T operator->() const { return m_ptr; }
bool operator!() const { return !m_ptr; }
explicit operator bool() const { return m_ptr; }
JSRetainPtr& operator=(const JSRetainPtr&);
template<typename U> JSRetainPtr& operator=(const JSRetainPtr<U>&);
JSRetainPtr& operator=(T);
template<typename U> JSRetainPtr& operator=(U*);
void adopt(T);
void swap(JSRetainPtr&);
private:
T m_ptr;
};
inline JSRetainPtr<JSStringRef> adopt(JSStringRef o)
{
return JSRetainPtr<JSStringRef>(Adopt, o);
}
inline JSRetainPtr<JSGlobalContextRef> adopt(JSGlobalContextRef o)
{
return JSRetainPtr<JSGlobalContextRef>(Adopt, o);
}
template<typename T> inline JSRetainPtr<T>::JSRetainPtr(const JSRetainPtr& o)
: m_ptr(o.m_ptr)
{
if (m_ptr)
JSRetain(m_ptr);
}
template<typename T> template<typename U> inline JSRetainPtr<T>::JSRetainPtr(const JSRetainPtr<U>& o)
: m_ptr(o.get())
{
if (m_ptr)
JSRetain(m_ptr);
}
template<typename T> inline JSRetainPtr<T>::~JSRetainPtr()
{
if (m_ptr)
JSRelease(m_ptr);
}
template<typename T> inline void JSRetainPtr<T>::clear()
{
if (T ptr = m_ptr) {
m_ptr = 0;
JSRelease(ptr);
}
}
template<typename T> inline T JSRetainPtr<T>::leakRef()
{
T ptr = m_ptr;
m_ptr = 0;
return ptr;
}
template<typename T> inline JSRetainPtr<T>& JSRetainPtr<T>::operator=(const JSRetainPtr<T>& o)
{
T optr = o.get();
if (optr)
JSRetain(optr);
T ptr = m_ptr;
m_ptr = optr;
if (ptr)
JSRelease(ptr);
return *this;
}
template<typename T> template<typename U> inline JSRetainPtr<T>& JSRetainPtr<T>::operator=(const JSRetainPtr<U>& o)
{
T optr = o.get();
if (optr)
JSRetain(optr);
T ptr = m_ptr;
m_ptr = optr;
if (ptr)
JSRelease(ptr);
return *this;
}
template<typename T> inline JSRetainPtr<T>& JSRetainPtr<T>::operator=(T optr)
{
if (optr)
JSRetain(optr);
T ptr = m_ptr;
m_ptr = optr;
if (ptr)
JSRelease(ptr);
return *this;
}
template<typename T> inline void JSRetainPtr<T>::adopt(T optr)
{
T ptr = m_ptr;
m_ptr = optr;
if (ptr)
JSRelease(ptr);
}
template<typename T> template<typename U> inline JSRetainPtr<T>& JSRetainPtr<T>::operator=(U* optr)
{
if (optr)
JSRetain(optr);
T ptr = m_ptr;
m_ptr = optr;
if (ptr)
JSRelease(ptr);
return *this;
}
template<typename T> inline void JSRetainPtr<T>::swap(JSRetainPtr<T>& o)
{
std::swap(m_ptr, o.m_ptr);
}
template<typename T> inline void swap(JSRetainPtr<T>& a, JSRetainPtr<T>& b)
{
a.swap(b);
}
template<typename T, typename U> inline bool operator==(const JSRetainPtr<T>& a, const JSRetainPtr<U>& b)
{
return a.get() == b.get();
}
template<typename T, typename U> inline bool operator==(const JSRetainPtr<T>& a, U* b)
{
return a.get() == b;
}
template<typename T, typename U> inline bool operator==(T* a, const JSRetainPtr<U>& b)
{
return a == b.get();
}
template<typename T, typename U> inline bool operator!=(const JSRetainPtr<T>& a, const JSRetainPtr<U>& b)
{
return a.get() != b.get();
}
template<typename T, typename U> inline bool operator!=(const JSRetainPtr<T>& a, U* b)
{
return a.get() != b;
}
template<typename T, typename U> inline bool operator!=(T* a, const JSRetainPtr<U>& b)
{
return a != b.get();
}
#endif // JSRetainPtr_h

View File

@ -0,0 +1,148 @@
/*
* Copyright (C) 2006 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSStringRef_h
#define JSStringRef_h
#include <JavaScriptCore/JSValueRef.h>
#ifndef __cplusplus
#include <stdbool.h>
#endif
#include <stddef.h> /* for size_t */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(_NATIVE_WCHAR_T_DEFINED) /* MSVC */ \
&& (!defined(__WCHAR_MAX__) || (__WCHAR_MAX__ > 0xffffU)) /* ISO C/C++ */ \
&& (!defined(WCHAR_MAX) || (WCHAR_MAX > 0xffffU)) /* RVCT */
/*!
@typedef JSChar
@abstract A UTF-16 code unit. One, or a sequence of two, can encode any Unicode
character. As with all scalar types, endianness depends on the underlying
architecture.
*/
typedef unsigned short JSChar;
#else
typedef wchar_t JSChar;
#endif
/*!
@function
@abstract Creates a JavaScript string from a buffer of Unicode characters.
@param chars The buffer of Unicode characters to copy into the new JSString.
@param numChars The number of characters to copy from the buffer pointed to by chars.
@result A JSString containing chars. Ownership follows the Create Rule.
*/
JS_EXPORT JSStringRef JSStringCreateWithCharacters(const JSChar* chars, size_t numChars);
/*!
@function
@abstract Creates a JavaScript string from a null-terminated UTF8 string.
@param string The null-terminated UTF8 string to copy into the new JSString.
@result A JSString containing string. Ownership follows the Create Rule.
*/
JS_EXPORT JSStringRef JSStringCreateWithUTF8CString(const char* string);
/*!
@function
@abstract Retains a JavaScript string.
@param string The JSString to retain.
@result A JSString that is the same as string.
*/
JS_EXPORT JSStringRef JSStringRetain(JSStringRef string);
/*!
@function
@abstract Releases a JavaScript string.
@param string The JSString to release.
*/
JS_EXPORT void JSStringRelease(JSStringRef string);
/*!
@function
@abstract Returns the number of Unicode characters in a JavaScript string.
@param string The JSString whose length (in Unicode characters) you want to know.
@result The number of Unicode characters stored in string.
*/
JS_EXPORT size_t JSStringGetLength(JSStringRef string);
/*!
@function
@abstract Returns a pointer to the Unicode character buffer that
serves as the backing store for a JavaScript string.
@param string The JSString whose backing store you want to access.
@result A pointer to the Unicode character buffer that serves as string's
backing store, which will be deallocated when string is deallocated.
*/
JS_EXPORT const JSChar* JSStringGetCharactersPtr(JSStringRef string);
/*!
@function
@abstract Returns the maximum number of bytes a JavaScript string will
take up if converted into a null-terminated UTF8 string.
@param string The JSString whose maximum converted size (in bytes) you
want to know.
@result The maximum number of bytes that could be required to convert string into a
null-terminated UTF8 string. The number of bytes that the conversion actually ends
up requiring could be less than this, but never more.
*/
JS_EXPORT size_t JSStringGetMaximumUTF8CStringSize(JSStringRef string);
/*!
@function
@abstract Converts a JavaScript string into a null-terminated UTF8 string,
and copies the result into an external byte buffer.
@param string The source JSString.
@param buffer The destination byte buffer into which to copy a null-terminated
UTF8 representation of string. On return, buffer contains a UTF8 string
representation of string. If bufferSize is too small, buffer will contain only
partial results. If buffer is not at least bufferSize bytes in size,
behavior is undefined.
@param bufferSize The size of the external buffer in bytes.
@result The number of bytes written into buffer (including the null-terminator byte).
*/
JS_EXPORT size_t JSStringGetUTF8CString(JSStringRef string, char* buffer, size_t bufferSize);
/*!
@function
@abstract Tests whether two JavaScript strings match.
@param a The first JSString to test.
@param b The second JSString to test.
@result true if the two strings match, otherwise false.
*/
JS_EXPORT bool JSStringIsEqual(JSStringRef a, JSStringRef b);
/*!
@function
@abstract Tests whether a JavaScript string matches a null-terminated UTF8 string.
@param a The JSString to test.
@param b The null-terminated UTF8 string to test.
@result true if the two strings match, otherwise false.
*/
JS_EXPORT bool JSStringIsEqualToUTF8CString(JSStringRef a, const char* b);
#ifdef __cplusplus
}
#endif
#endif /* JSStringRef_h */

View File

@ -0,0 +1,180 @@
/*
* Copyright (C) 2015 Dominic Szablewski (dominic@phoboslab.org)
* Copyright (C) 2015-2016 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSTypedArray_h
#define JSTypedArray_h
#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/JSValueRef.h>
#ifdef __cplusplus
extern "C" {
#endif
// ------------- Typed Array functions --------------
/*!
@function
@abstract Creates a JavaScript Typed Array object with the given number of elements.
@param ctx The execution context to use.
@param arrayType A value identifying the type of array to create. If arrayType is kJSTypedArrayTypeNone or kJSTypedArrayTypeArrayBuffer then NULL will be returned.
@param length The number of elements to be in the new Typed Array.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObjectRef that is a Typed Array with all elements set to zero or NULL if there was an error.
*/
JS_EXPORT JSObjectRef JSObjectMakeTypedArray(JSContextRef ctx, JSTypedArrayType arrayType, size_t length, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Creates a JavaScript Typed Array object from an existing pointer.
@param ctx The execution context to use.
@param arrayType A value identifying the type of array to create. If arrayType is kJSTypedArrayTypeNone or kJSTypedArrayTypeArrayBuffer then NULL will be returned.
@param bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object.
@param byteLength The number of bytes pointed to by the parameter bytes.
@param bytesDeallocator The allocator to use to deallocate the external buffer when the JSTypedArrayData object is deallocated.
@param deallocatorContext A pointer to pass back to the deallocator.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObjectRef Typed Array whose backing store is the same as the one pointed to by bytes or NULL if there was an error.
@discussion If an exception is thrown during this function the bytesDeallocator will always be called.
*/
JS_EXPORT JSObjectRef JSObjectMakeTypedArrayWithBytesNoCopy(JSContextRef ctx, JSTypedArrayType arrayType, void* bytes, size_t byteLength, JSTypedArrayBytesDeallocator bytesDeallocator, void* deallocatorContext, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Creates a JavaScript Typed Array object from an existing JavaScript Array Buffer object.
@param ctx The execution context to use.
@param arrayType A value identifying the type of array to create. If arrayType is kJSTypedArrayTypeNone or kJSTypedArrayTypeArrayBuffer then NULL will be returned.
@param buffer An Array Buffer object that should be used as the backing store for the created JavaScript Typed Array object.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObjectRef that is a Typed Array or NULL if there was an error. The backing store of the Typed Array will be buffer.
*/
JS_EXPORT JSObjectRef JSObjectMakeTypedArrayWithArrayBuffer(JSContextRef ctx, JSTypedArrayType arrayType, JSObjectRef buffer, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Creates a JavaScript Typed Array object from an existing JavaScript Array Buffer object with the given offset and length.
@param ctx The execution context to use.
@param arrayType A value identifying the type of array to create. If arrayType is kJSTypedArrayTypeNone or kJSTypedArrayTypeArrayBuffer then NULL will be returned.
@param buffer An Array Buffer object that should be used as the backing store for the created JavaScript Typed Array object.
@param byteOffset The byte offset for the created Typed Array. byteOffset should aligned with the element size of arrayType.
@param length The number of elements to include in the Typed Array.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObjectRef that is a Typed Array or NULL if there was an error. The backing store of the Typed Array will be buffer.
*/
JS_EXPORT JSObjectRef JSObjectMakeTypedArrayWithArrayBufferAndOffset(JSContextRef ctx, JSTypedArrayType arrayType, JSObjectRef buffer, size_t byteOffset, size_t length, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Returns a temporary pointer to the backing store of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The Typed Array object whose backing store pointer to return.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A pointer to the raw data buffer that serves as object's backing store or NULL if object is not a Typed Array object.
@discussion The pointer returned by this function is temporary and is not guaranteed to remain valid across JavaScriptCore API calls.
*/
JS_EXPORT void* JSObjectGetTypedArrayBytesPtr(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Returns the length of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The Typed Array object whose length to return.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The length of the Typed Array object or 0 if the object is not a Typed Array object.
*/
JS_EXPORT size_t JSObjectGetTypedArrayLength(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Returns the byte length of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The Typed Array object whose byte length to return.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The byte length of the Typed Array object or 0 if the object is not a Typed Array object.
*/
JS_EXPORT size_t JSObjectGetTypedArrayByteLength(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Returns the byte offset of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The Typed Array object whose byte offset to return.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The byte offset of the Typed Array object or 0 if the object is not a Typed Array object.
*/
JS_EXPORT size_t JSObjectGetTypedArrayByteOffset(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Returns the JavaScript Array Buffer object that is used as the backing of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The JSObjectRef whose Typed Array type data pointer to obtain.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObjectRef with a JSTypedArrayType of kJSTypedArrayTypeArrayBuffer or NULL if object is not a Typed Array.
*/
JS_EXPORT JSObjectRef JSObjectGetTypedArrayBuffer(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
// ------------- Array Buffer functions -------------
/*!
@function
@abstract Creates a JavaScript Array Buffer object from an existing pointer.
@param ctx The execution context to use.
@param bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object.
@param byteLength The number of bytes pointed to by the parameter bytes.
@param bytesDeallocator The allocator to use to deallocate the external buffer when the Typed Array data object is deallocated.
@param deallocatorContext A pointer to pass back to the deallocator.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObjectRef Array Buffer whose backing store is the same as the one pointed to by bytes or NULL if there was an error.
@discussion If an exception is thrown during this function the bytesDeallocator will always be called.
*/
JS_EXPORT JSObjectRef JSObjectMakeArrayBufferWithBytesNoCopy(JSContextRef ctx, void* bytes, size_t byteLength, JSTypedArrayBytesDeallocator bytesDeallocator, void* deallocatorContext, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Returns a pointer to the data buffer that serves as the backing store for a JavaScript Typed Array object.
@param object The Array Buffer object whose internal backing store pointer to return.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A pointer to the raw data buffer that serves as object's backing store or NULL if object is not an Array Buffer object.
@discussion The pointer returned by this function is temporary and is not guaranteed to remain valid across JavaScriptCore API calls.
*/
JS_EXPORT void* JSObjectGetArrayBufferBytesPtr(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Returns the number of bytes in a JavaScript data object.
@param ctx The execution context to use.
@param object The JS Arary Buffer object whose length in bytes to return.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The number of bytes stored in the data object.
*/
JS_EXPORT size_t JSObjectGetArrayBufferByteLength(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
#ifdef __cplusplus
}
#endif
#endif /* JSTypedArray_h */

View File

@ -0,0 +1,359 @@
/*
* Copyright (C) 2006 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSValueRef_h
#define JSValueRef_h
#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/WebKitAvailability.h>
#ifndef __cplusplus
#include <stdbool.h>
#endif
/*!
@enum JSType
@abstract A constant identifying the type of a JSValue.
@constant kJSTypeUndefined The unique undefined value.
@constant kJSTypeNull The unique null value.
@constant kJSTypeBoolean A primitive boolean value, one of true or false.
@constant kJSTypeNumber A primitive number value.
@constant kJSTypeString A primitive string value.
@constant kJSTypeObject An object value (meaning that this JSValueRef is a JSObjectRef).
*/
typedef enum {
kJSTypeUndefined,
kJSTypeNull,
kJSTypeBoolean,
kJSTypeNumber,
kJSTypeString,
kJSTypeObject
} JSType;
/*!
@enum JSTypedArrayType
@abstract A constant identifying the Typed Array type of a JSObjectRef.
@constant kJSTypedArrayTypeInt8Array Int8Array
@constant kJSTypedArrayTypeInt16Array Int16Array
@constant kJSTypedArrayTypeInt32Array Int32Array
@constant kJSTypedArrayTypeUint8Array Uint8Array
@constant kJSTypedArrayTypeUint8ClampedArray Uint8ClampedArray
@constant kJSTypedArrayTypeUint16Array Uint16Array
@constant kJSTypedArrayTypeUint32Array Uint32Array
@constant kJSTypedArrayTypeFloat32Array Float32Array
@constant kJSTypedArrayTypeFloat64Array Float64Array
@constant kJSTypedArrayTypeArrayBuffer ArrayBuffer
@constant kJSTypedArrayTypeNone Not a Typed Array
*/
typedef enum {
kJSTypedArrayTypeInt8Array,
kJSTypedArrayTypeInt16Array,
kJSTypedArrayTypeInt32Array,
kJSTypedArrayTypeUint8Array,
kJSTypedArrayTypeUint8ClampedArray,
kJSTypedArrayTypeUint16Array,
kJSTypedArrayTypeUint32Array,
kJSTypedArrayTypeFloat32Array,
kJSTypedArrayTypeFloat64Array,
kJSTypedArrayTypeArrayBuffer,
kJSTypedArrayTypeNone,
} JSTypedArrayType CF_ENUM_AVAILABLE(10_12, 10_0);
#ifdef __cplusplus
extern "C" {
#endif
/*!
@function
@abstract Returns a JavaScript value's type.
@param ctx The execution context to use.
@param value The JSValue whose type you want to obtain.
@result A value of type JSType that identifies value's type.
*/
JS_EXPORT JSType JSValueGetType(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the undefined type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the undefined type, otherwise false.
*/
JS_EXPORT bool JSValueIsUndefined(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the null type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the null type, otherwise false.
*/
JS_EXPORT bool JSValueIsNull(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the boolean type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the boolean type, otherwise false.
*/
JS_EXPORT bool JSValueIsBoolean(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the number type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the number type, otherwise false.
*/
JS_EXPORT bool JSValueIsNumber(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the string type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the string type, otherwise false.
*/
JS_EXPORT bool JSValueIsString(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the object type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the object type, otherwise false.
*/
JS_EXPORT bool JSValueIsObject(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value is an object with a given class in its class chain.
@param ctx The execution context to use.
@param value The JSValue to test.
@param jsClass The JSClass to test against.
@result true if value is an object and has jsClass in its class chain, otherwise false.
*/
JS_EXPORT bool JSValueIsObjectOfClass(JSContextRef ctx, JSValueRef value, JSClassRef jsClass);
/*!
@function
@abstract Tests whether a JavaScript value is an array.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value is an array, otherwise false.
*/
JS_EXPORT bool JSValueIsArray(JSContextRef ctx, JSValueRef value) CF_AVAILABLE(10_11, 9_0);
/*!
@function
@abstract Tests whether a JavaScript value is a date.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value is a date, otherwise false.
*/
JS_EXPORT bool JSValueIsDate(JSContextRef ctx, JSValueRef value) CF_AVAILABLE(10_11, 9_0);
/*!
@function
@abstract Returns a JavaScript value's Typed Array type.
@param ctx The execution context to use.
@param value The JSValue whose Typed Array type to return.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A value of type JSTypedArrayType that identifies value's Typed Array type, or kJSTypedArrayTypeNone if the value is not a Typed Array object.
*/
JS_EXPORT JSTypedArrayType JSValueGetTypedArrayType(JSContextRef ctx, JSValueRef value, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/* Comparing values */
/*!
@function
@abstract Tests whether two JavaScript values are equal, as compared by the JS == operator.
@param ctx The execution context to use.
@param a The first value to test.
@param b The second value to test.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result true if the two values are equal, false if they are not equal or an exception is thrown.
*/
JS_EXPORT bool JSValueIsEqual(JSContextRef ctx, JSValueRef a, JSValueRef b, JSValueRef* exception);
/*!
@function
@abstract Tests whether two JavaScript values are strict equal, as compared by the JS === operator.
@param ctx The execution context to use.
@param a The first value to test.
@param b The second value to test.
@result true if the two values are strict equal, otherwise false.
*/
JS_EXPORT bool JSValueIsStrictEqual(JSContextRef ctx, JSValueRef a, JSValueRef b);
/*!
@function
@abstract Tests whether a JavaScript value is an object constructed by a given constructor, as compared by the JS instanceof operator.
@param ctx The execution context to use.
@param value The JSValue to test.
@param constructor The constructor to test against.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result true if value is an object constructed by constructor, as compared by the JS instanceof operator, otherwise false.
*/
JS_EXPORT bool JSValueIsInstanceOfConstructor(JSContextRef ctx, JSValueRef value, JSObjectRef constructor, JSValueRef* exception);
/* Creating values */
/*!
@function
@abstract Creates a JavaScript value of the undefined type.
@param ctx The execution context to use.
@result The unique undefined value.
*/
JS_EXPORT JSValueRef JSValueMakeUndefined(JSContextRef ctx);
/*!
@function
@abstract Creates a JavaScript value of the null type.
@param ctx The execution context to use.
@result The unique null value.
*/
JS_EXPORT JSValueRef JSValueMakeNull(JSContextRef ctx);
/*!
@function
@abstract Creates a JavaScript value of the boolean type.
@param ctx The execution context to use.
@param boolean The bool to assign to the newly created JSValue.
@result A JSValue of the boolean type, representing the value of boolean.
*/
JS_EXPORT JSValueRef JSValueMakeBoolean(JSContextRef ctx, bool boolean);
/*!
@function
@abstract Creates a JavaScript value of the number type.
@param ctx The execution context to use.
@param number The double to assign to the newly created JSValue.
@result A JSValue of the number type, representing the value of number.
*/
JS_EXPORT JSValueRef JSValueMakeNumber(JSContextRef ctx, double number);
/*!
@function
@abstract Creates a JavaScript value of the string type.
@param ctx The execution context to use.
@param string The JSString to assign to the newly created JSValue. The
newly created JSValue retains string, and releases it upon garbage collection.
@result A JSValue of the string type, representing the value of string.
*/
JS_EXPORT JSValueRef JSValueMakeString(JSContextRef ctx, JSStringRef string);
/* Converting to and from JSON formatted strings */
/*!
@function
@abstract Creates a JavaScript value from a JSON formatted string.
@param ctx The execution context to use.
@param string The JSString containing the JSON string to be parsed.
@result A JSValue containing the parsed value, or NULL if the input is invalid.
*/
JS_EXPORT JSValueRef JSValueMakeFromJSONString(JSContextRef ctx, JSStringRef string) CF_AVAILABLE(10_7, 7_0);
/*!
@function
@abstract Creates a JavaScript string containing the JSON serialized representation of a JS value.
@param ctx The execution context to use.
@param value The value to serialize.
@param indent The number of spaces to indent when nesting. If 0, the resulting JSON will not contains newlines. The size of the indent is clamped to 10 spaces.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSString with the result of serialization, or NULL if an exception is thrown.
*/
JS_EXPORT JSStringRef JSValueCreateJSONString(JSContextRef ctx, JSValueRef value, unsigned indent, JSValueRef* exception) CF_AVAILABLE(10_7, 7_0);
/* Converting to primitive values */
/*!
@function
@abstract Converts a JavaScript value to boolean and returns the resulting boolean.
@param ctx The execution context to use.
@param value The JSValue to convert.
@result The boolean result of conversion.
*/
JS_EXPORT bool JSValueToBoolean(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Converts a JavaScript value to number and returns the resulting number.
@param ctx The execution context to use.
@param value The JSValue to convert.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The numeric result of conversion, or NaN if an exception is thrown.
*/
JS_EXPORT double JSValueToNumber(JSContextRef ctx, JSValueRef value, JSValueRef* exception);
/*!
@function
@abstract Converts a JavaScript value to string and copies the result into a JavaScript string.
@param ctx The execution context to use.
@param value The JSValue to convert.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSString with the result of conversion, or NULL if an exception is thrown. Ownership follows the Create Rule.
*/
JS_EXPORT JSStringRef JSValueToStringCopy(JSContextRef ctx, JSValueRef value, JSValueRef* exception);
/*!
@function
@abstract Converts a JavaScript value to object and returns the resulting object.
@param ctx The execution context to use.
@param value The JSValue to convert.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The JSObject result of conversion, or NULL if an exception is thrown.
*/
JS_EXPORT JSObjectRef JSValueToObject(JSContextRef ctx, JSValueRef value, JSValueRef* exception);
/* Garbage collection */
/*!
@function
@abstract Protects a JavaScript value from garbage collection.
@param ctx The execution context to use.
@param value The JSValue to protect.
@discussion Use this method when you want to store a JSValue in a global or on the heap, where the garbage collector will not be able to discover your reference to it.
A value may be protected multiple times and must be unprotected an equal number of times before becoming eligible for garbage collection.
*/
JS_EXPORT void JSValueProtect(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Unprotects a JavaScript value from garbage collection.
@param ctx The execution context to use.
@param value The JSValue to unprotect.
@discussion A value may be protected multiple times and must be unprotected an
equal number of times before becoming eligible for garbage collection.
*/
JS_EXPORT void JSValueUnprotect(JSContextRef ctx, JSValueRef value);
#ifdef __cplusplus
}
#endif
#endif /* JSValueRef_h */

View File

@ -0,0 +1,37 @@
/*
* Copyright (C) 2006 Apple Inc. All rights reserved.
* Copyright (C) 2008 Alp Toker <alp@atoker.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JavaScript_h
#define JavaScript_h
#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/JSContextRef.h>
#include <JavaScriptCore/JSStringRef.h>
#include <JavaScriptCore/JSObjectRef.h>
#include <JavaScriptCore/JSTypedArray.h>
#include <JavaScriptCore/JSValueRef.h>
#endif /* JavaScript_h */

View File

@ -0,0 +1,85 @@
/*
* Copyright (C) 2008, 2009, 2010, 2014 Apple Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __WebKitAvailability__
#define __WebKitAvailability__
#if defined(__APPLE__) && defined(DEFINE_AVAILABILITY_MACROS)
#include <AvailabilityMacros.h>
#include <CoreFoundation/CoreFoundation.h>
#if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED < 101100
/* To support availability macros that mention newer OS X versions when building on older OS X versions,
we provide our own definitions of the underlying macros that the availability macros expand to. We're
free to expand the macros as no-ops since frameworks built on older OS X versions only ship bundled with
an application rather than as part of the system.
*/
#ifndef __NSi_10_10 // Building from trunk rather than SDK.
#define __NSi_10_10 introduced=10.0 // Use 10.0 to indicate that everything is available.
#endif
#ifndef __NSi_10_11 // Building from trunk rather than SDK.
#define __NSi_10_11 introduced=10.0 // Use 10.0 to indicate that everything is available.
#endif
#ifndef __NSi_10_12 // Building from trunk rather than SDK.
#define __NSi_10_12 introduced=10.0 // Use 10.0 to indicate that everything is available.
#endif
#ifndef __AVAILABILITY_INTERNAL__MAC_10_9
#define __AVAILABILITY_INTERNAL__MAC_10_9
#endif
#ifndef __AVAILABILITY_INTERNAL__MAC_10_10
#define __AVAILABILITY_INTERNAL__MAC_10_10
#endif
#ifndef AVAILABLE_MAC_OS_X_VERSION_10_9_AND_LATER
#define AVAILABLE_MAC_OS_X_VERSION_10_9_AND_LATER
#endif
#ifndef AVAILABLE_MAC_OS_X_VERSION_10_10_AND_LATER
#define AVAILABLE_MAC_OS_X_VERSION_10_10_AND_LATER
#endif
#endif /* __MAC_OS_X_VERSION_MIN_REQUIRED <= 101100 */
#if defined(BUILDING_GTK__)
#undef CF_AVAILABLE
#define CF_AVAILABLE(_mac, _ios)
#undef CF_ENUM_AVAILABLE
#define CF_ENUM_AVAILABLE(_mac, _ios)
#endif
#else
#ifndef CF_AVAILABLE
#define CF_AVAILABLE(_mac, _ios)
#define CF_ENUM_AVAILABLE(_mac, _ios)
#endif
#endif
#endif /* __WebKitAvailability__ */

224
include/Ultralight/Bitmap.h Normal file
View File

@ -0,0 +1,224 @@
///
/// @file Bitmap.h
///
/// @brief The header for the Bitmap class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/RefPtr.h>
#include <Ultralight/Geometry.h>
namespace ultralight {
#pragma pack(push, 1)
///
/// The various Bitmap formats.
///
enum UExport BitmapFormat {
/// Alpha-channel only, 8-bits per channel (8-bits in total per pixel)
kBitmapFormat_A8,
/// Red Green Blue Alpha, 8-bits per channel (32-bits in total per pixel)
kBitmapFormat_RGBA8
};
///
/// Macro to get the bytes per pixel from a BitmapFormat
///
#define GetBytesPerPixel(x) (x == kBitmapFormat_A8? 1 : 4)
///
/// @brief Bitmap container with basic blitting and conversion routines.
///
class UExport Bitmap : public RefCounted {
public:
///
/// Create an empty Bitmap. No pixels will be allocated.
///
static Ref<Bitmap> Create();
///
/// Create a Bitmap with a certain configuration. Pixels will be allocated
/// but not initialized.
///
/// @param width The width in pixels.
///
/// @param height The height in pixels.
///
/// @param format The pixel format to use.
///
/// @return A ref-pointer to a new Bitmap instance.
///
static Ref<Bitmap> Create(uint32_t width, uint32_t height, BitmapFormat format);
///
/// Create a Bitmap with existing pixels and configuration.
///
/// @param width The width in pixels.
///
/// @param height The height in pixels.
///
/// @param format The pixel format to use.
///
/// @param row_bytes The number of bytes between each row (note that this
/// value should be >= width * bytes_per_pixel).
///
/// @param pixels Pointer to raw pixel buffer.
///
/// @param size Size of the raw pixel buffer.
///
/// @param should_copy Whether or not a copy should be made of the pixels.
/// If this is false, the returned Bitmap will use the
/// raw pixels passed in as its own, but you are still
/// responsible for destroying your buffer afterwards.
///
/// @return A ref-pointer to a new Bitmap instance.
///
static Ref<Bitmap> Create(uint32_t width, uint32_t height, BitmapFormat format,
uint32_t row_bytes, const void* pixels, size_t size, bool should_copy = true);
///
/// Create a bitmap from a deep copy of another Bitmap.
///
static Ref<Bitmap> Create(const Bitmap& bitmap);
///
/// Get the width in pixels.
///
virtual uint32_t width() const = 0;
///
/// Get the height in pixels.
///
virtual uint32_t height() const = 0;
///
/// Get the bounds as an IntRect
///
virtual IntRect bounds() const = 0;
///
/// Get the pixel format.
///
virtual BitmapFormat format() const = 0;
///
/// Get the number of bytes per pixel.
///
virtual uint32_t bpp() const = 0;
///
/// Get the number of bytes between each row (this is always >= width * bpp)
///
virtual uint32_t row_bytes() const = 0;
///
/// Get the size in bytes of the pixel buffer.
///
virtual size_t size() const = 0;
///
/// Whether or not this Bitmap owns the pixel buffer and will destroy it
/// at the end of its lifetime.
///
virtual bool owns_pixels() const = 0;
///
/// Lock the pixel buffer for reading/writing.
///
/// @return A pointer to the pixel buffer.
///
virtual void* LockPixels() = 0;
///
/// Unlock the pixel buffer.
///
virtual void UnlockPixels() = 0;
///
/// Lock the pixel buffer for reading/writing. (const)
///
/// @return A const pointer to the pixel buffer.
///
virtual const void* LockPixels() const = 0;
///
/// Unlock the pixel buffer. (const)
///
virtual void UnlockPixels() const = 0;
///
/// Get the raw pixel buffer.
///
/// @note You should only call this if pixels are already locked.
///
virtual void* raw_pixels() = 0;
///
/// Whether or not this Bitmap is empty (no pixels allocated).
///
virtual bool IsEmpty() const = 0;
///
/// Erase the Bitmap (set all pixels to 0).
///
virtual void Erase() = 0;
///
/// Assign another bitmap to this one.
///
/// @param bitmap The bitmap to copy from.
///
virtual void Set(Ref<Bitmap> bitmap) = 0;
///
/// Draw another bitmap to this bitmap.
///
/// @note Formats do not need to match. Bitmap formats will be converted
/// to one another automatically. Note that when converting from
/// RGBA8 to A8, only the Red channel will be used.
///
/// @param src_rect The source rectangle, relative to src bitmap.
///
/// @param dest_rect The destination rectangle, relative to this bitmap.
///
/// @param src The source bitmap.
///
/// @param pad_repeat Whether or not we should pad the drawn bitmap by one
/// pixel of repeated edge pixels from the source bitmap.
///
/// @return Whether or not the operation succeeded (this can fail if the
/// src_rect and/or dest_rect are invalid, or if their total
/// dimensions do not match).
///
virtual bool DrawBitmap(IntRect src_rect, IntRect dest_rect,
Ref<Bitmap> src, bool pad_repeat) = 0;
///
/// Write this Bitmap out to a PNG image. (mainly used for Debug)
///
/// @param path The filepath to write to (opened with fopen())
///
/// @return Whether or not the operation succeeded.
///
virtual bool WritePNG(const char* path) = 0;
protected:
Bitmap();
virtual ~Bitmap();
Bitmap(const Bitmap&);
void operator=(const Bitmap&);
};
#pragma pack(pop)
} // namespace ultralight

View File

@ -0,0 +1,47 @@
///
/// @file Buffer.h
///
/// @brief The header for the Buffer class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/RefPtr.h>
namespace ultralight {
///
/// A fixed-size byte container for passing data around.
///
class UExport Buffer : public RefCounted {
public:
///
/// Create a Buffer, a copy of data is made.
///
static Ref<Buffer> Create(const void* data, size_t size);
///
/// Get a pointer to raw byte data.
///
virtual void* data() = 0;
///
/// Get the size in bytes.
///
virtual size_t size() const = 0;
protected:
Buffer();
virtual ~Buffer();
Buffer(const Buffer&);
void operator=(const Buffer&);
};
} // namespace ultralight

705
include/Ultralight/CAPI.h Normal file
View File

@ -0,0 +1,705 @@
///
/// @file CAPI.h
///
/// @brief The C-language API for Ultralight
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#ifndef ULTRALIGHT_CAPI_H
#define ULTRALIGHT_CAPI_H
#ifndef __cplusplus
//#include <stdbool.h>
#endif
#include <stddef.h>
#include <JavaScriptCore/JavaScript.h>
#ifdef __OBJC__
#import <AppKit/NSEvent.h>
#endif
#if defined(__WIN32__) || defined(_WIN32)
# if defined(ULTRALIGHT_IMPLEMENTATION)
# define ULExport __declspec(dllexport)
# else
# define ULExport __declspec(dllimport)
# endif
#define _thread_local __declspec(thread)
#ifndef _NATIVE_WCHAR_T_DEFINED
#define DISABLE_NATIVE_WCHAR_T
typedef unsigned short ULChar16;
#else
typedef wchar_t ULChar16;
#endif
#else
# define ULExport __attribute__((visibility("default")))
#define _thread_local __thread
typedef unsigned short ULChar16;
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef struct C_Config* ULConfig;
typedef struct C_Renderer* ULRenderer;
typedef struct C_View* ULView;
typedef struct C_Bitmap* ULBitmap;
typedef struct C_String* ULString;
typedef struct C_Buffer* ULBuffer;
typedef struct C_RenderTarget* ULRenderTarget;
typedef struct C_KeyEvent* ULKeyEvent;
typedef struct C_MouseEvent* ULMouseEvent;
typedef struct C_ScrollEvent* ULScrollEvent;
typedef enum {
kMessageSource_XML = 0,
kMessageSource_JS,
kMessageSource_Network,
kMessageSource_ConsoleAPI,
kMessageSource_Storage,
kMessageSource_AppCache,
kMessageSource_Rendering,
kMessageSource_CSS,
kMessageSource_Security,
kMessageSource_ContentBlocker,
kMessageSource_Other,
} ULMessageSource;
typedef enum {
kMessageLevel_Log = 1,
kMessageLevel_Warning = 2,
kMessageLevel_Error = 3,
kMessageLevel_Debug = 4,
kMessageLevel_Info = 5,
} ULMessageLevel;
typedef enum {
kCursor_Pointer = 0,
kCursor_Cross,
kCursor_Hand,
kCursor_IBeam,
kCursor_Wait,
kCursor_Help,
kCursor_EastResize,
kCursor_NorthResize,
kCursor_NorthEastResize,
kCursor_NorthWestResize,
kCursor_SouthResize,
kCursor_SouthEastResize,
kCursor_SouthWestResize,
kCursor_WestResize,
kCursor_NorthSouthResize,
kCursor_EastWestResize,
kCursor_NorthEastSouthWestResize,
kCursor_NorthWestSouthEastResize,
kCursor_ColumnResize,
kCursor_RowResize,
kCursor_MiddlePanning,
kCursor_EastPanning,
kCursor_NorthPanning,
kCursor_NorthEastPanning,
kCursor_NorthWestPanning,
kCursor_SouthPanning,
kCursor_SouthEastPanning,
kCursor_SouthWestPanning,
kCursor_WestPanning,
kCursor_Move,
kCursor_VerticalText,
kCursor_Cell,
kCursor_ContextMenu,
kCursor_Alias,
kCursor_Progress,
kCursor_NoDrop,
kCursor_Copy,
kCursor_None,
kCursor_NotAllowed,
kCursor_ZoomIn,
kCursor_ZoomOut,
kCursor_Grab,
kCursor_Grabbing,
kCursor_Custom
} ULCursor;
typedef enum {
kBitmapFormat_A8,
kBitmapFormat_RGBA8
} ULBitmapFormat;
typedef enum {
kKeyEventType_KeyDown,
kKeyEventType_KeyUp,
kKeyEventType_RawKeyDown,
kKeyEventType_Char,
} ULKeyEventType;
typedef enum {
kMouseEventType_MouseMoved,
kMouseEventType_MouseDown,
kMouseEventType_MouseUp,
} ULMouseEventType;
typedef enum {
kMouseButton_None = 0,
kMouseButton_Left,
kMouseButton_Middle,
kMouseButton_Right,
} ULMouseButton;
typedef enum {
kScrollEventType_ScrollByPixel,
kScrollEventType_ScrollByPage,
} ULScrollEventType;
/******************************************************************************
* API Note:
*
* You should only destroy objects that you explicitly create. Do not destroy
* any objects returned from the API or callbacks unless otherwise noted.
*****************************************************************************/
/******************************************************************************
* Config
*****************************************************************************/
///
/// Create config with default values (see <Ultralight/platform/Config.h>).
///
ULExport ULConfig ulCreateConfig();
///
/// Destroy config.
///
ULExport void ulDestroyConfig(ULConfig config);
///
/// Set whether images should be enabled (Default = True)
///
ULExport void ulConfigSetEnableImages(ULConfig config, bool enabled);
///
/// Set whether JavaScript should be eanbled (Default = True)
///
ULExport void ulConfigSetEnableJavaScript(ULConfig config, bool enabled);
///
/// Set whether we should use BGRA byte order (instead of RGBA) for View
/// bitmaps. (Default = False)
///
ULExport void ulConfigSetUseBGRAForOffscreenRendering(ULConfig config,
bool enabled);
///
/// Set the amount that the application DPI has been scaled, used for
/// scaling device coordinates to pixels and oversampling raster shapes.
/// (Default = 1.0)
///
ULExport void ulConfigSetDeviceScaleHint(ULConfig config, double value);
///
/// Set default font-family to use (Default = Times New Roman)
///
ULExport void ulConfigSetFontFamilyStandard(ULConfig config,
ULString font_name);
///
/// Set default font-family to use for fixed fonts, eg <pre> and <code>.
/// (Default = Courier New)
///
ULExport void ulConfigSetFontFamilyFixed(ULConfig config, ULString font_name);
///
/// Set default font-family to use for serif fonts. (Default = Times New Roman)
///
ULExport void ulConfigSetFontFamilySerif(ULConfig config, ULString font_name);
///
/// Set default font-family to use for sans-serif fonts. (Default = Arial)
///
ULExport void ulConfigSetFontFamilySansSerif(ULConfig config,
ULString font_name);
///
/// Set user agent string. (See <Ultralight/platform/Config.h> for the default)
///
ULExport void ulConfigSetUserAgent(ULConfig config, ULString agent_string);
///
/// Set user stylesheet (CSS). (Default = Empty)
///
ULExport void ulConfigSetUserStylesheet(ULConfig config, ULString css_string);
/******************************************************************************
* Renderer
*****************************************************************************/
///
/// Create renderer (create this only once per application lifetime).
///
ULExport ULRenderer ulCreateRenderer(ULConfig config);
///
/// Destroy renderer.
///
ULExport void ulDestroyRenderer(ULRenderer renderer);
///
/// Update timers and dispatch internal callbacks (JavaScript and network)
///
ULExport void ulUpdate(ULRenderer renderer);
///
/// Render all active Views to their respective bitmaps.
///
ULExport void ulRender(ULRenderer renderer);
/******************************************************************************
* View
*****************************************************************************/
///
/// Create a View with certain size (in device coordinates).
///
ULExport ULView ulCreateView(ULRenderer renderer, unsigned int width,
unsigned int height, bool transparent);
///
/// Destroy a View.
///
ULExport void ulDestroyView(ULView view);
///
/// Get current URL.
///
/// @note Don't destroy the returned string, it is owned by the View.
///
ULExport ULString ulViewGetURL(ULView view);
///
/// Get current title.
///
/// @note Don't destroy the returned string, it is owned by the View.
///
ULExport ULString ulViewGetTitle(ULView view);
///
/// Check if main frame is loading.
///
ULExport bool ulViewIsLoading(ULView view);
///
/// Check if bitmap is dirty (has changed since last call to ulViewGetBitmap)
///
ULExport bool ulViewIsBitmapDirty(ULView view);
///
/// Get bitmap (will reset the dirty flag).
///
/// @note Don't destroy the returned bitmap, it is owned by the View.
///
ULExport ULBitmap ulViewGetBitmap(ULView view);
///
/// Load a raw string of html
///
ULExport void ulViewLoadHTML(ULView view, ULString html_string);
///
/// Load a URL into main frame
///
ULExport void ulViewLoadURL(ULView view, ULString url_string);
///
/// Resize view to a certain width and height (in device coordinates)
///
ULExport void ulViewResize(ULView view, unsigned int width,
unsigned int height);
///
/// Get the page's JSContext for use with JavaScriptCore API
///
ULExport JSContextRef ulViewGetJSContext(ULView view);
///
/// Evaluate a raw string of JavaScript and return result
///
ULExport JSValueRef ulViewEvaluateScript(ULView view, ULString js_string);
///
/// Check if can navigate backwards in history
///
ULExport bool ulViewCanGoBack(ULView view);
///
/// Check if can navigate forwards in history
///
ULExport bool ulViewCanGoForward(ULView view);
///
/// Navigate backwards in history
///
ULExport void ulViewGoBack(ULView view);
///
/// Navigate forwards in history
///
ULExport void ulViewGoForward(ULView view);
///
/// Navigate to arbitrary offset in history
///
ULExport void ulViewGoToHistoryOffset(ULView view, int offset);
///
/// Reload current page
///
ULExport void ulViewReload(ULView view);
///
/// Stop all page loads
///
ULExport void ulViewStop(ULView view);
///
/// Fire a keyboard event
///
ULExport void ulViewFireKeyEvent(ULView view, ULKeyEvent key_event);
///
/// Fire a mouse event
///
ULExport void ulViewFireMouseEvent(ULView view, ULMouseEvent mouse_event);
///
/// Fire a scroll event
///
ULExport void ulViewFireScrollEvent(ULView view, ULScrollEvent scroll_event);
typedef void
(*ULChangeTitleCallback) (void* user_data, ULView caller, ULString title);
///
/// Set callback for when the page title changes
///
ULExport void ulViewSetChangeTitleCallback(ULView view,
ULChangeTitleCallback callback,
void* user_data);
typedef void
(*ULChangeURLCallback) (void* user_data, ULView caller, ULString url);
///
/// Set callback for when the page URL changes
///
ULExport void ulViewSetChangeURLCallback(ULView view,
ULChangeURLCallback callback,
void* user_data);
typedef void
(*ULChangeTooltipCallback) (void* user_data, ULView caller, ULString tooltip);
///
/// Set callback for when the tooltip changes (usually result of a mouse hover)
///
ULExport void ulViewSetChangeTooltipCallback(ULView view,
ULChangeTooltipCallback callback,
void* user_data);
typedef void
(*ULChangeCursorCallback) (void* user_data, ULView caller, ULCursor cursor);
///
/// Set callback for when the mouse cursor changes
///
ULExport void ulViewSetChangeCursorCallback(ULView view,
ULChangeCursorCallback callback,
void* user_data);
typedef void
(*ULAddConsoleMessageCallback) (void* user_data, ULView caller,
ULMessageSource source, ULMessageLevel level,
ULString message, unsigned int line_number,
unsigned int column_number,
ULString source_id);
///
/// Set callback for when a message is added to the console (useful for
/// JavaScript / network errors and debugging)
///
ULExport void ulViewSetAddConsoleMessageCallback(ULView view,
ULAddConsoleMessageCallback callback,
void* user_data);
typedef void
(*ULBeginLoadingCallback) (void* user_data, ULView caller);
///
/// Set callback for when the page begins loading new URL into main frame
///
ULExport void ulViewSetBeginLoadingCallback(ULView view,
ULBeginLoadingCallback callback,
void* user_data);
typedef void
(*ULFinishLoadingCallback) (void* user_data, ULView caller);
///
/// Set callback for when the page finishes loading URL into main frame
///
ULExport void ulViewSetFinishLoadingCallback(ULView view,
ULFinishLoadingCallback callback,
void* user_data);
typedef void
(*ULUpdateHistoryCallback) (void* user_data, ULView caller);
///
/// Set callback for when the history (back/forward state) is modified
///
ULExport void ulViewSetUpdateHistoryCallback(ULView view,
ULUpdateHistoryCallback callback,
void* user_data);
typedef void
(*ULDOMReadyCallback) (void* user_data, ULView caller);
///
/// Set callback for when all JavaScript has been parsed and the document is
/// ready. This is the best time to make initial JavaScript calls to your page.
///
ULExport void ulViewSetDOMReadyCallback(ULView view,
ULDOMReadyCallback callback,
void* user_data);
///
/// Set whether or not a view should be repainted during the next call to
/// ulRender.
///
/// @note This flag is automatically set whenever the page content changes
/// but you can set it directly in case you need to force a repaint.
///
ULExport void ulViewSetNeedsPaint(ULView view, bool needs_paint);
///
/// Whether or not a view should be painted during the next call to ulRender.
///
ULExport bool ulViewGetNeedsPaint(ULView view);
/******************************************************************************
* String
*****************************************************************************/
///
/// Create string from null-terminated ASCII C-string
///
ULExport ULString ulCreateString(const char* str);
///
/// Create string from UTF-8 buffer
///
ULExport ULString ulCreateStringUTF8(const char* str, size_t len);
///
/// Create string from UTF-16 buffer
///
ULExport ULString ulCreateStringUTF16(ULChar16* str, size_t len);
///
/// Destroy string (you should destroy any strings you explicitly Create).
///
ULExport void ulDestroyString(ULString str);
///
/// Get internal UTF-16 buffer data.
///
ULExport ULChar16* ulStringGetData(ULString str);
///
/// Get length in UTF-16 characters
///
ULExport size_t ulStringGetLength(ULString str);
///
/// Whether this string is empty or not.
///
ULExport bool ulStringIsEmpty(ULString str);
/******************************************************************************
* Bitmap
*****************************************************************************/
///
/// Create empty bitmap.
///
ULExport ULBitmap ulCreateEmptyBitmap();
///
/// Create bitmap with certain dimensions and pixel format.
///
ULExport ULBitmap ulCreateBitmap(unsigned int width, unsigned int height,
ULBitmapFormat format);
///
/// Create bitmap from existing pixel buffer. @see Bitmap for help using
/// this function.
///
ULExport ULBitmap ulCreateBitmapFromPixels(unsigned int width,
unsigned int height,
ULBitmapFormat format,
unsigned int row_bytes,
const void* pixels, size_t size,
bool should_copy);
///
/// Create bitmap from copy.
///
ULExport ULBitmap ulCreateBitmapFromCopy(ULBitmap existing_bitmap);
///
/// Destroy a bitmap (you should only destroy Bitmaps you have explicitly
/// created via one of the creation functions above.
///
ULExport void ulDestroyBitmap(ULBitmap bitmap);
///
/// Get the width in pixels.
///
ULExport unsigned int ulBitmapGetWidth(ULBitmap bitmap);
///
/// Get the height in pixels.
///
ULExport unsigned int ulBitmapGetHeight(ULBitmap bitmap);
///
/// Get the pixel format.
///
ULExport ULBitmapFormat ulBitmapGetFormat(ULBitmap bitmap);
///
/// Get the bytes per pixel.
///
ULExport unsigned int ulBitmapGetBpp(ULBitmap bitmap);
///
/// Get the number of bytes per row.
///
ULExport unsigned int ulBitmapGetRowBytes(ULBitmap bitmap);
///
/// Get the size in bytes of the underlying pixel buffer.
///
ULExport size_t ulBitmapGetSize(ULBitmap bitmap);
///
/// Whether or not this bitmap owns its own pixel buffer.
///
ULExport bool ulBitmapOwnsPixels(ULBitmap bitmap);
///
/// Lock pixels for reading/writing, returns pointer to pixel buffer.
///
ULExport void* ulBitmapLockPixels(ULBitmap bitmap);
///
/// Unlock pixels after locking.
///
ULExport void ulBitmapUnlockPixels(ULBitmap bitmap);
///
/// Get raw pixel buffer-- you should only call this if Bitmap is already
/// locked.
///
ULExport void* ulBitmapRawPixels(ULBitmap bitmap);
///
/// Whether or not this bitmap is empty.
///
ULExport bool ulBitmapIsEmpty(ULBitmap bitmap);
///
/// Reset bitmap pixels to 0.
///
ULExport void ulBitmapErase(ULBitmap bitmap);
///
/// Write bitmap to a PNG on disk.
///
ULExport bool ulBitmapWritePNG(ULBitmap bitmap, const char* path);
/******************************************************************************
* Key Event
******************************************************************************/
///
/// Create a key event, @see KeyEvent for help with the following parameters.
///
ULExport ULKeyEvent ulCreateKeyEvent(ULKeyEventType type,
unsigned int modifiers,
int virtual_key_code, int native_key_code,
ULString text, ULString unmodified_text,
bool is_keypad, bool is_auto_repeat,
bool is_system_key);
#ifdef _WIN32
///
/// Create a key event from native Windows event.
///
ULExport ULKeyEvent ulCreateKeyEventWindows(ULKeyEventType type,
uintptr_t wparam, intptr_t lparam,
bool is_system_key);
#endif
#ifdef __OBJC__
///
/// Create a key event from native macOS event.
///
ULExport ULKeyEvent ulCreateKeyEventMacOS(NSEvent* evt);
#endif
///
/// Destroy a key event.
///
ULExport void ulDestroyKeyEvent(ULKeyEvent evt);
/******************************************************************************
* Mouse Event
*****************************************************************************/
///
/// Create a mouse event, @see MouseEvent for help using this function.
///
ULExport ULMouseEvent ulCreateMouseEvent(ULMouseEventType type, int x, int y,
ULMouseButton button);
///
/// Destroy a mouse event.
///
ULExport void ulDestroyMouseEvent(ULMouseEvent evt);
/******************************************************************************
* Scroll Event
*****************************************************************************/
///
/// Create a scroll event, @see ScrollEvent for help using this function.
///
ULExport ULScrollEvent ulCreateScrollEvent(ULScrollEventType type, int delta_x,
int delta_y);
///
/// Destroy a scroll event.
///
ULExport void ulDestroyScrollEvent(ULScrollEvent evt);
#ifdef __cplusplus
}
#endif
#endif // ULTRALIGHT_CAPI_H

View File

@ -0,0 +1,79 @@
///
/// @file Defines.h
///
/// @brief Common platform definitions
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
// Needed for limit defines, like INTMAX_MAX, which is used by the std C++ library
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#include <cstdint>
#include <cstddef>
#include <limits.h>
#ifdef SWIG
#define UExport
#else
// Require C++11 Support
#if defined(_MSC_VER)
# if _MSC_VER < 1800
# error This project needs at least Visual Studio 2013 to build
# endif
#elif __cplusplus <= 199711L
# error This project can only be compiled with a compiler that supports C++11
#endif
#if defined(__WIN32__) || defined(_WIN32)
# if defined(ULTRALIGHT_IMPLEMENTATION)
# define UExport __declspec(dllexport)
# else
# define UExport __declspec(dllimport)
# endif
#define _thread_local __declspec(thread)
#ifndef _NATIVE_WCHAR_T_DEFINED
#define DISABLE_NATIVE_WCHAR_T
#endif
#else
# define UExport __attribute__((visibility("default")))
#define _thread_local __thread
#endif
#endif
#define ULTRALIGHT_VERSION "1.0.0"
///
/// @mainpage Ultralight C++ API Reference
///
/// @section intro_sec Introduction
///
/// Hi there, welcome to the C++ API Reference for Ultralight!
///
/// Ultralight is a fast, lightweight HTML UI engine for desktop apps.
///
/// If this is your first time exploring the API, we recommend
/// starting with ultralight::Renderer and ultralight::View.
///
///
/// @section usefullinks_sec Useful Links
/// - Home: <https://ultralig.ht> -- Get the latest binaries
/// - Docs: <https://docs.ultralig.ht> -- API overview, code snippets, tutorials and more!
/// - Slack: <http://chat.ultralig.ht/> -- Stuck? Have questions? Come chat with us!
/// - GitHub: <https://github.com/ultralight-ux/ultralight> -- Report issues and browse code
///
/// @section copyright_sec Copyright
/// Documentation is copyright (C) 2019 Ultralight, Inc. All rights reserved.
///

View File

@ -0,0 +1,676 @@
///
/// @file Geometry.h
///
/// @brief The header for various geometry definitions and helpers
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <memory.h>
#include <cmath>
#include <algorithm>
namespace ultralight {
///
/// 2D Vector Helper
///
struct UExport vec2 {
union {
float value[2];
struct { float x, y; };
};
inline vec2() {}
inline vec2(float x, float y) : x(x), y(y) {}
inline vec2(float x) : x(x), y(x) {}
inline vec2 yx() const { return { y, x }; }
inline vec2 xx() const { return { x, x }; }
inline vec2 yy() const { return { y, y }; }
inline friend vec2 operator+(vec2 lhs, const vec2& rhs) { lhs += rhs; return lhs; }
inline friend vec2 operator-(vec2 lhs, const vec2& rhs) { lhs -= rhs; return lhs; }
inline friend vec2 operator*(vec2 lhs, const vec2& rhs) { lhs *= rhs; return lhs; }
inline friend vec2 operator/(vec2 lhs, const vec2& rhs) { lhs /= rhs; return lhs; }
inline friend vec2 operator+(vec2 lhs, float rhs) { lhs += rhs; return lhs; }
inline friend vec2 operator-(vec2 lhs, float rhs) { lhs -= rhs; return lhs; }
inline friend vec2 operator*(vec2 lhs, float rhs) { lhs *= rhs; return lhs; }
inline friend vec2 operator/(vec2 lhs, float rhs) { lhs /= rhs; return lhs; }
inline vec2& operator+=(const vec2& rhs) {
value[0] += rhs.value[0];
value[1] += rhs.value[1];
return *this;
}
inline vec2& operator-=(const vec2& rhs) {
value[0] -= rhs.value[0];
value[1] -= rhs.value[1];
return *this;
}
inline vec2& operator*=(const vec2& rhs) {
value[0] *= rhs.value[0];
value[1] *= rhs.value[1];
return *this;
}
inline vec2& operator/=(const vec2& rhs) {
value[0] /= rhs.value[0];
value[1] /= rhs.value[1];
return *this;
}
inline vec2& operator+=(float rhs) {
value[0] += rhs;
value[1] += rhs;
return *this;
}
inline vec2& operator-=(float rhs) {
value[0] -= rhs;
value[1] -= rhs;
return *this;
}
inline vec2& operator*=(float rhs) {
value[0] *= rhs;
value[1] *= rhs;
return *this;
}
inline vec2& operator/=(float rhs) {
value[0] /= rhs;
value[1] /= rhs;
return *this;
}
inline friend bool operator==(const vec2& a, const vec2& b) {
return !memcmp(&a, &b, sizeof(a));
}
inline friend bool operator!=(const vec2& a, const vec2& b) {
return !(a == b);
}
inline friend vec2 min_(const vec2& a, const vec2& b) {
return{ (b.x < a.x) ? b.x : a.x,
(b.y < a.y) ? b.y : a.y };
}
inline friend vec2 max_(const vec2& a, const vec2& b) {
return{ (a.x < b.x) ? b.x : a.x,
(a.y < b.y) ? b.y : a.y };
}
inline friend vec2 clamp(const vec2& x, const vec2& minVal, const vec2& maxVal) {
return min_(max_(x, minVal), maxVal);
}
inline friend vec2 mix(const vec2& a, const vec2& b, float t) {
return a * (1.0f - t) + b * t;
}
inline friend float length(const vec2& a) {
return sqrtf(a.x * a.x + a.y * a.y);
}
// squared length
inline friend float length2(const vec2& a) {
return dot(a, a);
}
inline friend float distance(const vec2& a, const vec2& b) {
return length(a - b);
}
// squared distance
inline friend float distance2(const vec2& a, const vec2& b) {
return length2(a - b);
}
inline friend vec2 normalize(const vec2& a) {
return a / length(a);
}
inline friend float dot(const vec2& a, const vec2& b) {
return a.x * b.x + a.y * b.y;
}
};
///
/// 3D Vector Helper
///
struct UExport vec3 {
union {
float value[3];
struct { float x, y, z; };
};
inline vec3() {}
inline vec3(float x, float y, float z) : x(x), y(y), z(z) {}
inline vec3(float x) : x(x), y(x), z(x) {}
inline friend vec3 operator+(vec3 lhs, const vec3& rhs) { lhs += rhs; return lhs; }
inline friend vec3 operator-(vec3 lhs, const vec3& rhs) { lhs -= rhs; return lhs; }
inline friend vec3 operator*(vec3 lhs, const vec3& rhs) { lhs *= rhs; return lhs; }
inline friend vec3 operator/(vec3 lhs, const vec3& rhs) { lhs /= rhs; return lhs; }
inline friend vec3 operator+(vec3 lhs, float rhs) { lhs += rhs; return lhs; }
inline friend vec3 operator-(vec3 lhs, float rhs) { lhs -= rhs; return lhs; }
inline friend vec3 operator*(vec3 lhs, float rhs) { lhs *= rhs; return lhs; }
inline friend vec3 operator/(vec3 lhs, float rhs) { lhs /= rhs; return lhs; }
inline vec3& operator+=(const vec3& rhs) {
value[0] += rhs.value[0];
value[1] += rhs.value[1];
value[2] += rhs.value[2];
return *this;
}
inline vec3& operator-=(const vec3& rhs) {
value[0] -= rhs.value[0];
value[1] -= rhs.value[1];
value[2] -= rhs.value[2];
return *this;
}
inline vec3& operator*=(const vec3& rhs) {
value[0] *= rhs.value[0];
value[1] *= rhs.value[1];
value[2] *= rhs.value[2];
return *this;
}
inline vec3& operator/=(const vec3& rhs) {
value[0] /= rhs.value[0];
value[1] /= rhs.value[1];
value[2] /= rhs.value[2];
return *this;
}
inline vec3& operator+=(float rhs) {
value[0] += rhs;
value[1] += rhs;
value[2] += rhs;
return *this;
}
inline vec3& operator-=(float rhs) {
value[0] -= rhs;
value[1] -= rhs;
value[2] -= rhs;
return *this;
}
inline vec3& operator*=(float rhs) {
value[0] *= rhs;
value[1] *= rhs;
value[2] *= rhs;
return *this;
}
inline vec3& operator/=(float rhs) {
value[0] /= rhs;
value[1] /= rhs;
value[2] /= rhs;
return *this;
}
inline friend bool operator==(const vec3& a, const vec3& b) {
return !memcmp(&a, &b, sizeof(a));
}
inline friend bool operator!=(const vec3& a, const vec3& b) {
return !(a == b);
}
inline friend vec3 min_(const vec3& a, const vec3& b) {
return{ (b.x < a.x) ? b.x : a.x,
(b.y < a.y) ? b.y : a.y,
(b.z < a.z) ? b.z : a.z };
}
inline friend vec3 max_(const vec3& a, const vec3& b) {
return{ (a.x < b.x) ? b.x : a.x,
(a.y < b.y) ? b.y : a.y,
(a.z < b.z) ? b.z : a.z };
}
inline friend vec3 clamp(const vec3& x, const vec3& minVal, const vec3& maxVal) {
return min_(max_(x, minVal), maxVal);
}
inline friend vec3 mix(const vec3& a, const vec3& b, float t) {
return a * (1.0f - t) + b * t;
}
inline friend float length(const vec3& a) {
return sqrtf(a.x * a.x + a.y * a.y + a.z * a.z);
}
inline friend float distance(const vec3& a, const vec3& b) {
return length(a - b);
}
inline friend vec3 normalize(const vec3& a) {
return a / length(a);
}
inline friend float dot(const vec3& a, const vec3& b) {
return a.x * b.x + a.y * b.y + a.z * b.z;
}
};
///
/// 4D Vector Helper
///
struct UExport vec4 {
union {
float value[4];
struct { float x, y, z, w; };
};
inline vec4() {}
inline vec4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) {}
inline vec4(float x) : x(x), y(x), z(x), w(x) {}
inline vec4(const float x[4]) { memcpy(value, x, sizeof(value)); }
inline friend bool operator==(const vec4& a, const vec4& b) {
return !memcmp(&a, &b, sizeof(a));
}
inline friend bool operator!=(const vec4& a, const vec4& b) {
return !(a == b);
}
inline friend vec4 operator+(vec4 lhs, const vec4& rhs) { lhs += rhs; return lhs; }
inline friend vec4 operator-(vec4 lhs, const vec4& rhs) { lhs -= rhs; return lhs; }
inline friend vec4 operator*(vec4 lhs, const vec4& rhs) { lhs *= rhs; return lhs; }
inline friend vec4 operator/(vec4 lhs, const vec4& rhs) { lhs /= rhs; return lhs; }
inline friend vec4 operator+(vec4 lhs, float rhs) { lhs += rhs; return lhs; }
inline friend vec4 operator-(vec4 lhs, float rhs) { lhs -= rhs; return lhs; }
inline friend vec4 operator*(vec4 lhs, float rhs) { lhs *= rhs; return lhs; }
inline friend vec4 operator/(vec4 lhs, float rhs) { lhs /= rhs; return lhs; }
inline vec4& operator+=(const vec4& rhs) {
value[0] += rhs.value[0];
value[1] += rhs.value[1];
value[2] += rhs.value[2];
value[3] += rhs.value[3];
return *this;
}
inline vec4& operator-=(const vec4& rhs) {
value[0] -= rhs.value[0];
value[1] -= rhs.value[1];
value[2] -= rhs.value[2];
value[3] -= rhs.value[3];
return *this;
}
inline vec4& operator*=(const vec4& rhs) {
value[0] *= rhs.value[0];
value[1] *= rhs.value[1];
value[2] *= rhs.value[2];
value[3] *= rhs.value[3];
return *this;
}
inline vec4& operator/=(const vec4& rhs) {
value[0] /= rhs.value[0];
value[1] /= rhs.value[1];
value[2] /= rhs.value[2];
value[3] /= rhs.value[3];
return *this;
}
inline vec4& operator+=(float rhs) {
value[0] += rhs;
value[1] += rhs;
value[2] += rhs;
value[3] += rhs;
return *this;
}
inline vec4& operator-=(float rhs) {
value[0] -= rhs;
value[1] -= rhs;
value[2] -= rhs;
value[3] -= rhs;
return *this;
}
inline vec4& operator*=(float rhs) {
value[0] *= rhs;
value[1] *= rhs;
value[2] *= rhs;
value[3] *= rhs;
return *this;
}
inline vec4& operator/=(float rhs) {
value[0] /= rhs;
value[1] /= rhs;
value[2] /= rhs;
value[3] /= rhs;
return *this;
}
inline friend vec4 min_(const vec4& a, const vec4& b) {
return{ (b.x < a.x) ? b.x : a.x,
(b.y < a.y) ? b.y : a.y,
(b.z < a.z) ? b.z : a.z,
(b.w < a.w) ? b.w : a.w };
}
inline friend vec4 max_(const vec4& a, const vec4& b) {
return{ (a.x < b.x) ? b.x : a.x,
(a.y < b.y) ? b.y : a.y,
(a.z < b.z) ? b.z : a.z,
(a.w < b.w) ? b.w : a.w };
}
};
///
/// Point is typedef'd to a 2D vector
///
typedef vec2 Point;
///
/// Float Rectangle Helper
///
struct UExport Rect {
union {
float value[4];
struct { float left, top, right, bottom; };
};
static inline Rect MakeEmpty() {
Rect result;
result.SetEmpty();
return result;
}
inline float width() const { return right - left; }
inline float height() const { return bottom - top; }
inline float x() const { return left; }
inline float y() const { return top; }
inline float center_x() const { return (left + right) * 0.5f; }
inline float center_y() const { return (top + bottom) * 0.5f; }
inline Point origin() const { return { left, top }; }
inline void SetEmpty() {
memset(this, 0, sizeof(*this));
}
inline bool IsEmpty() const {
return *this == MakeEmpty();
}
inline bool IsValid() const {
return width() > 0 && height() > 0;
}
inline void Inset(float dx, float dy) {
value[0] += dx;
value[1] += dy;
value[2] -= dx;
value[3] -= dy;
}
inline void Outset(float dx, float dy) {
Inset(-dx, -dy);
}
inline void Move(float dx, float dy) {
value[0] += dx;
value[1] += dy;
value[2] += dx;
value[3] += dy;
}
inline float area() const {
return width() * height();
}
inline void Join(const Rect& rhs) {
// if we are empty, just assign
if (IsEmpty()) {
*this = rhs;
}
else {
if (rhs.value[0] < value[0]) value[0] = rhs.value[0];
if (rhs.value[1] < value[1]) value[1] = rhs.value[1];
if (rhs.value[2] > value[2]) value[2] = rhs.value[2];
if (rhs.value[3] > value[3]) value[3] = rhs.value[3];
}
}
inline void Join(const Point& p) {
// if we are empty, just assign
if (IsEmpty()) {
*this = { p.x, p.y, p.x, p.y };
}
else {
if (p.x < value[0]) value[0] = p.x;
if (p.y < value[1]) value[1] = p.y;
if (p.x > value[2]) value[2] = p.x;
if (p.y > value[3]) value[3] = p.y;
}
}
inline bool Contains(const Point& p) const {
return p.x >= left && p.x <= right &&
p.y >= top && p.y <= bottom;
}
inline bool Contains(const Rect& r) const {
return left <= r.left && top <= r.top &&
right >= r.right && bottom >= r.bottom;
}
inline bool Intersects(const Rect& rhs) const {
return !(rhs.left > right ||
rhs.right < left ||
rhs.top > bottom ||
rhs.bottom < top);
}
inline Rect Intersect(const Rect& other) const {
return{ (left < other.left) ? other.left : left,
(top < other.top) ? other.top : top,
(other.right < right) ? other.right : right,
(other.bottom < bottom) ? other.bottom : bottom };
}
friend inline bool operator==(const Rect& a, const Rect& b) {
return !memcmp(&a, &b, sizeof(a));
}
friend inline bool operator!=(const Rect& a, const Rect& b) {
return !(a == b);
}
};
///
/// Integer Rectangle Helper
///
struct UExport IntRect {
union {
int value[4];
struct { int left, top, right, bottom; };
};
static inline IntRect MakeEmpty() {
IntRect result;
result.SetEmpty();
return result;
}
inline int width() const { return right - left; }
inline int height() const { return bottom - top; }
inline int x() const { return left; }
inline int y() const { return top; }
inline int center_x() const { return (int)std::round((left + right) * 0.5f); }
inline int center_y() const { return (int)std::round((top + bottom) * 0.5f); }
inline Point origin() const { return{ (float)left, (float)top }; }
inline void SetEmpty() {
memset(this, 0, sizeof(*this));
}
inline bool IsEmpty() const {
return *this == MakeEmpty();
}
inline bool IsValid() const {
return width() > 0 && height() > 0;
}
inline void Inset(int dx, int dy) {
value[0] += dx;
value[1] += dy;
value[2] -= dx;
value[3] -= dy;
}
inline void Outset(int dx, int dy) {
Inset(-dx, -dy);
}
inline void Move(int dx, int dy) {
value[0] += dx;
value[1] += dy;
value[2] += dx;
value[3] += dy;
}
inline int area() const {
return width() * height();
}
inline void Join(const IntRect& rhs) {
// if we are empty, just assign
if (IsEmpty()) {
*this = rhs;
}
else {
if (rhs.value[0] < value[0]) value[0] = rhs.value[0];
if (rhs.value[1] < value[1]) value[1] = rhs.value[1];
if (rhs.value[2] > value[2]) value[2] = rhs.value[2];
if (rhs.value[3] > value[3]) value[3] = rhs.value[3];
}
}
inline void Join(const Point& p) {
// if we are empty, just assign
if (IsEmpty()) {
*this = { (int)std::floor(p.x), (int)std::floor(p.y), (int)std::ceil(p.x), (int)std::ceil(p.y) };
}
else {
if ((int)std::floor(p.x) < value[0]) value[0] = (int)std::floor(p.x);
if ((int)std::floor(p.y) < value[1]) value[1] = (int)std::floor(p.y);
if ((int)std::ceil(p.x) > value[2]) value[2] = (int)std::ceil(p.x);
if ((int)std::ceil(p.y) > value[3]) value[3] = (int)std::ceil(p.y);
}
}
inline bool Contains(const Point& p) const {
return p.x >= left && p.x <= right &&
p.y >= top && p.y <= bottom;
}
inline bool Contains(const IntRect& r) const {
return left <= r.left && top <= r.top &&
right >= r.right && bottom >= r.bottom;
}
inline bool Intersects(const IntRect& rhs) const {
// Since this is mostly used for pixel operations, we only count
// intersections that have width and height >= 1.
return !(rhs.left > right - 1 ||
rhs.right < left ||
rhs.top > bottom - 1 ||
rhs.bottom < top);
}
inline IntRect Intersect(const IntRect& other) const {
return{ (left < other.left) ? other.left : left,
(top < other.top) ? other.top : top,
(other.right < right) ? other.right : right,
(other.bottom < bottom) ? other.bottom : bottom };
}
friend inline bool operator==(const IntRect& a, const IntRect& b) {
return !memcmp(&a, &b, sizeof(a));
}
friend inline bool operator!=(const IntRect& a, const IntRect& b) {
return !(a == b);
}
};
///
/// Rounded Rectangle Helper
///
struct UExport RoundedRect {
Rect rect;
float radii_x[4];
float radii_y[4];
void SetEmpty();
bool IsRounded() const;
// Negative is inside, positive is outside.
float GetSignedDistance(const Point& p) const;
// Returns whether or not intersection is found. Can fail if the resulting
// geometry is not a rounded rectangle.
bool Intersect(const RoundedRect& other, RoundedRect& result) const;
void SnapToPixels();
Rect CalculateInterior() const;
};
} // namespace ultralight

View File

@ -0,0 +1,527 @@
///
/// @file KeyCodes.h
///
/// @brief The header for the KeyCodes definitions.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
namespace ultralight {
///
/// Namespace containing all the key-code definitions for KeyboardEvent.
/// Most of these correspond directly to the key-code values on Windows.
///
namespace KeyCodes {
// GK_BACK (08) BACKSPACE key
const int GK_BACK = 0x08;
// GK_TAB (09) TAB key
const int GK_TAB = 0x09;
// GK_CLEAR (0C) CLEAR key
const int GK_CLEAR = 0x0C;
// GK_RETURN (0D)
const int GK_RETURN = 0x0D;
// GK_SHIFT (10) SHIFT key
const int GK_SHIFT = 0x10;
// GK_CONTROL (11) CTRL key
const int GK_CONTROL = 0x11;
// GK_MENU (12) ALT key
const int GK_MENU = 0x12;
// GK_PAUSE (13) PAUSE key
const int GK_PAUSE = 0x13;
// GK_CAPITAL (14) CAPS LOCK key
const int GK_CAPITAL = 0x14;
// GK_KANA (15) Input Method Editor (IME) Kana mode
const int GK_KANA = 0x15;
// GK_HANGUEL (15) IME Hanguel mode (maintained for compatibility; use GK_HANGUL)
// GK_HANGUL (15) IME Hangul mode
const int GK_HANGUL = 0x15;
// GK_JUNJA (17) IME Junja mode
const int GK_JUNJA = 0x17;
// GK_FINAL (18) IME final mode
const int GK_FINAL = 0x18;
// GK_HANJA (19) IME Hanja mode
const int GK_HANJA = 0x19;
// GK_KANJI (19) IME Kanji mode
const int GK_KANJI = 0x19;
// GK_ESCAPE (1B) ESC key
const int GK_ESCAPE = 0x1B;
// GK_CONVERT (1C) IME convert
const int GK_CONVERT = 0x1C;
// GK_NONCONVERT (1D) IME nonconvert
const int GK_NONCONVERT = 0x1D;
// GK_ACCEPT (1E) IME accept
const int GK_ACCEPT = 0x1E;
// GK_MODECHANGE (1F) IME mode change request
const int GK_MODECHANGE = 0x1F;
// GK_SPACE (20) SPACEBAR
const int GK_SPACE = 0x20;
// GK_PRIOR (21) PAGE UP key
const int GK_PRIOR = 0x21;
// GK_NEXT (22) PAGE DOWN key
const int GK_NEXT = 0x22;
// GK_END (23) END key
const int GK_END = 0x23;
// GK_HOME (24) HOME key
const int GK_HOME = 0x24;
// GK_LEFT (25) LEFT ARROW key
const int GK_LEFT = 0x25;
// GK_UP (26) UP ARROW key
const int GK_UP = 0x26;
// GK_RIGHT (27) RIGHT ARROW key
const int GK_RIGHT = 0x27;
// GK_DOWN (28) DOWN ARROW key
const int GK_DOWN = 0x28;
// GK_SELECT (29) SELECT key
const int GK_SELECT = 0x29;
// GK_PRINT (2A) PRINT key
const int GK_PRINT = 0x2A;
// GK_EXECUTE (2B) EXECUTE key
const int GK_EXECUTE = 0x2B;
// GK_SNAPSHOT (2C) PRINT SCREEN key
const int GK_SNAPSHOT = 0x2C;
// GK_INSERT (2D) INS key
const int GK_INSERT = 0x2D;
// GK_DELETE (2E) DEL key
const int GK_DELETE = 0x2E;
// GK_HELP (2F) HELP key
const int GK_HELP = 0x2F;
// (30) 0 key
const int GK_0 = 0x30;
// (31) 1 key
const int GK_1 = 0x31;
// (32) 2 key
const int GK_2 = 0x32;
// (33) 3 key
const int GK_3 = 0x33;
// (34) 4 key
const int GK_4 = 0x34;
// (35) 5 key;
const int GK_5 = 0x35;
// (36) 6 key
const int GK_6 = 0x36;
// (37) 7 key
const int GK_7 = 0x37;
// (38) 8 key
const int GK_8 = 0x38;
// (39) 9 key
const int GK_9 = 0x39;
// (41) A key
const int GK_A = 0x41;
// (42) B key
const int GK_B = 0x42;
// (43) C key
const int GK_C = 0x43;
// (44) D key
const int GK_D = 0x44;
// (45) E key
const int GK_E = 0x45;
// (46) F key
const int GK_F = 0x46;
// (47) G key
const int GK_G = 0x47;
// (48) H key
const int GK_H = 0x48;
// (49) I key
const int GK_I = 0x49;
// (4A) J key
const int GK_J = 0x4A;
// (4B) K key
const int GK_K = 0x4B;
// (4C) L key
const int GK_L = 0x4C;
// (4D) M key
const int GK_M = 0x4D;
// (4E) N key
const int GK_N = 0x4E;
// (4F) O key
const int GK_O = 0x4F;
// (50) P key
const int GK_P = 0x50;
// (51) Q key
const int GK_Q = 0x51;
// (52) R key
const int GK_R = 0x52;
// (53) S key
const int GK_S = 0x53;
// (54) T key
const int GK_T = 0x54;
// (55) U key
const int GK_U = 0x55;
// (56) V key
const int GK_V = 0x56;
// (57) W key
const int GK_W = 0x57;
// (58) X key
const int GK_X = 0x58;
// (59) Y key
const int GK_Y = 0x59;
// (5A) Z key
const int GK_Z = 0x5A;
// GK_LWIN (5B) Left Windows key (Microsoft Natural keyboard)
const int GK_LWIN = 0x5B;
// GK_RWIN (5C) Right Windows key (Natural keyboard)
const int GK_RWIN = 0x5C;
// GK_APPS (5D) Applications key (Natural keyboard)
const int GK_APPS = 0x5D;
// GK_SLEEP (5F) Computer Sleep key
const int GK_SLEEP = 0x5F;
// GK_NUMPAD0 (60) Numeric keypad 0 key
const int GK_NUMPAD0 = 0x60;
// GK_NUMPAD1 (61) Numeric keypad 1 key
const int GK_NUMPAD1 = 0x61;
// GK_NUMPAD2 (62) Numeric keypad 2 key
const int GK_NUMPAD2 = 0x62;
// GK_NUMPAD3 (63) Numeric keypad 3 key
const int GK_NUMPAD3 = 0x63;
// GK_NUMPAD4 (64) Numeric keypad 4 key
const int GK_NUMPAD4 = 0x64;
// GK_NUMPAD5 (65) Numeric keypad 5 key
const int GK_NUMPAD5 = 0x65;
// GK_NUMPAD6 (66) Numeric keypad 6 key
const int GK_NUMPAD6 = 0x66;
// GK_NUMPAD7 (67) Numeric keypad 7 key
const int GK_NUMPAD7 = 0x67;
// GK_NUMPAD8 (68) Numeric keypad 8 key
const int GK_NUMPAD8 = 0x68;
// GK_NUMPAD9 (69) Numeric keypad 9 key
const int GK_NUMPAD9 = 0x69;
// GK_MULTIPLY (6A) Multiply key
const int GK_MULTIPLY = 0x6A;
// GK_ADD (6B) Add key
const int GK_ADD = 0x6B;
// GK_SEPARATOR (6C) Separator key
const int GK_SEPARATOR = 0x6C;
// GK_SUBTRACT (6D) Subtract key
const int GK_SUBTRACT = 0x6D;
// GK_DECIMAL (6E) Decimal key
const int GK_DECIMAL = 0x6E;
// GK_DIVIDE (6F) Divide key
const int GK_DIVIDE = 0x6F;
// GK_F1 (70) F1 key
const int GK_F1 = 0x70;
// GK_F2 (71) F2 key
const int GK_F2 = 0x71;
// GK_F3 (72) F3 key
const int GK_F3 = 0x72;
// GK_F4 (73) F4 key
const int GK_F4 = 0x73;
// GK_F5 (74) F5 key
const int GK_F5 = 0x74;
// GK_F6 (75) F6 key
const int GK_F6 = 0x75;
// GK_F7 (76) F7 key
const int GK_F7 = 0x76;
// GK_F8 (77) F8 key
const int GK_F8 = 0x77;
// GK_F9 (78) F9 key
const int GK_F9 = 0x78;
// GK_F10 (79) F10 key
const int GK_F10 = 0x79;
// GK_F11 (7A) F11 key
const int GK_F11 = 0x7A;
// GK_F12 (7B) F12 key
const int GK_F12 = 0x7B;
// GK_F13 (7C) F13 key
const int GK_F13 = 0x7C;
// GK_F14 (7D) F14 key
const int GK_F14 = 0x7D;
// GK_F15 (7E) F15 key
const int GK_F15 = 0x7E;
// GK_F16 (7F) F16 key
const int GK_F16 = 0x7F;
// GK_F17 (80H) F17 key
const int GK_F17 = 0x80;
// GK_F18 (81H) F18 key
const int GK_F18 = 0x81;
// GK_F19 (82H) F19 key
const int GK_F19 = 0x82;
// GK_F20 (83H) F20 key
const int GK_F20 = 0x83;
// GK_F21 (84H) F21 key
const int GK_F21 = 0x84;
// GK_F22 (85H) F22 key
const int GK_F22 = 0x85;
// GK_F23 (86H) F23 key
const int GK_F23 = 0x86;
// GK_F24 (87H) F24 key
const int GK_F24 = 0x87;
// GK_NUMLOCK (90) NUM LOCK key
const int GK_NUMLOCK = 0x90;
// GK_SCROLL (91) SCROLL LOCK key
const int GK_SCROLL = 0x91;
// GK_LSHIFT (A0) Left SHIFT key
const int GK_LSHIFT = 0xA0;
// GK_RSHIFT (A1) Right SHIFT key
const int GK_RSHIFT = 0xA1;
// GK_LCONTROL (A2) Left CONTROL key
const int GK_LCONTROL = 0xA2;
// GK_RCONTROL (A3) Right CONTROL key
const int GK_RCONTROL = 0xA3;
// GK_LMENU (A4) Left MENU key
const int GK_LMENU = 0xA4;
// GK_RMENU (A5) Right MENU key
const int GK_RMENU = 0xA5;
// GK_BROWSER_BACK (A6) Windows 2000/XP: Browser Back key
const int GK_BROWSER_BACK = 0xA6;
// GK_BROWSER_FORWARD (A7) Windows 2000/XP: Browser Forward key
const int GK_BROWSER_FORWARD = 0xA7;
// GK_BROWSER_REFRESH (A8) Windows 2000/XP: Browser Refresh key
const int GK_BROWSER_REFRESH = 0xA8;
// GK_BROWSER_STOP (A9) Windows 2000/XP: Browser Stop key
const int GK_BROWSER_STOP = 0xA9;
// GK_BROWSER_SEARCH (AA) Windows 2000/XP: Browser Search key
const int GK_BROWSER_SEARCH = 0xAA;
// GK_BROWSER_FAVORITES (AB) Windows 2000/XP: Browser Favorites key
const int GK_BROWSER_FAVORITES = 0xAB;
// GK_BROWSER_HOME (AC) Windows 2000/XP: Browser Start and Home key
const int GK_BROWSER_HOME = 0xAC;
// GK_VOLUME_MUTE (AD) Windows 2000/XP: Volume Mute key
const int GK_VOLUME_MUTE = 0xAD;
// GK_VOLUME_DOWN (AE) Windows 2000/XP: Volume Down key
const int GK_VOLUME_DOWN = 0xAE;
// GK_VOLUME_UP (AF) Windows 2000/XP: Volume Up key
const int GK_VOLUME_UP = 0xAF;
// GK_MEDIA_NEXT_TRACK (B0) Windows 2000/XP: Next Track key
const int GK_MEDIA_NEXT_TRACK = 0xB0;
// GK_MEDIA_PREV_TRACK (B1) Windows 2000/XP: Previous Track key
const int GK_MEDIA_PREV_TRACK = 0xB1;
// GK_MEDIA_STOP (B2) Windows 2000/XP: Stop Media key
const int GK_MEDIA_STOP = 0xB2;
// GK_MEDIA_PLAY_PAUSE (B3) Windows 2000/XP: Play/Pause Media key
const int GK_MEDIA_PLAY_PAUSE = 0xB3;
// GK_LAUNCH_MAIL (B4) Windows 2000/XP: Start Mail key
const int GK_MEDIA_LAUNCH_MAIL = 0xB4;
// GK_LAUNCH_MEDIA_SELECT (B5) Windows 2000/XP: Select Media key
const int GK_MEDIA_LAUNCH_MEDIA_SELECT = 0xB5;
// GK_LAUNCH_APP1 (B6) Windows 2000/XP: Start Application 1 key
const int GK_MEDIA_LAUNCH_APP1 = 0xB6;
// GK_LAUNCH_APP2 (B7) Windows 2000/XP: Start Application 2 key
const int GK_MEDIA_LAUNCH_APP2 = 0xB7;
// GK_OEM_1 (BA) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ';:' key
const int GK_OEM_1 = 0xBA;
// GK_OEM_PLUS (BB) Windows 2000/XP: For any country/region, the '+' key
const int GK_OEM_PLUS = 0xBB;
// GK_OEM_COMMA (BC) Windows 2000/XP: For any country/region, the ',' key
const int GK_OEM_COMMA = 0xBC;
// GK_OEM_MINUS (BD) Windows 2000/XP: For any country/region, the '-' key
const int GK_OEM_MINUS = 0xBD;
// GK_OEM_PERIOD (BE) Windows 2000/XP: For any country/region, the '.' key
const int GK_OEM_PERIOD = 0xBE;
// GK_OEM_2 (BF) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '/?' key
const int GK_OEM_2 = 0xBF;
// GK_OEM_3 (C0) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '`~' key
const int GK_OEM_3 = 0xC0;
// GK_OEM_4 (DB) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '[{' key
const int GK_OEM_4 = 0xDB;
// GK_OEM_5 (DC) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '\|' key
const int GK_OEM_5 = 0xDC;
// GK_OEM_6 (DD) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ']}' key
const int GK_OEM_6 = 0xDD;
// GK_OEM_7 (DE) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the 'single-quote/double-quote' key
const int GK_OEM_7 = 0xDE;
// GK_OEM_8 (DF) Used for miscellaneous characters; it can vary by keyboard.
const int GK_OEM_8 = 0xDF;
// GK_OEM_102 (E2) Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard
const int GK_OEM_102 = 0xE2;
// GK_PROCESSKEY (E5) Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key
const int GK_PROCESSKEY = 0xE5;
// GK_PACKET (E7) Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes. The GK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT,SendInput, WM_KEYDOWN, and WM_KEYUP
const int GK_PACKET = 0xE7;
// GK_ATTN (F6) Attn key
const int GK_ATTN = 0xF6;
// GK_CRSEL (F7) CrSel key
const int GK_CRSEL = 0xF7;
// GK_EXSEL (F8) ExSel key
const int GK_EXSEL = 0xF8;
// GK_EREOF (F9) Erase EOF key
const int GK_EREOF = 0xF9;
// GK_PLAY (FA) Play key
const int GK_PLAY = 0xFA;
// GK_ZOOM (FB) Zoom key
const int GK_ZOOM = 0xFB;
// GK_NONAME (FC) Reserved for future use
const int GK_NONAME = 0xFC;
// GK_PA1 (FD) PA1 key
const int GK_PA1 = 0xFD;
// GK_OEM_CLEAR (FE) Clear key
const int GK_OEM_CLEAR = 0xFE;
const int GK_UNKNOWN = 0;
} // namespace KeyCodes
} // namespace ultralight

View File

@ -0,0 +1,164 @@
///
/// @file KeyEvent.h
///
/// @brief The header for the KeyEvent class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/KeyCodes.h>
#include <Ultralight/String.h>
#ifdef __OBJC__
#import <AppKit/NSEvent.h>
#endif
namespace ultralight {
///
/// @brief A generic keyboard event that can be created from a platform event
/// or synthesized from scratch.
///
/// @see View::FireKeyEvent
///
class UExport KeyEvent {
public:
///
/// The various KeyEvent types.
///
enum Type {
/// Key-Down type
kType_KeyDown,
/// Key-Up type
kType_KeyUp,
/// Raw Key-Down type
kType_RawKeyDown,
/// Character input type (this event generates text in input fields)
kType_Char,
};
///
/// Creates an empty KeyEvent, you will need to initialize its members
/// yourself. This is useful for synthesizing your own keyboard events.
///
KeyEvent();
#ifdef _WIN32
///
/// Create a KeyEvent directly from a Windows keyboard event.
///
KeyEvent(Type type, uintptr_t wparam, intptr_t lparam, bool is_system_key);
#endif
#ifdef __OBJC__
///
/// Create a KeyEvent directly from a macOS NSEvent.
///
KeyEvent(NSEvent* evt);
#endif
///
/// An enumeration of the different keyboard modifiers.
///
enum Modifiers : uint8_t {
/// Whether or not an ALT key is down
kMod_AltKey = 1 << 0,
/// Whether or not a Control key is down
kMod_CtrlKey = 1 << 1,
/// Whether or not a meta key (Command-key on Mac, Windows-key on Win) is down
kMod_MetaKey = 1 << 2,
/// Whether or not a Shift key is down
kMod_ShiftKey = 1 << 3,
};
///
// The type of this KeyEvent
///
Type type;
///
/// The current state of the keyboard. Modifiers may be OR'd together to
/// represent multiple values.
///
unsigned modifiers;
///
// The virtual key-code associated with this keyboard event. This is either
// directly from the event (ie, WPARAM on Windows) or via a mapping function.
// You can see a full list of the possible virtual key-codes in
// KeyboardCodes.h
///
int virtual_key_code;
///
/// The actual key-code generated by the platform. The DOM spec primarily
/// uses Windows-equivalent codes (hence virtualKeyCode above) but it helps to
/// also specify the platform-specific key-code as well.
///
int native_key_code;
///
/// This is a string identifying the key that was pressed. This can be
/// generated from the virtual_key_code via the GetKeyIdentifierFromVirtualKeyCode()
/// utility function. You can find the full list of key identifiers at:
/// <http://www.w3.org/TR/DOM-Level-3-Events/keyset.html>
///
String key_identifier;
///
/// The actual text generated by this keyboard event. This is usually only a
/// single character.
///
String text;
///
/// The text generated by this keyboard event before all modifiers except
/// shift are applied. This is used internally for working out shortcut keys.
/// This is usually only a single character.
///
String unmodified_text;
///
/// Whether or not this is a keypad event.
///
bool is_keypad;
///
/// Whether or not this was generated as the result of an auto-repeat
/// (eg, holding down a key).
///
bool is_auto_repeat;
///
/// Whether or not the pressed key is a "system key". This is a Windows-only
/// concept and should be "false" for all non-Windows platforms. For more
/// information, see the following link:
/// <http://msdn.microsoft.com/en-us/library/ms646286(VS.85).aspx>
bool is_system_key;
};
///
/// Utility function for generating a key identifier string from a virtual
/// key-code.
///
/// @param virtual_key_code The virtual key-code to generate the key
/// identifier from.
///
/// @param key_identifier_result The string to store the result in.
///
void UExport GetKeyIdentifierFromVirtualKeyCode(int virtual_key_code,
String& key_identifier_result);
} // namespace ultralight

View File

@ -0,0 +1,176 @@
///
/// @file Listener.h
///
/// @brief The header for View listener interfaces.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/String.h>
namespace ultralight {
class View;
///
/// MessageSource types, @see ViewListener::OnAddConsoleMessage
///
enum MessageSource {
kMessageSource_XML = 0,
kMessageSource_JS,
kMessageSource_Network,
kMessageSource_ConsoleAPI,
kMessageSource_Storage,
kMessageSource_AppCache,
kMessageSource_Rendering,
kMessageSource_CSS,
kMessageSource_Security,
kMessageSource_ContentBlocker,
kMessageSource_Other,
};
///
/// MessageLevel types, @see ViewListener::OnAddConsoleMessage
///
enum MessageLevel {
kMessageLevel_Log = 1,
kMessageLevel_Warning = 2,
kMessageLevel_Error = 3,
kMessageLevel_Debug = 4,
kMessageLevel_Info = 5,
};
///
/// Cursor types, @see ViewListener::OnChangeCursor
///
enum Cursor {
kCursor_Pointer = 0,
kCursor_Cross,
kCursor_Hand,
kCursor_IBeam,
kCursor_Wait,
kCursor_Help,
kCursor_EastResize,
kCursor_NorthResize,
kCursor_NorthEastResize,
kCursor_NorthWestResize,
kCursor_SouthResize,
kCursor_SouthEastResize,
kCursor_SouthWestResize,
kCursor_WestResize,
kCursor_NorthSouthResize,
kCursor_EastWestResize,
kCursor_NorthEastSouthWestResize,
kCursor_NorthWestSouthEastResize,
kCursor_ColumnResize,
kCursor_RowResize,
kCursor_MiddlePanning,
kCursor_EastPanning,
kCursor_NorthPanning,
kCursor_NorthEastPanning,
kCursor_NorthWestPanning,
kCursor_SouthPanning,
kCursor_SouthEastPanning,
kCursor_SouthWestPanning,
kCursor_WestPanning,
kCursor_Move,
kCursor_VerticalText,
kCursor_Cell,
kCursor_ContextMenu,
kCursor_Alias,
kCursor_Progress,
kCursor_NoDrop,
kCursor_Copy,
kCursor_None,
kCursor_NotAllowed,
kCursor_ZoomIn,
kCursor_ZoomOut,
kCursor_Grab,
kCursor_Grabbing,
kCursor_Custom
};
///
/// @brief Interface for View-related events
///
/// @note For more info @see View::set_view_listener
///
class UExport ViewListener {
public:
virtual ~ViewListener() {}
///
/// Called when the page title changes
///
virtual void OnChangeTitle(ultralight::View* caller,
const String& title) {}
///
/// Called when the page URL changes
///
virtual void OnChangeURL(ultralight::View* caller,
const String& url) {}
///
/// Called when the tooltip changes (usually as result of a mouse hover)
///
virtual void OnChangeTooltip(ultralight::View* caller,
const String& tooltip) {}
///
/// Called when the mouse cursor changes
///
virtual void OnChangeCursor(ultralight::View* caller,
Cursor cursor) {}
///
/// Called when a message is added to the console (useful for errors / debug)
///
virtual void OnAddConsoleMessage(ultralight::View* caller,
MessageSource source,
MessageLevel level,
const String& message,
uint32_t line_number,
uint32_t column_number,
const String& source_id) {}
};
///
/// @brief Interface for Load-related events
///
/// @note For more info @see View::set_load_listener
///
class UExport LoadListener {
public:
virtual ~LoadListener() {}
///
/// Called when the page begins loading new URL into main frame
///
virtual void OnBeginLoading(ultralight::View* caller) {}
///
/// Called when the page finishes loading URL into main frame
///
virtual void OnFinishLoading(ultralight::View* caller) {}
///
/// Called when the history (back/forward state) is modified
///
virtual void OnUpdateHistory(ultralight::View* caller) {}
///
/// Called when all JavaScript has been parsed and the document is ready.
/// This is the best time to make any initial JavaScript calls to your page.
///
virtual void OnDOMReady(ultralight::View* caller) {}
};
} // namespace ultralight

133
include/Ultralight/Matrix.h Normal file
View File

@ -0,0 +1,133 @@
///
/// @file Matrix.h
///
/// @brief The header for Matrix helpers
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/RefPtr.h>
#include <Ultralight/Geometry.h>
namespace ultralight {
///
/// Affine Matrix helper
///
struct UExport Matrix {
///
/// Raw affine matrix as an array
///
float data[6];
///
/// Set to identity matrix
///
void SetIdentity();
///
/// Set to another matrix
///
void Set(const Matrix& other);
///
/// Set from raw affine members
///
void Set(float a, float b, float c, float d, float e, float f);
///
/// Whether or not this is an identity matrix
///
bool IsIdentity() const;
///
/// Whether or not this is an identity matrix or translation
///
bool IsIdentityOrTranslation() const;
///
/// Whether or not this is an identity, translation, or non-negative
/// uniform scale
///
bool IsSimple() const;
///
/// Translate by x and y
///
void Translate(float x, float y);
///
/// Scale by x and y
///
void Scale(float x, float y);
///
/// Rotate matrix by theta (in degrees)
///
void Rotate(float theta);
///
/// Rotate matrix by x and y
///
void Rotate(float x, float y);
///
/// Transform (multiply) by another Matrix
///
void Transform(const Matrix& other);
///
/// Get the inverse of this matrix. May return false if not invertible.
///
bool GetInverse(Matrix& result) const;
///
/// Transform point by this matrix and get the result.
///
Point Apply(const Point& p) const;
///
/// Transform rect by this matrix and get the result as an axis-aligned rect.
///
Rect Apply(const Rect& r) const;
///
/// Get an integer hash of this matrix's members.
///
uint32_t Hash() const;
};
///
/// 4x4 Matrix Helper
///
struct UExport Matrix4x4 {
///
/// Raw 4x4 matrix as an array
///
float data[16];
///
/// Set to identity matrix.
///
void SetIdentity();
};
///
/// Convert affine matrix to a 4x4 matrix.
///
Matrix4x4 UExport ConvertAffineTo4x4(const Matrix& mat);
bool UExport operator==(const Matrix& a, const Matrix& b);
bool UExport operator!=(const Matrix& a, const Matrix& b);
bool UExport operator==(const Matrix4x4& a, const Matrix4x4& b);
bool UExport operator!=(const Matrix4x4& a, const Matrix4x4& b);
} // namespace ultralight

View File

@ -0,0 +1,77 @@
///
/// @file MouseEvent.h
///
/// @brief The header for the MouseEvent class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
namespace ultralight {
///
/// @brief A generic mouse event.
///
/// @note @see View::FireMouseEvent
///
class MouseEvent {
public:
///
/// The various MouseEvent types.
///
enum Type {
///
/// Mouse moved type
///
kType_MouseMoved,
///
/// Mouse button pressed type
///
kType_MouseDown,
///
/// Mouse button released type
///
kType_MouseUp,
};
///
/// The various mouse button types.
///
enum Button {
kButton_None = 0,
kButton_Left,
kButton_Middle,
kButton_Right,
};
///
/// The type of this MouseEvent
///
Type type;
///
/// The current x-position of the mouse, relative to the View
///
int x;
///
/// The current y-position of the mouse, relative to the View
///
int y;
///
/// The mouse button that was pressed/released, if any.
///
Button button;
};
} // namespace ultralight

537
include/Ultralight/RefPtr.h Normal file
View File

@ -0,0 +1,537 @@
///
/// @file RefPtr.h
///
/// @brief The header for all ref-counting utilities.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
/*
* Portions of the below code are derived from 'RefPtr.h' from Apple's WTF,
* with the following license header:
*
* Copyright (C) 2013-2014 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <Ultralight/Defines.h>
#include <assert.h>
#include <utility>
namespace ultralight {
///
/// @brief Interface for all ref-counted objects that will be managed using
/// the Ref<> and RefPtr<> smart pointers.
///
class UExport RefCounted {
public:
virtual void AddRef() const = 0;
virtual void Release() const = 0;
virtual int ref_count() const = 0;
protected:
virtual ~RefCounted();
};
inline void adopted(const void*) { }
template<typename T> class Ref;
///
/// @brief Helper for wrapping new objects with the Ref smart pointer.
///
/// All ref-counted object are created with an initial ref-count of '1'.
/// The AdoptRef() helper returns a Ref<T> without calling AddRef().
/// This is used for creating new objects, like so:
///
/// Ref<Object> ref = AdoptRef(*new ObjectImpl());
///
template<typename T> Ref<T> AdoptRef(T&);
///
/// @brief A non-nullable smart pointer.
///
/// This smart pointer automatically manages the lifetime of a RefCounted
/// object. Also guarantees that the managed instance is not NULL.
///
template<typename T> class Ref {
public:
///
/// Destroy Ref (wll decrement ref-count by one)
///
~Ref()
{
if (instance_)
instance_->Release();
}
///
/// Construct Ref from a reference. (Will increment ref-count by one)
///
Ref(T& object)
: instance_(&object)
{
instance_->AddRef();
}
///
/// Copy constructor.
///
Ref(const Ref& other)
: instance_(other.instance_)
{
instance_->AddRef();
}
///
/// Copy constructor with internal type conversion.
///
template<typename U>
Ref(Ref<U>& other)
: instance_(other.ptr())
{
instance_->AddRef();
}
///
/// Copy constructor with internal type conversion.
///
template<typename U>
Ref(const Ref<U>& other)
: instance_(other.ptr())
{
instance_->AddRef();
}
///
/// Move constructor.
///
Ref(Ref&& other)
: instance_(&other.LeakRef())
{
assert(instance_);
}
///
/// Move constructor.
///
template<typename U>
Ref(Ref<U>&& other)
: instance_(&other.LeakRef())
{
assert(instance_);
}
Ref& operator=(T& object)
{
assert(instance_);
object.AddRef();
instance_->Release();
instance_ = &object;
assert(instance_);
return *this;
}
Ref& operator=(const Ref& other)
{
assert(instance_);
other.instance_->AddRef();
instance_->Release();
instance_ = other.instance_;
assert(instance_);
return *this;
}
template<typename U>
Ref& operator=(const Ref<U>& other)
{
assert(instance_);
other.instance_->AddRef();
instance_->Release();
instance_ = other.instance_;
assert(instance_);
return *this;
}
Ref& operator=(Ref&& reference)
{
assert(instance_);
instance_->Release();
instance_ = &reference.LeakRef();
assert(instance_);
return *this;
}
template<typename U> Ref& operator=(Ref<U>&& reference)
{
assert(instance_);
instance_->Release();
instance_ = &reference.LeakRef();
assert(instance_);
return *this;
}
const T* operator->() const { assert(instance_); return instance_; }
T* operator->() { assert(instance_); return instance_; }
///
/// Get a pointer to wrapped object.
///
const T* ptr() const { assert(instance_); return instance_; }
///
/// Get a pointer to wrapped object.
///
T* ptr() { assert(instance_); return instance_; }
///
/// Get a reference to wrapped object.
///
const T& get() const { assert(instance_); return *instance_; }
///
/// Get a reference to wrapped object.
///
T& get() { assert(instance_); return *instance_; }
operator T&() { assert(instance_); return *instance_; }
operator const T&() const { assert(instance_); return *instance_; }
template<typename U> Ref<T> Replace(Ref<U>&&);
T& LeakRef() {
assert(instance_);
T* result = std::move(instance_);
instance_ = std::forward<T*>(nullptr);
return *result;
}
friend inline bool operator==(const Ref& a, const Ref& b) {
return a.instance_ == b.instance_;
}
friend inline bool operator!=(const Ref& a, const Ref& b) {
return a.instance_ != b.instance_;
}
friend inline bool operator<(const Ref& a, const Ref& b) {
return a.instance_ < b.instance_;
}
protected:
friend Ref AdoptRef<T>(T&);
template<typename U> friend class RefPtr;
enum AdoptTag { Adopt };
Ref(T& object, AdoptTag)
: instance_(&object)
{
}
T* instance_;
};
template<typename T> template<typename U> Ref<T> Ref<T>::Replace(Ref<U>&& reference)
{
auto oldReference = AdoptRef(*instance_);
instance_ = &reference.LeakRef();
return oldReference;
}
template<typename T>
Ref<T> AdoptRef(T& reference)
{
adopted(&reference);
return Ref<T>(reference, Ref<T>::Adopt);
}
///
/// @brief A nullable smart pointer.
///
/// This smart pointer automatically manages the lifetime of a RefCounted
/// object. The managed instance may be NULL.
///
template<typename T> class RefPtr {
public:
///
/// Construct a NULL ref-pointer.
///
RefPtr()
: instance_(nullptr)
{
}
///
/// Construct a NULL ref-pointer.
///
RefPtr(std::nullptr_t)
: instance_(nullptr)
{
}
///
/// Construct from a pointer. (Will increment ref-count by one)
///
RefPtr(T* other)
: instance_(other)
{
if (instance_)
instance_->AddRef();
}
///
/// Copy constructor.
///
RefPtr(const RefPtr& other)
: instance_(other.instance_)
{
if (instance_)
instance_->AddRef();
}
///
/// Copy constructor with internal type conversion.
///
template<typename U>
RefPtr(const RefPtr<U>& other)
: instance_(other.instance_)
{
if (instance_)
instance_->AddRef();
}
///
/// Move constructor.
///
RefPtr(RefPtr&& other)
: instance_(other.LeakRef())
{
}
///
/// Move constructor.
///
template<typename U>
RefPtr(RefPtr<U>&& other)
: instance_(other.LeakRef())
{
}
///
/// Construct from a Ref
///
template<typename U>
RefPtr(const Ref<U>& other)
: instance_(other.instance_)
{
if (instance_)
instance_->AddRef();
}
///
/// Construct by moving from a Ref
///
template<typename U>
RefPtr(Ref<U>&& other);
///
/// Destroy RefPtr (wll decrement ref-count by one)
///
~RefPtr()
{
T* old_value = std::move(instance_);
instance_ = std::forward<T*>(nullptr);
if (old_value)
old_value->Release();
}
///
/// Get a pointer to wrapped object.
///
T* get() const { return instance_; }
T* LeakRef() {
T* result = std::move(instance_);
instance_ = std::forward<T*>(nullptr);
return result;
}
T& operator*() const { assert(instance_); return *instance_; }
T* operator->() const { return instance_; }
bool operator!() const { return !instance_; }
// This conversion operator allows implicit conversion to bool but not to other integer types.
typedef T* (RefPtr::*UnspecifiedBoolType);
operator UnspecifiedBoolType() const { return instance_ ? &RefPtr::instance_ : nullptr; }
RefPtr& operator=(const RefPtr&);
RefPtr& operator=(T*);
RefPtr& operator=(std::nullptr_t);
template<typename U> RefPtr& operator=(const RefPtr<U>&);
RefPtr& operator=(RefPtr&&);
template<typename U> RefPtr& operator=(RefPtr<U>&&);
template<typename U> RefPtr& operator=(Ref<U>&&);
friend inline bool operator==(const RefPtr& a, const RefPtr& b) {
return a.instance_ == b.instance_;
}
friend inline bool operator!=(const RefPtr& a, const RefPtr& b) {
return a.instance_ != b.instance_;
}
friend inline bool operator<(const RefPtr& a, const RefPtr& b) {
return a.instance_ < b.instance_;
}
void Swap(RefPtr&);
private:
T* instance_;
};
template<typename T>
template<typename U>
RefPtr<T>::RefPtr(Ref<U>&& reference)
: instance_(&reference.LeakRef())
{
}
template<typename T>
RefPtr<T>& RefPtr<T>::operator=(const RefPtr& other)
{
RefPtr ptr = other;
Swap(ptr);
return *this;
}
template<typename T>
template<typename U>
RefPtr<T>& RefPtr<T>::operator=(const RefPtr<U>& other)
{
RefPtr ptr = other;
Swap(ptr);
return *this;
}
template<typename T>
RefPtr<T>& RefPtr<T>::operator=(T* object)
{
RefPtr ptr = object;
Swap(ptr);
return *this;
}
template<typename T>
RefPtr<T>& RefPtr<T>::operator=(std::nullptr_t)
{
T* old_instance = std::move(instance_);
instance_ = std::forward<T*>(nullptr);
if (old_instance)
old_instance->Release();
return *this;
}
template<typename T>
RefPtr<T>& RefPtr<T>::operator=(RefPtr&& other)
{
RefPtr ptr = std::move(other);
Swap(ptr);
return *this;
}
template<typename T>
template<typename U>
RefPtr<T>& RefPtr<T>::operator=(RefPtr<U>&& other)
{
RefPtr ptr = std::move(other);
Swap(ptr);
return *this;
}
template<typename T>
template<typename U>
RefPtr<T>& RefPtr<T>::operator=(Ref<U>&& other)
{
RefPtr ptr = std::move(other);
Swap(ptr);
return *this;
}
template<typename T>
void RefPtr<T>::Swap(RefPtr& other)
{
std::swap(instance_, other.instance_);
}
template<class T>
void Swap(RefPtr<T>& a, RefPtr<T>& b)
{
a.Swap(b);
}
template<typename T, typename U>
bool operator==(const RefPtr<T>& a, const RefPtr<U>& b)
{
return a.get() == b.get();
}
template<typename T, typename U>
bool operator==(const RefPtr<T>& a, U* b)
{
return a.get() == b;
}
template<typename T, typename U>
bool operator==(T* a, const RefPtr<U>& b)
{
return a == b.get();
}
template<typename T, typename U>
bool operator!=(const RefPtr<T>& a, const RefPtr<U>& b)
{
return a.get() != b.get();
}
template<typename T, typename U>
bool operator!=(const RefPtr<T>& a, U* b)
{
return a.get() != b;
}
template<typename T, typename U>
bool operator!=(T* a, const RefPtr<U>& b)
{
return a != b.get();
}
} // namespace ultralight

View File

@ -0,0 +1,84 @@
///
/// @file RenderTarget.h
///
/// @brief The header for the RenderTarget struct.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/Bitmap.h>
#include <Ultralight/Geometry.h>
namespace ultralight {
#pragma pack(push, 1)
///
/// @brief Rendering details for a View, to be used with your own GPUDriver
///
/// When using your own GPUDriver, each View is rendered to an offscreen
/// texture that you must display on a quad in your engine. This struct
/// provides all the details you need to render the View texture in your
/// engine.
///
struct UExport RenderTarget {
///
/// Whether this target is empty (null texture)
///
bool is_empty;
///
/// The viewport width (in device coordinates).
///
uint32_t width;
///
/// The viewport height (in device coordinates).
///
uint32_t height;
///
/// The GPUDriver-specific texture ID (you should bind the texture using
/// your implementation of GPUDriver::BindTexture before drawing a quad).
///
uint32_t texture_id;
///
/// The texture width (in pixels). This may be padded.
///
uint32_t texture_width;
///
/// The texture height (in pixels). This may be padded.
///
uint32_t texture_height;
///
/// The pixel format of the texture.
///
BitmapFormat texture_format;
///
/// UV coordinates of the texture (this is needed because the texture may
/// be padded).
///
Rect uv_coords;
///
/// The GPUDriver-specific render buffer ID.
///
uint32_t render_buffer_id;
RenderTarget();
};
#pragma pack(pop)
} // namespace ultralight

View File

@ -0,0 +1,90 @@
///
/// @file Renderer.h
///
/// @brief The header for the Renderer class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/RefPtr.h>
#include <Ultralight/View.h>
namespace ultralight {
///
/// @brief The core of Ultralight. You should initialize it after setting up
/// your Platform config and drivers.
///
/// This singleton class manages the lifetime of all Views (@see View) and
/// coordinates all painting, rendering, network requests, and event dispatch.
///
/// @note You don't have to create this instance directly if you use the
/// AppCore API. The App class will automatically create a Renderer and
/// perform all rendering within its run loop. @see App::Create
///
class UExport Renderer : public RefCounted {
public:
///
/// Create the Renderer singleton. You should set up all your Platform config,
/// file-system, and drivers before calling this function. @see Platform
///
/// @note You should only create one Renderer per application lifetime.
///
/// @return Returns a ref-pointer to a new Renderer instance. You should
/// assign it to either a Ref<Renderer> (non-nullable) or
/// RefPtr<Renderer> (nullable).
///
static Ref<Renderer> Create();
///
/// Create a new View.
///
/// @param width The initial width, in device coordinates.
///
/// @param height The initial height, in device coordinates.
///
/// @param transparent Whether or not the view background is transparent.
///
/// @return Returns a ref-pointer to a new View instance. You should assign
/// it to either a Ref<View> (non-nullable) or RefPtr<View>
/// (nullable).
///
/// @note The device coordinates are scaled to pixels by multiplying them
/// with the current DPI scale (@see Config::device_scale_hint) and
/// rounding to the nearest integer value.
///
virtual Ref<View> CreateView(uint32_t width, uint32_t height,
bool transparent) = 0;
///
/// Update timers and dispatch internal callbacks. You should call this often
/// from your main application loop.
///
virtual void Update() = 0;
///
/// Render all active views to display lists and dispatch calls to GPUDriver.
///
/// @note If you're using the default, offscreen GL driver, this updates the
/// internal bitmap of each View (@see View::bitmap).
///
virtual void Render() = 0;
///
/// Attempt to release as much memory as possible. Don't call this from any
/// callbacks or driver code.
///
virtual void PurgeMemory() = 0;
protected:
virtual ~Renderer();
};
} // namespace ultralight

View File

@ -0,0 +1,53 @@
///
/// @file ScrollEvent.h
///
/// @brief The header for the ScrollEvent class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
namespace ultralight {
///
/// @brief A generic scroll event.
///
/// @note @see View::FireScrollEvent
///
class ScrollEvent {
public:
///
/// The scroll event granularity type
///
enum Type {
/// The delta value is interpreted as number of pixels
kType_ScrollByPixel,
/// The delta value is interpreted as number of pages
kType_ScrollByPage,
};
///
/// Scroll granularity type
///
Type type;
///
/// Horizontal scroll amount
///
int delta_x;
///
/// Vertical scroll amount
///
int delta_y;
};
} // namespace ultralight

120
include/Ultralight/String.h Normal file
View File

@ -0,0 +1,120 @@
///
/// @file String.h
///
/// @brief The header for the String class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/String8.h>
#include <Ultralight/String16.h>
#include <Ultralight/String32.h>
namespace ultralight {
///
/// @brief UTF-16 String container with conversions for UTF-8 and UTF-32.
///
/// @note Internally, all strings are represented as UTF-16.
///
class UExport String {
public:
///
/// Create empty string
///
String();
///
/// Create from null-terminated, ASCII C-string
///
String(const char* str);
///
/// Create from raw, UTF-8 string with certain length
///
String(const char* str, size_t len);
///
/// Create from existing String8 (UTF-8).
///
String(const String8& str);
///
/// Create from raw UTF-16 string with certain length
///
String(const Char16* str, size_t len);
///
/// Create from existing String16 (UTF-16)
///
String(const String16& str);
///
/// Create from existing String32 (UTF-32)
///
String(const String32& str);
///
/// Copy constructor
///
String(const String& other);
///
/// Destructor
///
~String();
///
/// Assign string from another, copy is made
///
String& operator=(const String& other);
///
/// Append string with another
///
String& operator+=(const String& other);
///
/// Concatenation operator
///
inline friend String operator+(String lhs, const String& rhs) { lhs += rhs; return lhs; }
///
/// Get native UTF-16 string
///
String16& utf16() { return str_; }
///
/// Get native UTF-16 string
///
const String16& utf16() const { return str_; }
///
/// Convert to UTF-8 string
///
String8 utf8() const;
///
/// Convert to UTF-32 string
///
String32 utf32() const;
///
/// Check if string is empty or not
///
bool empty() const { return utf16().empty(); }
private:
String16 str_;
};
} // namespace ultralight

View File

@ -0,0 +1,130 @@
///
/// @file String16.h
///
/// @brief The header for the String16 class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/RefPtr.h>
#include <stddef.h>
namespace ultralight {
namespace detail {
template<int> struct selector;
template<> struct selector<4> { typedef char16_t Char16; };
template<> struct selector<2> { typedef wchar_t Char16; };
}
#ifdef DISABLE_NATIVE_WCHAR_T
// Force Char16 type to use char16_t, used on Windows when native wchar_t support is disabled.
typedef char16_t Char16;
#else
// We use wchar_t if size == 2, otherwise use char16_t
typedef detail::selector<sizeof(wchar_t)>::Char16 Char16;
#endif
///
/// @brief A UTF-16 string container.
///
class UExport String16 {
public:
// Make an empty String16
String16();
// Make a String16 from null-terminated ASCII C-string
String16(const char* c_str);
// Make a String16 from ASCII C-string with certain length
String16(const char* c_str, size_t len);
// Make a String16 from raw UTF-16 buffer with certain length
String16(const Char16* str, size_t len);
// Make a String16 from raw unsigned short UTF-16 buffer with certain length. Useful on Windows
// when native support for wchar_t is disabled (eg, /Zc:wchar_t-).
String16(const unsigned short* str, size_t len);
// Make a deep copy of String16
String16(const String16& other);
~String16();
// Assign a String16 to this one, deep copy is made
String16& operator=(const String16& other);
// Append a String16 to this one.
String16& operator+=(const String16& other);
// Concatenation operator
inline friend String16 operator+(String16 lhs, const String16& rhs) { lhs += rhs; return lhs; }
// Get raw UTF-16 data
Char16* data() { return data_; }
// Get raw UTF-16 data (const)
const Char16* data() const { return data_; }
// Get raw UTF-16 data as unsigned short. This is useful on Windows if you compile without native
// support for wchar_t (eg, /Zc:wchar_t-)
unsigned short* udata() { return reinterpret_cast<unsigned short*>(data_); }
// Get raw UTF-16 data as unsigned short (const).
const unsigned short* udata() const { return reinterpret_cast<const unsigned short*>(data_); }
// Get length in characters.
size_t length() const { return length_; }
// Get size in characters (synonym for length)
size_t size() const { return length_; }
// Check if string is empty.
bool empty() const { return !data_ || length_ == 0; }
// Get character at specific position
Char16& operator[](size_t pos) { return data_[pos]; }
// Get character at specific position (const)
const Char16& operator[](size_t pos) const { return data_[pos]; }
private:
Char16* data_;
size_t length_;
};
///
/// @brief A UTF-16 string vector.
///
class UExport String16Vector : public RefCounted {
public:
// Create an empty string vector
static Ref<String16Vector> Create();
// Create a string vector from an existing array (a deep copy is made)
static Ref<String16Vector> Create(const String16* stringArray, size_t len);
// Add an element to the back of the string vector
virtual void push_back(const String16& val) = 0;
// Get raw String16 vector array
virtual String16* data() = 0;
// Get the number of elements in vector
virtual size_t size() const = 0;
protected:
String16Vector();
virtual ~String16Vector();
String16Vector(const String16Vector&);
void operator=(const String16Vector&);
};
} // namespace ultralight

View File

@ -0,0 +1,71 @@
///
/// @file String32.h
///
/// @brief The header for the String32 class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <stddef.h>
namespace ultralight {
///
/// @brief A UTF-32 string container.
///
class UExport String32 {
public:
// Make an empty String32
String32();
// Make a String32 from raw UTF-32 string with certain length
String32(const char32_t* c_str, size_t len);
// Make a deep copy of String32
String32(const String32& other);
~String32();
// Assign a String32 to this one, deep copy is made
String32& operator=(const String32& other);
// Append a String32 to this one.
String32& operator+=(const String32& other);
// Concatenation operator
inline friend String32 operator+(String32 lhs, const String32& rhs) { lhs += rhs; return lhs; }
// Get raw UTF-32 data
char32_t* data() { return data_; }
// Get raw UTF-32 data (const)
const char32_t* data() const { return data_; }
// Get length in characters.
size_t length() const { return length_; }
// Get size in characters (synonym for length)
size_t size() const { return length_; }
// Check if string is empty.
bool empty() const { return !data_ || length_ == 0; }
// Get character at specific position
char32_t& operator[](size_t pos) { return data_[pos]; }
// Get character at specific position (const)
const char32_t& operator[](size_t pos) const { return data_[pos]; }
private:
char32_t* data_;
size_t length_;
};
} // namespace ultralight

View File

@ -0,0 +1,74 @@
///
/// @file String8.h
///
/// @brief The header for the String8 class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <stddef.h>
namespace ultralight {
///
/// @brief A UTF-8 string container.
//
class UExport String8 {
public:
// Make an empty String8
String8();
// Make a String8 from raw, null-terminated UTF-8 string
String8(const char* c_str);
// Make a String8 from raw UTF-8 string with certain length
String8(const char* c_str, size_t len);
// Make a deep copy of String8
String8(const String8& other);
~String8();
// Assign a String8 to this one, deep copy is made
String8& operator=(const String8& other);
// Append a String8 to this one.
String8& operator+=(const String8& other);
// Concatenation operator
inline friend String8 operator+(String8 lhs, const String8& rhs) { lhs += rhs; return lhs; }
// Get raw UTF-8 data
char* data() { return data_; }
// Get raw UTF-8 data (const)
const char* data() const { return data_; }
// Get length in characters.
size_t length() const { return length_; }
// Get size in characters (synonym for length)
size_t size() const { return length_; }
// Check if string is empty.
bool empty() const { return !data_ || length_ == 0; }
// Get character at specific position
char& operator[](size_t pos) { return data_[pos]; }
// Get character at specific position (const)
const char& operator[](size_t pos) const { return data_[pos]; }
private:
char* data_;
size_t length_;
};
} // namespace ultralight

View File

@ -0,0 +1,24 @@
// Copyright 2019 Ultralight, Inc. All rights reserved.
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/RefPtr.h>
#include <Ultralight/String16.h>
#include <Ultralight/String8.h>
#include <Ultralight/String.h>
#include <Ultralight/Bitmap.h>
#include <Ultralight/Buffer.h>
#include <Ultralight/View.h>
#include <Ultralight/KeyCodes.h>
#include <Ultralight/KeyEvent.h>
#include <Ultralight/Listener.h>
#include <Ultralight/Matrix.h>
#include <Ultralight/MouseEvent.h>
#include <Ultralight/Renderer.h>
#include <Ultralight/Geometry.h>
#include <Ultralight/RenderTarget.h>
#include <Ultralight/ScrollEvent.h>
#include <Ultralight/platform/Platform.h>
#include <Ultralight/platform/Config.h>
#include <Ultralight/platform/GPUDriver.h>
#include <Ultralight/platform/FileSystem.h>
#include <Ultralight/platform/FontLoader.h>

233
include/Ultralight/View.h Normal file
View File

@ -0,0 +1,233 @@
///
/// @file View.h
///
/// @brief The header for the View class.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <JavaScriptCore/JavaScript.h>
#include <Ultralight/Defines.h>
#include <Ultralight/RefPtr.h>
#include <Ultralight/KeyEvent.h>
#include <Ultralight/MouseEvent.h>
#include <Ultralight/ScrollEvent.h>
#include <Ultralight/RenderTarget.h>
#include <Ultralight/Bitmap.h>
#include <Ultralight/Listener.h>
namespace ultralight {
///
/// @brief A View is similar to a tab in a browser-- you load web content into
/// it and display it however you want. @see Renderer::CreateView
///
/// @note The API is currently not thread-safe, all calls must be made on the
/// main thread.
///
class UExport View : public RefCounted {
public:
///
/// Get the URL of the current page loaded into this View, if any.
///
virtual String url() = 0;
///
/// Get the title of the current page loaded into this View, if any.
///
virtual String title() = 0;
///
/// Get the width of the View, in device coordinates.
///
virtual uint32_t width() const = 0;
///
/// Get the height of the View, in device coordinates.
///
virtual uint32_t height() const = 0;
///
/// Check if the main frame of the page is currently loading.
///
virtual bool is_loading() = 0;
///
/// Get the RenderTarget for the View.
///
/// @note The RenderTarget is only used when you define a custom GPUDriver.
///
/// During each call to Renderer::Render, each View will be drawn to
/// an offscreen texture/render-buffer. You should use RenderTarget
/// to obtain the internal texture ID for the View and then display
/// it in some quad (eg, call GPUDriver::BindTexture with the texture
/// ID, then draw a textured quad in your 3D engine, making sure to
/// use the UV coords specified in the RenderTarget).
///
/// @see Overlay.cpp within the AppCore source for an example.
///
virtual RenderTarget render_target() = 0;
///
/// Check if bitmap is dirty (has changed since last call to View::bitmap)
///
/// @note Only valid when using the default, offscreen GPUDriver.
///
virtual bool is_bitmap_dirty() = 0;
///
/// Get the bitmap for the View (calling this resets the dirty state).
///
// @note Only valid when using the default, offscreen GPUDriver.
///
virtual RefPtr<Bitmap> bitmap() = 0;
///
/// Load a raw string of HTML, the View will navigate to it as a new page.
///
virtual void LoadHTML(const String& html) = 0;
///
/// Load a URL, the View will navigate to it as a new page.
///
/// @note You can use File URLs (eg, file:///page.html) but you must define
/// your own FileSystem implementation. @see Platform::set_file_system
///
virtual void LoadURL(const String& url) = 0;
///
/// Resize View to a certain size.
///
/// @param width The initial width, in device coordinates.
///
/// @param height The initial height, in device coordinates.
///
/// @note The device coordinates are scaled to pixels by multiplying them
/// with the current DPI scale (@see Config::device_scale_hint) and
/// rounding to the nearest integer value.
///
virtual void Resize(uint32_t width, uint32_t height) = 0;
///
/// Get the page's JSContext for use with the JavaScriptCore API
///
/// @note We expose the entire JavaScriptCore API to users for maximum
/// flexibility. Each page has its own JSContext that gets reset
/// after each page navigation. You should make all your initial
/// JavaScript calls to the page within the DOMReady event,
/// @see ViewListener::OnDOMReady
///
virtual JSContextRef js_context() = 0;
///
/// Evaluate a raw string of JavaScript and return results as a native
/// JavaScriptCore JSValueRef (@see <JavaScriptCore/JSValueRef.h>)
///
/// @note This is just a wrapper for JSEvaluateScript() in JavaScriptCore
///
virtual JSValueRef EvaluateScript(const String& script) = 0;
///
/// Whether or not we can navigate backwards in history
///
virtual bool CanGoBack() = 0;
///
/// Whether or not we can navigate forwards in history
///
virtual bool CanGoForward() = 0;
///
/// Navigate backwards in history
///
virtual void GoBack() = 0;
///
/// Navigate forwards in history
///
virtual void GoForward() = 0;
///
/// Navigate to an arbitrary offset in history
///
virtual void GoToHistoryOffset(int offset) = 0;
///
/// Reload current page
///
virtual void Reload() = 0;
///
/// Stop all page loads
///
virtual void Stop() = 0;
///
/// Fire a keyboard event
///
/// @note Only 'Char' events actually generate text in input fields.
///
virtual void FireKeyEvent(const KeyEvent& evt) = 0;
///
/// Fire a mouse event
///
virtual void FireMouseEvent(const MouseEvent& evt) = 0;
///
/// Fire a scroll event
///
virtual void FireScrollEvent(const ScrollEvent& evt) = 0;
///
/// Set a ViewListener to receive callbacks for View-related events.
///
/// @note Ownership remains with the caller.
///
virtual void set_view_listener(ViewListener* listener) = 0;
///
/// Get the active ViewListener, if any
///
virtual ViewListener* view_listener() const = 0;
///
/// Set a LoadListener to receive callbacks for Load-related events.
///
/// @note Ownership remains with the caller.
///
virtual void set_load_listener(LoadListener* listener) = 0;
///
/// Get the active LoadListener, if any
///
virtual LoadListener* load_listener() const = 0;
///
/// Set whether or not this View should be repainted during the next
/// call to Renderer::Render
///
/// @note This flag is automatically set whenever the page content changes
/// but you can set it directly in case you need to force a repaint.
///
virtual void set_needs_paint(bool needs_paint) = 0;
///
/// Whether or not this View should be repainted during the next call to
/// Renderer::Render.
///
virtual bool needs_paint() const = 0;
virtual RefPtr<View> inspector() = 0;
protected:
virtual ~View();
};
} // namespace ultralight

View File

@ -0,0 +1,112 @@
///
/// @file Config.h
///
/// @brief The header for the Config struct.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/String16.h>
namespace ultralight {
///
/// The winding order for front-facing triangles.
///
/// @note In most 3D engines, there is the concept that triangles have a
/// a "front" and a "back". All the front-facing triangles (eg, those
/// that are facing the camera) are rendered, and all back-facing
/// triangles are culled (ignored). The winding-order of the triangle's
/// vertices is used to determine which side is front and back. You
/// should tell Ultralight which winding-order your 3D engine uses.
///
enum FaceWinding {
///
/// Clockwise Winding (Direct3D, etc.)
///
kFaceWinding_Clockwise,
///
/// Counter-Clockwise Winding (OpenGL, etc.)
///
kFaceWinding_CounterClockwise,
};
///
/// @brief Configurations settings for Ultralight.
///
/// This is intended to be implemented by users and defined before creating the
/// Renderer. @see Platform::set_config.
///
struct UExport Config {
///
/// The winding order for front-facing triangles. @see FaceWinding
///
FaceWinding face_winding = kFaceWinding_CounterClockwise;
///
/// Whether or not images should be enabled.
///
bool enable_images = true;
///
/// Whether or not JavaScript should be enabled
///
bool enable_javascript = true;
///
/// When using the default, offscreen GPU driver, whether or not we
/// should use BGRA byte order (instead of RGBA). @see View::bitmap
///
bool use_bgra_for_offscreen_rendering = false;
///
/// The amount that the application DPI has been scaled (200% = 2.0).
/// Used for scaling device coordinates to pixels and oversampling raster
/// shapes.
///
double device_scale_hint = 1.0;
///
/// Default font-family to use.
///
String16 font_family_standard = "Times New Roman";
///
/// Default font-family to use for fixed fonts. (pre/code)
///
String16 font_family_fixed = "Courier New";
///
/// Default font-family to use for serif fonts.
///
String16 font_family_serif = "Times New Roman";
///
/// Default font-family to use for sans-serif fonts.
///
String16 font_family_sans_serif = "Arial";
///
/// Default user-agent string.
///
String16 user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/602.1 (KHTML, like Gecko) "
"Ultralight/0.9.2 Safari/602.1";
///
/// Default user stylesheet. You should set this to your own custom CSS
/// string to define default styles for various DOM elements, scrollbars,
/// and platform input widgets.
///
String16 user_stylesheet;
};
} // namespace ultralight

View File

@ -0,0 +1,208 @@
///
/// @file FileSystem.h
///
/// @brief The header for the FileSystem interface.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/String16.h>
#include <time.h>
namespace ultralight {
///
/// File Handle type used as unique ID for opened files.
///
#if defined(__WIN32__) || defined(_WIN32)
typedef size_t FileHandle;
#else
typedef int FileHandle;
#endif
///
/// Handle used to denote an invalid file.
///
const FileHandle invalidFileHandle = (FileHandle)-1;
///
/// The position to seek from in a file, @see FileSystem::SeekFile
///
enum FileSeekOrigin {
kFileSeekOrigin_Beginning = 0,
kFileSeekOrigin_Current,
kFileSeekOrigin_End
};
///
/// The type of path, @see FileSystem::GetMetadata
///
enum MetadataType {
kMetadataType_Unknown = 0,
kMetadataType_File,
kMetadataType_Directory,
};
///
/// @brief FileSystem interface, used for all file system operations.
///
/// This is used for things like loading File URLs (eg, <file:///page.html> and
/// the JavaScript FileSystem API. If you don't implement this interface, you
/// will not be able to load any File URLs.
///
///
/// This is intended to be implemented by users and defined before creating the
/// Renderer. @see Platform::set_file_system.
///
/// @note To support File URL loading, you ONLY need to implement the
/// following functions:
/// - FileSystem::FileExists
/// - FileSystem::GetFileSize
/// - FileSystem::GetFileMimeType
/// - FileSystem::OpenFile
/// - FileSystem::ReadFromFile
/// - FileSystem::CloseFile
///
class UExport FileSystem {
public:
virtual ~FileSystem();
///
/// Check if file path exists, return true if exists.
///
virtual bool FileExists(const String16& path) = 0;
///
/// Delete file, return true on success.
///
virtual bool DeleteFile_(const String16& path) = 0;
///
/// Delete empty directory, return true on success.
///
virtual bool DeleteEmptyDirectory(const String16& path) = 0;
///
/// Move file, return true on success.
///
virtual bool MoveFile_(const String16& old_path, const String16& new_path) = 0;
///
/// Get file size, store result in 'result'. Return true on success.
///
virtual bool GetFileSize(const String16& path, int64_t& result) = 0;
///
/// Get file size of previously opened file, store result in 'result'. Return true on success.
///
virtual bool GetFileSize(FileHandle handle, int64_t& result) = 0;
///
/// Get file mime type (eg "text/html"), store result in 'result'. Return true on success.
///
virtual bool GetFileMimeType(const String16& path, String16& result) = 0;
///
/// Get file last modification time, store result in 'result'. Return true on success.
///
virtual bool GetFileModificationTime(const String16& path, time_t& result) = 0;
///
/// Get file creation time, store result in 'result'. Return true on success.
///
virtual bool GetFileCreationTime(const String16& path, time_t& result) = 0;
///
/// Get path type (file or directory).
///
virtual MetadataType GetMetadataType(const String16& path) = 0;
///
/// Concatenate path with another path component. Return concatenated result.
///
virtual String16 GetPathByAppendingComponent(const String16& path, const String16& component) = 0;
///
/// Create directory, return true on success.
///
virtual bool CreateDirectory_(const String16& path) = 0;
///
/// Get home directory path.
///
virtual String16 GetHomeDirectory() = 0;
///
/// Get filename component from path.
///
virtual String16 GetFilenameFromPath(const String16& path) = 0;
///
/// Get directory name from path.
///
virtual String16 GetDirectoryNameFromPath(const String16& path) = 0;
///
/// Get volume from path and store free space in 'result'. Return true on success.
///
virtual bool GetVolumeFreeSpace(const String16& path, uint64_t& result) = 0;
///
/// Get volume from path and return its unique volume id.
///
virtual int32_t GetVolumeId(const String16& path) = 0;
///
/// Get file listing for directory path with optional filter, return vector of file paths.
///
virtual Ref<String16Vector> ListDirectory(const String16& path, const String16& filter) = 0;
///
/// Open a temporary file with suggested prefix, store handle in 'handle'. Return path of temporary file.
///
virtual String16 OpenTemporaryFile(const String16& prefix, FileHandle& handle) = 0;
///
/// Open file path for reading or writing. Return file handle on success, or invalidFileHandle on failure.
///
virtual FileHandle OpenFile(const String16& path, bool open_for_writing) = 0;
///
/// Close previously-opened file.
///
virtual void CloseFile(FileHandle& handle) = 0;
///
/// Seek currently-opened file, with offset relative to certain origin. Return new file offset.
///
virtual int64_t SeekFile(FileHandle handle, int64_t offset, FileSeekOrigin origin) = 0;
///
/// Truncate currently-opened file with offset, return true on success.
///
virtual bool TruncateFile(FileHandle handle, int64_t offset) = 0;
///
/// Write to currently-opened file, return number of bytes written or -1 on failure.
///
virtual int64_t WriteToFile(FileHandle handle, const char* data, int64_t length) = 0;
///
/// Read from currently-opened file, return number of bytes read or -1 on failure.
///
virtual int64_t ReadFromFile(FileHandle handle, char* data, int64_t length) = 0;
///
/// Copy file from source to destination, return true on success.
///
virtual bool CopyFile_(const String16& source_path, const String16& destination_path) = 0;
};
} // namespace ultralight

View File

@ -0,0 +1,86 @@
///
/// @file FontLoader.h
///
/// @brief The header for the FontLoader interface.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
#include <Ultralight/String16.h>
#include <Ultralight/Buffer.h>
namespace ultralight {
///
/// @brief Font Loader interface, used for all font lookup operations.
///
/// Every operating system has its own library of installed system fonts. The
/// FontLoader interface is used to lookup these fonts and fetch the actual
/// font data (raw TTF/OTF file data) given a certain font description.
///
/// You can override this interface to bundle your own fonts or override the
/// default system font loading behavior.
///
/// This is intended to be implemented by users and defined before creating the
/// Renderer. @see Platform::set_font_loader
///
class UExport FontLoader {
public:
virtual ~FontLoader();
///
/// Fallback font family name. Will be used if all other fonts fail to load.
///
/// @note This font should be GUARANTEED to exist (eg, FontLoader::Load
/// won't fail when passed this font family name).
///
virtual String16 fallback_font() const = 0;
///
/// Fallback font family name that can render the specified characters. This
/// is mainly used to support CJK (Chinese, Japanese, Korean) text display.
///
/// @param characters One or more UTF-16 characters. This is almost ALWAYS
/// a single character.
///
/// @param weight Font weight.
///
/// @param italic Whether or not italic is requested.
///
/// @param size Font size.
///
/// @return Should return a font family name that can render the text.
///
virtual String16 fallback_font_for_characters(const String16& characters,
int weight, bool italic,
float size) const = 0;
///
/// Get the actual font file data (TTF/OTF) for a given font description.
///
/// @param family Font family name.
///
/// @param weight Font weight.
///
/// @param italic Whether or not italic is requested.
///
/// @param size Font size.
///
/// @return A buffer of bytes containing raw font file contents of the
/// font matching the given description.
///
/// @note As an example of usage, when given the family "Arial", this
/// function should return the raw file contents for "ARIAL.TTF"
///
virtual Ref<Buffer> Load(const String16& family, int weight, bool italic,
float size) = 0;
};
} // namespace ultralight

View File

@ -0,0 +1,283 @@
///
/// @file GPUDriver.h
///
/// @brief The header for the GPUDriver interface.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#pragma warning(disable: 4251)
#include <Ultralight/Defines.h>
#include <Ultralight/Geometry.h>
#include <Ultralight/Matrix.h>
#include <Ultralight/Bitmap.h>
namespace ultralight {
///
/// @note This pragma pack(push, 1) command is important! Vertex layouts
/// should not be padded with any bytes.
///
#pragma pack(push, 1)
///
/// RenderBuffer description, @see GPUDriver::CreateRenderBuffer.
///
struct UExport RenderBuffer {
uint32_t texture_id;
uint32_t width;
uint32_t height;
bool has_stencil_buffer;
bool has_depth_buffer;
};
///
/// Vertex layout for path vertices, useful for synthesizing or modifying
/// vertex data.
///
struct Vertex_2f_4ub_2f {
float pos[2];
unsigned char color[4];
float obj[2];
};
///
/// Vertex layout for quad vertices, useful for synthesizing or modifying
/// vertex data.
///
struct Vertex_2f_4ub_2f_2f_28f {
float pos[2];
unsigned char color[4];
float tex[2];
float obj[2];
float data0[4];
float data1[4];
float data2[4];
float data3[4];
float data4[4];
float data5[4];
float data6[4];
};
///
/// Vertex formats
///
enum UExport VertexBufferFormat {
kVertexBufferFormat_2f_4ub_2f,
kVertexBufferFormat_2f_4ub_2f_2f_28f,
};
///
/// Vertex buffer, @see GPUDriver::CreateGeometry
///
struct UExport VertexBuffer {
VertexBufferFormat format;
uint32_t size;
uint8_t* data;
};
///
/// Vertex index type
///
typedef uint32_t IndexType;
///
/// Vertex index buffer, @see GPUDriver::CreateGeometry
///
struct UExport IndexBuffer {
uint32_t size;
uint8_t* data;
};
///
/// Shader types, used by GPUState::shader_type
///
enum UExport ShaderType {
kShaderType_Fill,
kShaderType_FillPath,
};
///
/// GPU state description.
///
struct UExport GPUState {
float viewport_width;
float viewport_height;
Matrix4x4 transform;
bool enable_texturing;
bool enable_blend;
uint8_t shader_type;
uint32_t render_buffer_id;
uint32_t texture_1_id;
uint32_t texture_2_id;
uint32_t texture_3_id;
float uniform_scalar[8];
vec4 uniform_vector[8];
uint8_t clip_size;
Matrix4x4 clip[8];
};
///
/// Command types, used by Command::command_type
///
enum UExport CommandType {
kCommandType_ClearRenderBuffer,
kCommandType_DrawGeometry,
};
///
/// Command description, handling one of these should result in either a call to
/// GPUDriver::ClearRenderBuffer or GPUDriver::DrawGeometry.
///
struct UExport Command {
uint8_t command_type;
GPUState gpu_state;
uint32_t geometry_id;
uint32_t indices_count;
uint32_t indices_offset;
};
///
/// Command list, @see GPUDriver::UpdateCommandList
///
struct UExport CommandList {
uint32_t size;
Command* commands;
};
#pragma pack(pop)
///
/// @brief GPUDriver interface, dispatches GPU calls to the native driver.
///
/// By default, Ultralight uses an offscreen, OpenGL GPUDriver that draws each
/// View to an offscreen Bitmap (@see View::bitmap). You can override this to
/// provide your own GPUDriver and integrate directly with your own 3D engine.
///
/// This is intended to be implemented by users and defined before creating the
/// Renderer. @see Platform::set_gpu_driver
///
class UExport GPUDriver {
public:
virtual ~GPUDriver();
///
/// Called before any commands are dispatched during a frame.
///
virtual void BeginSynchronize() = 0;
///
/// Called after any commands are dispatched during a frame.
///
virtual void EndSynchronize() = 0;
///
/// Get the next available texture ID.
///
virtual uint32_t NextTextureId() = 0;
/// Create a texture with a certain ID and optional bitmap. If the Bitmap is
/// empty (Bitmap::IsEmpty), then a RTT Texture should be created instead.
///
virtual void CreateTexture(uint32_t texture_id,
Ref<Bitmap> bitmap) = 0;
///
/// Update an existing non-RTT texture with new bitmap data.
///
virtual void UpdateTexture(uint32_t texture_id,
Ref<Bitmap> bitmap) = 0;
///
/// Bind a texture to a certain texture unit.
///
virtual void BindTexture(uint8_t texture_unit,
uint32_t texture_id) = 0;
///
/// Destroy a texture.
///
virtual void DestroyTexture(uint32_t texture_id) = 0;
///
/// Generate the next available render buffer ID.
///
virtual uint32_t NextRenderBufferId() = 0;
///
/// Create a render buffer with certain ID and buffer description.
///
virtual void CreateRenderBuffer(uint32_t render_buffer_id,
const RenderBuffer& buffer) = 0;
///
/// Bind a render buffer
///
virtual void BindRenderBuffer(uint32_t render_buffer_id) = 0;
///
/// Clear a render buffer (flush pixels)
///
virtual void ClearRenderBuffer(uint32_t render_buffer_id) = 0;
///
/// Destroy a render buffer
///
virtual void DestroyRenderBuffer(uint32_t render_buffer_id) = 0;
///
/// Generate the next available geometry ID.
///
virtual uint32_t NextGeometryId() = 0;
///
/// Create geometry with certain ID and vertex/index data.
///
virtual void CreateGeometry(uint32_t geometry_id,
const VertexBuffer& vertices,
const IndexBuffer& indices) = 0;
///
/// Update existing geometry with new vertex/index data.
///
virtual void UpdateGeometry(uint32_t geometry_id,
const VertexBuffer& vertices,
const IndexBuffer& indices) = 0;
///
/// Draw geometry using the specific index count/offset and GPUState.
///
virtual void DrawGeometry(uint32_t geometry_id,
uint32_t indices_count,
uint32_t indices_offset,
const GPUState& state) = 0;
///
/// Destroy geometry.
///
virtual void DestroyGeometry(uint32_t geometry_id) = 0;
///
/// Update command list (you should copy the commands to your own structure).
///
virtual void UpdateCommandList(const CommandList& list) = 0;
///
/// Check if any commands need drawing.
///
virtual bool HasCommandsPending() = 0;
///
/// Iterate through stored command list and dispatch to ClearRenderBuffer or
/// DrawGeometry, respectively. Command list should be cleared at end of call.
///
virtual void DrawCommandList() = 0;
};
} // namespace ultralight

View File

@ -0,0 +1,116 @@
///
/// @file Platform.h
///
/// @brief The header for the Platform singleton.
///
/// @author
///
/// This file is a part of Ultralight, a fast, lightweight, HTML UI engine
///
/// Website: <http://ultralig.ht>
///
/// Copyright (C) 2019 Ultralight, Inc. All rights reserved.
///
#pragma once
#include <Ultralight/Defines.h>
namespace ultralight {
struct Config;
class GPUDriver;
class FontLoader;
class FileSystem;
///
/// @brief Platform singleton to configure Ultralight and provide user-defined
/// implementations for various platform operations.
///
/// @note All of these settings and user-defined interfaces should be set
/// BEFORE creating the Renderer.
///
/// A default GPUDriver and FontLoader are provided, you must provide
/// your own FileSystem interface if you want to load local files.
///
/// For more info about the defaults @see DefaultGPUDriver and
/// @see DefaultFontLoader.
///
class UExport Platform {
public:
///
/// Get the Platform singleton
///
static Platform& instance();
virtual ~Platform();
///
/// Set the Config
///
virtual void set_config(const Config& config) = 0;
///
/// Get the Config
///
virtual const Config& config() const = 0;
///
/// Set the GPU Driver (will handle all rendering)
///
/// @param gpu_driver A user-defined GPUDriver implementation, ownership
/// remains with the caller.
///
/// @note If you never call this, the default driver will be used instead.
/// @see DefaultGPUDriver
///
virtual void set_gpu_driver(GPUDriver* gpu_driver) = 0;
///
/// Get the GPU Driver
///
virtual GPUDriver* gpu_driver() const = 0;
///
/// Set the Font Loader (will be used to map font families to actual fonts)
///
/// @param font_loader A user-defined FontLoader implementation, ownership
/// remains with the caller.
///
/// @note If you never call this, the default font loader will be used
/// instead. @see DefaultFontLoader
///
virtual void set_font_loader(FontLoader* font_loader) = 0;
///
/// Get the Font Loader
///
virtual FontLoader* font_loader() const = 0;
///
/// Set the File System (will be used for all file system operations)
///
/// @param file_system A user-defined FileSystem implementation, ownership
/// remains with the caller.
///
virtual void set_file_system(FileSystem* file_system) = 0;
///
/// Get the File System
///
virtual FileSystem* file_system() const = 0;
};
///
/// The default GPU driver is an OpenGL driver that paints each View to an
/// offscreen bitmap (@see View::bitmap). This is lazily-initialized.
///
UExport GPUDriver* DefaultGPUDriver();
///
/// The default Font Loader uses the native font loader API for the platform.
///
/// @note Windows and macOS font loading is implemented but Linux is still in
/// progress-- currently just loads an embedded Roboto font.
///
UExport FontLoader* DefaultFontLoader();
} // namespace ultralight

76
main.go Normal file
View File

@ -0,0 +1,76 @@
//go:generate fileb0x b0x.yml
package main
import (
"fmt"
"runtime"
. "test/ultralight"
"unsafe"
"test/fileserver"
)
func jsHandle(
ctx JSContextRef,
function JSObjectRef,
thisObject JSObjectRef,
argumentCount uint,
arguments []JSValueRef,
exception []JSValueRef) JSValueRef {
fmt.Println("Hello, World!")
return JSValueMakeString(ctx, JSStringCreateWithUTF8CString(runtime.GOOS))
}
func main() {
cfg := UlCreateConfig()
app := UlCreateApp(cfg)
mm := UlAppGetMainMonitor(app)
wnd := UlCreateWindow(mm, 500, 500, false, 2|4)
UlWindowSetTitle(wnd, "Hello, World!")
UlAppSetWindow(app, wnd)
ov := UlCreateOverlay(wnd, 500, 500, 0, 0)
UlWindowSetResizeCallback(wnd, resizeCallback, unsafe.Pointer(&ov))
view := UlOverlayGetView(ov)
addr, err := fileserver.Serve()
if err != nil {
panic(err)
}
fmt.Println(addr)
url := UlCreateString(addr)
defer UlDestroyString(url)
addFunctionToView(view, "getOS", jsHandle)
UlViewLoadURL(view, url)
UlAppRun(app)
}
func addFunctionToView(view ULView, name string, callback JSObjectCallAsFunctionCallback) {
ctx := UlViewGetJSContext(view)
gobj := JSContextGetGlobalObject(ctx)
fn := JSStringCreateWithUTF8CString(name)
defer JSStringRelease(fn)
fob := JSObjectMakeFunctionWithCallback(ctx, fn, callback)
val := *(*JSValueRef)(unsafe.Pointer(&fob))
JSObjectSetProperty(ctx, gobj, fn, val, KJSPropertyAttributeNone, []JSValueRef{})
}
func resizeCallback(user_data unsafe.Pointer, width uint32, height uint32) {
overlay := *(*ULOverlay)(user_data)
UlOverlayResize(overlay, width, height)
}

23
public/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

68
public/README.md Normal file
View File

@ -0,0 +1,68 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.<br>
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br>
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.<br>
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.<br>
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br>
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `npm run build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify

31
public/package.json Normal file
View File

@ -0,0 +1,31 @@
{
"name": "public",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-scripts": "3.1.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

BIN
public/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

43
public/public/index.html Normal file
View File

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

BIN
public/public/logo192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

BIN
public/public/logo512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

View File

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

2
public/public/robots.txt Normal file
View File

@ -0,0 +1,2 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *

22
public/src/App.css Normal file
View File

@ -0,0 +1,22 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #09d3ac;
}

28
public/src/App.js Normal file
View File

@ -0,0 +1,28 @@
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
/*eslint-disable no-undef*/
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
ts
{/* {getOS()} */}
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;

9
public/src/App.test.js Normal file
View File

@ -0,0 +1,9 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});

13
public/src/index.css Normal file
View File

@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
monospace;
}

12
public/src/index.js Normal file
View File

@ -0,0 +1,12 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

1
public/src/logo.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.0 KiB

135
public/src/serviceWorker.js Normal file
View File

@ -0,0 +1,135 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}

10076
public/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

54
ultralight.yml Normal file
View File

@ -0,0 +1,54 @@
GENERATOR:
PackageName: ultralight
PackageDescription: "Ultralight bindings for golang"
PackageLicense: "THE AUTOGENERATED LICENSE. ALL THE RIGHTS ARE RESERVED BY ROBOTS."
FlagGroups:
- {name: CFLAGS, flags: [-I../include]}
- {name: LDFLAGS, flags: [-L -lUltralightCore -lWebCore -lUltralight -lAppCore]}
Includes: ["AppCore/CAPI.h"]
Options:
SafeStrings: true
PARSER:
Arch: x86_64
IncludePaths:
- include
- /usr/include
- /usr/lib/gcc/x86_64-linux-gnu/7/include
SourcesPaths:
- AppCore/CAPI.h
TRANSLATOR:
ConstRules:
defines: eval
Rules:
global:
- {action: accept, from: "^ul"}
- {action: accept, from: "^UL"}
- {action: accept, from: "^JS"}
- {action: accept, from: "^k"}
- {action: accept, from: "^B"}
- {action: ignore, from: __size_t__}
- {action: ignore, from: __SIZE_T__}
- {action: ignore, from: _BSD_SIZE_T_DEFINED_}
- {action: ignore, from: _SIZE_T_DECLARED}
- {action: ignore, from: __wchar_t__}
- {action: ignore, from: __WCHAR_T__}
- {transform: export}
function:
- {action: ignore, from: __GO__}
- {action: ignore, from: JSObjectGetArrayBufferByteLength}
- {action: ignore, from: JSObjectGetArrayBufferBytesPtr}
- {action: ignore, from: JSObjectGetTypedArrayBuffer}
- {action: ignore, from: JSObjectGetTypedArrayByteLength}
- {action: ignore, from: JSObjectGetTypedArrayByteOffset}
- {action: ignore, from: JSObjectGetTypedArrayBytesPtr}
- {action: ignore, from: JSObjectGetTypedArrayLength}
- {action: ignore, from: JSObjectMakeArrayBufferWithBytesNoCopy}
- {action: ignore, from: JSObjectMakeTypedArray}
- {action: ignore, from: JSObjectMakeTypedArrayWithArrayBuffer}
- {action: ignore, from: JSObjectMakeTypedArrayWithArrayBufferAndOffset}
- {action: ignore, from: JSObjectMakeTypedArrayWithBytesNoCopy}
- {action: ignore, from: JSValueGetTypedArrayType}
private:
- {transform: unexport}

104
ultralight/cgo_helpers.c Normal file
View File

@ -0,0 +1,104 @@
// THE AUTOGENERATED LICENSE. ALL THE RIGHTS ARE RESERVED BY ROBOTS.
// WARNING: This file has automatically been generated on Thu, 26 Sep 2019 10:38:04 CDT.
// Code generated by https://git.io/c-for-go. DO NOT EDIT.
#include "_cgo_export.h"
#include "cgo_helpers.h"
void ULUpdateCallback_7e1c6355(void* user_data) {
uLUpdateCallback7E1C6355(user_data);
}
void ULCloseCallback_195b2f9(void* user_data) {
uLCloseCallback195B2F9(user_data);
}
void ULResizeCallback_6e7309d9(void* user_data, unsigned int width, unsigned int height) {
uLResizeCallback6E7309D9(user_data, width, height);
}
void ULChangeTitleCallback_bd58034c(void* user_data, ULView caller, ULString title) {
uLChangeTitleCallbackBD58034C(user_data, caller, title);
}
void ULChangeURLCallback_4ec32b80(void* user_data, ULView caller, ULString url) {
uLChangeURLCallback4EC32B80(user_data, caller, url);
}
void ULChangeTooltipCallback_12ca407(void* user_data, ULView caller, ULString tooltip) {
uLChangeTooltipCallback12CA407(user_data, caller, tooltip);
}
void ULChangeCursorCallback_1a7011df(void* user_data, ULView caller, ULCursor cursor) {
uLChangeCursorCallback1A7011DF(user_data, caller, cursor);
}
void ULAddConsoleMessageCallback_44b8dd01(void* user_data, ULView caller, ULMessageSource source, ULMessageLevel level, ULString message, unsigned int line_number, unsigned int column_number, ULString source_id) {
uLAddConsoleMessageCallback44B8DD01(user_data, caller, source, level, message, line_number, column_number, source_id);
}
void ULBeginLoadingCallback_70d8c0ad(void* user_data, ULView caller) {
uLBeginLoadingCallback70D8C0AD(user_data, caller);
}
void ULFinishLoadingCallback_1ed4ecae(void* user_data, ULView caller) {
uLFinishLoadingCallback1ED4ECAE(user_data, caller);
}
void ULUpdateHistoryCallback_6e105364(void* user_data, ULView caller) {
uLUpdateHistoryCallback6E105364(user_data, caller);
}
void ULDOMReadyCallback_6432c207(void* user_data, ULView caller) {
uLDOMReadyCallback6432C207(user_data, caller);
}
void JSTypedArrayBytesDeallocator_68d51f83(void* bytes, void* deallocatorContext) {
jSTypedArrayBytesDeallocator68D51F83(bytes, deallocatorContext);
}
void JSObjectInitializeCallback_5793b16(JSContextRef ctx, JSObjectRef object) {
jSObjectInitializeCallback5793B16(ctx, object);
}
void JSObjectFinalizeCallback_93da0aea(JSObjectRef object) {
jSObjectFinalizeCallback93DA0AEA(object);
}
_Bool JSObjectHasPropertyCallback_340bfa95(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName) {
return jSObjectHasPropertyCallback340BFA95(ctx, object, propertyName);
}
JSValueRef JSObjectGetPropertyCallback_5caec716(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) {
return jSObjectGetPropertyCallback5CAEC716(ctx, object, propertyName, exception);
}
_Bool JSObjectSetPropertyCallback_a684f1fe(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) {
return jSObjectSetPropertyCallbackA684F1FE(ctx, object, propertyName, value, exception);
}
_Bool JSObjectDeletePropertyCallback_b0108ebe(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) {
return jSObjectDeletePropertyCallbackB0108EBE(ctx, object, propertyName, exception);
}
void JSObjectGetPropertyNamesCallback_e77d2329(JSContextRef ctx, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames) {
jSObjectGetPropertyNamesCallbackE77D2329(ctx, object, propertyNames);
}
JSValueRef JSObjectCallAsFunctionCallback_89f9469b(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, unsigned long int argumentCount, JSValueRef* arguments, JSValueRef* exception) {
return jSObjectCallAsFunctionCallback89F9469B(ctx, function, thisObject, argumentCount, arguments, exception);
}
JSObjectRef JSObjectCallAsConstructorCallback_45f4b71f(JSContextRef ctx, JSObjectRef constructor, unsigned long int argumentCount, JSValueRef* arguments, JSValueRef* exception) {
return jSObjectCallAsConstructorCallback45F4B71F(ctx, constructor, argumentCount, arguments, exception);
}
_Bool JSObjectHasInstanceCallback_aa527d2e(JSContextRef ctx, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception) {
return jSObjectHasInstanceCallbackAA527D2E(ctx, constructor, possibleInstance, exception);
}
JSValueRef JSObjectConvertToTypeCallback_d379d61c(JSContextRef ctx, JSObjectRef object, JSType _type, JSValueRef* exception) {
return jSObjectConvertToTypeCallbackD379D61C(ctx, object, _type, exception);
}

1556
ultralight/cgo_helpers.go Normal file

File diff suppressed because it is too large Load Diff

83
ultralight/cgo_helpers.h Normal file
View File

@ -0,0 +1,83 @@
// THE AUTOGENERATED LICENSE. ALL THE RIGHTS ARE RESERVED BY ROBOTS.
// WARNING: This file has automatically been generated on Thu, 26 Sep 2019 10:38:04 CDT.
// Code generated by https://git.io/c-for-go. DO NOT EDIT.
#include "AppCore/CAPI.h"
#include <stdlib.h>
#pragma once
#define __CGOGEN 1
// ULUpdateCallback_7e1c6355 is a proxy for callback ULUpdateCallback.
void ULUpdateCallback_7e1c6355(void* user_data);
// ULCloseCallback_195b2f9 is a proxy for callback ULCloseCallback.
void ULCloseCallback_195b2f9(void* user_data);
// ULResizeCallback_6e7309d9 is a proxy for callback ULResizeCallback.
void ULResizeCallback_6e7309d9(void* user_data, unsigned int width, unsigned int height);
// ULChangeTitleCallback_bd58034c is a proxy for callback ULChangeTitleCallback.
void ULChangeTitleCallback_bd58034c(void* user_data, ULView caller, ULString title);
// ULChangeURLCallback_4ec32b80 is a proxy for callback ULChangeURLCallback.
void ULChangeURLCallback_4ec32b80(void* user_data, ULView caller, ULString url);
// ULChangeTooltipCallback_12ca407 is a proxy for callback ULChangeTooltipCallback.
void ULChangeTooltipCallback_12ca407(void* user_data, ULView caller, ULString tooltip);
// ULChangeCursorCallback_1a7011df is a proxy for callback ULChangeCursorCallback.
void ULChangeCursorCallback_1a7011df(void* user_data, ULView caller, ULCursor cursor);
// ULAddConsoleMessageCallback_44b8dd01 is a proxy for callback ULAddConsoleMessageCallback.
void ULAddConsoleMessageCallback_44b8dd01(void* user_data, ULView caller, ULMessageSource source, ULMessageLevel level, ULString message, unsigned int line_number, unsigned int column_number, ULString source_id);
// ULBeginLoadingCallback_70d8c0ad is a proxy for callback ULBeginLoadingCallback.
void ULBeginLoadingCallback_70d8c0ad(void* user_data, ULView caller);
// ULFinishLoadingCallback_1ed4ecae is a proxy for callback ULFinishLoadingCallback.
void ULFinishLoadingCallback_1ed4ecae(void* user_data, ULView caller);
// ULUpdateHistoryCallback_6e105364 is a proxy for callback ULUpdateHistoryCallback.
void ULUpdateHistoryCallback_6e105364(void* user_data, ULView caller);
// ULDOMReadyCallback_6432c207 is a proxy for callback ULDOMReadyCallback.
void ULDOMReadyCallback_6432c207(void* user_data, ULView caller);
// JSTypedArrayBytesDeallocator_68d51f83 is a proxy for callback JSTypedArrayBytesDeallocator.
void JSTypedArrayBytesDeallocator_68d51f83(void* bytes, void* deallocatorContext);
// JSObjectInitializeCallback_5793b16 is a proxy for callback JSObjectInitializeCallback.
void JSObjectInitializeCallback_5793b16(JSContextRef ctx, JSObjectRef object);
// JSObjectFinalizeCallback_93da0aea is a proxy for callback JSObjectFinalizeCallback.
void JSObjectFinalizeCallback_93da0aea(JSObjectRef object);
// JSObjectHasPropertyCallback_340bfa95 is a proxy for callback JSObjectHasPropertyCallback.
_Bool JSObjectHasPropertyCallback_340bfa95(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
// JSObjectGetPropertyCallback_5caec716 is a proxy for callback JSObjectGetPropertyCallback.
JSValueRef JSObjectGetPropertyCallback_5caec716(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
// JSObjectSetPropertyCallback_a684f1fe is a proxy for callback JSObjectSetPropertyCallback.
_Bool JSObjectSetPropertyCallback_a684f1fe(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception);
// JSObjectDeletePropertyCallback_b0108ebe is a proxy for callback JSObjectDeletePropertyCallback.
_Bool JSObjectDeletePropertyCallback_b0108ebe(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
// JSObjectGetPropertyNamesCallback_e77d2329 is a proxy for callback JSObjectGetPropertyNamesCallback.
void JSObjectGetPropertyNamesCallback_e77d2329(JSContextRef ctx, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames);
// JSObjectCallAsFunctionCallback_89f9469b is a proxy for callback JSObjectCallAsFunctionCallback.
JSValueRef JSObjectCallAsFunctionCallback_89f9469b(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, unsigned long int argumentCount, JSValueRef* arguments, JSValueRef* exception);
// JSObjectCallAsConstructorCallback_45f4b71f is a proxy for callback JSObjectCallAsConstructorCallback.
JSObjectRef JSObjectCallAsConstructorCallback_45f4b71f(JSContextRef ctx, JSObjectRef constructor, unsigned long int argumentCount, JSValueRef* arguments, JSValueRef* exception);
// JSObjectHasInstanceCallback_aa527d2e is a proxy for callback JSObjectHasInstanceCallback.
_Bool JSObjectHasInstanceCallback_aa527d2e(JSContextRef ctx, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception);
// JSObjectConvertToTypeCallback_d379d61c is a proxy for callback JSObjectConvertToTypeCallback.
JSValueRef JSObjectConvertToTypeCallback_d379d61c(JSContextRef ctx, JSObjectRef object, JSType _type, JSValueRef* exception);

211
ultralight/const.go Normal file
View File

@ -0,0 +1,211 @@
// THE AUTOGENERATED LICENSE. ALL THE RIGHTS ARE RESERVED BY ROBOTS.
// WARNING: This file has automatically been generated on Thu, 26 Sep 2019 10:38:04 CDT.
// Code generated by https://git.io/c-for-go. DO NOT EDIT.
package ultralight
/*
#cgo CFLAGS: -I../include
#cgo LDFLAGS: -L -lUltralightCore -lWebCore -lUltralight -lAppCore
#include "AppCore/CAPI.h"
#include <stdlib.h>
#include "cgo_helpers.h"
*/
import "C"
const (
// JSC_OBJC_API_ENABLED as defined in JavaScriptCore/JSBase.h:141
JSC_OBJC_API_ENABLED = 0
)
// ULWindowFlags as declared in AppCore/CAPI.h:46
type ULWindowFlags int32
// ULWindowFlags enumeration from AppCore/CAPI.h:46
const (
KWindowFlags_Borderless ULWindowFlags = 1
KWindowFlags_Titled ULWindowFlags = 2
KWindowFlags_Resizable ULWindowFlags = 4
KWindowFlags_Maximizable ULWindowFlags = 8
)
// ULMessageSource as declared in Ultralight/CAPI.h:73
type ULMessageSource int32
// ULMessageSource enumeration from Ultralight/CAPI.h:73
const (
KMessageSource_XML ULMessageSource = iota
KMessageSource_JS ULMessageSource = 1
KMessageSource_Network ULMessageSource = 2
KMessageSource_ConsoleAPI ULMessageSource = 3
KMessageSource_Storage ULMessageSource = 4
KMessageSource_AppCache ULMessageSource = 5
KMessageSource_Rendering ULMessageSource = 6
KMessageSource_CSS ULMessageSource = 7
KMessageSource_Security ULMessageSource = 8
KMessageSource_ContentBlocker ULMessageSource = 9
KMessageSource_Other ULMessageSource = 10
)
// ULMessageLevel as declared in Ultralight/CAPI.h:81
type ULMessageLevel int32
// ULMessageLevel enumeration from Ultralight/CAPI.h:81
const (
KMessageLevel_Log ULMessageLevel = 1
KMessageLevel_Warning ULMessageLevel = 2
KMessageLevel_Error ULMessageLevel = 3
KMessageLevel_Debug ULMessageLevel = 4
KMessageLevel_Info ULMessageLevel = 5
)
// ULCursor as declared in Ultralight/CAPI.h:128
type ULCursor int32
// ULCursor enumeration from Ultralight/CAPI.h:128
const (
KCursor_Pointer ULCursor = iota
KCursor_Cross ULCursor = 1
KCursor_Hand ULCursor = 2
KCursor_IBeam ULCursor = 3
KCursor_Wait ULCursor = 4
KCursor_Help ULCursor = 5
KCursor_EastResize ULCursor = 6
KCursor_NorthResize ULCursor = 7
KCursor_NorthEastResize ULCursor = 8
KCursor_NorthWestResize ULCursor = 9
KCursor_SouthResize ULCursor = 10
KCursor_SouthEastResize ULCursor = 11
KCursor_SouthWestResize ULCursor = 12
KCursor_WestResize ULCursor = 13
KCursor_NorthSouthResize ULCursor = 14
KCursor_EastWestResize ULCursor = 15
KCursor_NorthEastSouthWestResize ULCursor = 16
KCursor_NorthWestSouthEastResize ULCursor = 17
KCursor_ColumnResize ULCursor = 18
KCursor_RowResize ULCursor = 19
KCursor_MiddlePanning ULCursor = 20
KCursor_EastPanning ULCursor = 21
KCursor_NorthPanning ULCursor = 22
KCursor_NorthEastPanning ULCursor = 23
KCursor_NorthWestPanning ULCursor = 24
KCursor_SouthPanning ULCursor = 25
KCursor_SouthEastPanning ULCursor = 26
KCursor_SouthWestPanning ULCursor = 27
KCursor_WestPanning ULCursor = 28
KCursor_Move ULCursor = 29
KCursor_VerticalText ULCursor = 30
KCursor_Cell ULCursor = 31
KCursor_ContextMenu ULCursor = 32
KCursor_Alias ULCursor = 33
KCursor_Progress ULCursor = 34
KCursor_NoDrop ULCursor = 35
KCursor_Copy ULCursor = 36
KCursor_None ULCursor = 37
KCursor_NotAllowed ULCursor = 38
KCursor_ZoomIn ULCursor = 39
KCursor_ZoomOut ULCursor = 40
KCursor_Grab ULCursor = 41
KCursor_Grabbing ULCursor = 42
KCursor_Custom ULCursor = 43
)
// ULBitmapFormat as declared in Ultralight/CAPI.h:133
type ULBitmapFormat int32
// ULBitmapFormat enumeration from Ultralight/CAPI.h:133
const (
KBitmapFormat_A8 ULBitmapFormat = iota
KBitmapFormat_RGBA8 ULBitmapFormat = 1
)
// ULKeyEventType as declared in Ultralight/CAPI.h:140
type ULKeyEventType int32
// ULKeyEventType enumeration from Ultralight/CAPI.h:140
const (
KKeyEventType_KeyDown ULKeyEventType = iota
KKeyEventType_KeyUp ULKeyEventType = 1
KKeyEventType_RawKeyDown ULKeyEventType = 2
KKeyEventType_Char ULKeyEventType = 3
)
// ULMouseEventType as declared in Ultralight/CAPI.h:146
type ULMouseEventType int32
// ULMouseEventType enumeration from Ultralight/CAPI.h:146
const (
KMouseEventType_MouseMoved ULMouseEventType = iota
KMouseEventType_MouseDown ULMouseEventType = 1
KMouseEventType_MouseUp ULMouseEventType = 2
)
// ULMouseButton as declared in Ultralight/CAPI.h:153
type ULMouseButton int32
// ULMouseButton enumeration from Ultralight/CAPI.h:153
const (
KMouseButton_None ULMouseButton = iota
KMouseButton_Left ULMouseButton = 1
KMouseButton_Middle ULMouseButton = 2
KMouseButton_Right ULMouseButton = 3
)
// ULScrollEventType as declared in Ultralight/CAPI.h:158
type ULScrollEventType int32
// ULScrollEventType enumeration from Ultralight/CAPI.h:158
const (
KScrollEventType_ScrollByPixel ULScrollEventType = iota
KScrollEventType_ScrollByPage ULScrollEventType = 1
)
// JSType as declared in JavaScriptCore/JSValueRef.h:53
type JSType int32
// JSType enumeration from JavaScriptCore/JSValueRef.h:53
const (
KJSTypeUndefined JSType = iota
KJSTypeNull JSType = 1
KJSTypeBoolean JSType = 2
KJSTypeNumber JSType = 3
KJSTypeString JSType = 4
KJSTypeObject JSType = 5
)
// JSTypedArrayType as declared in JavaScriptCore/JSValueRef.h:83
type JSTypedArrayType int32
// JSTypedArrayType enumeration from JavaScriptCore/JSValueRef.h:83
const (
KJSTypedArrayTypeInt8Array JSTypedArrayType = iota
KJSTypedArrayTypeInt16Array JSTypedArrayType = 1
KJSTypedArrayTypeInt32Array JSTypedArrayType = 2
KJSTypedArrayTypeUint8Array JSTypedArrayType = 3
KJSTypedArrayTypeUint8ClampedArray JSTypedArrayType = 4
KJSTypedArrayTypeUint16Array JSTypedArrayType = 5
KJSTypedArrayTypeUint32Array JSTypedArrayType = 6
KJSTypedArrayTypeFloat32Array JSTypedArrayType = 7
KJSTypedArrayTypeFloat64Array JSTypedArrayType = 8
KJSTypedArrayTypeArrayBuffer JSTypedArrayType = 9
KJSTypedArrayTypeNone JSTypedArrayType = 10
)
const (
// KJSPropertyAttributeNone as declared in JavaScriptCore/JSObjectRef.h:51
KJSPropertyAttributeNone = iota
// KJSPropertyAttributeReadOnly as declared in JavaScriptCore/JSObjectRef.h:52
KJSPropertyAttributeReadOnly = 2
// KJSPropertyAttributeDontEnum as declared in JavaScriptCore/JSObjectRef.h:53
KJSPropertyAttributeDontEnum = 4
// KJSPropertyAttributeDontDelete as declared in JavaScriptCore/JSObjectRef.h:54
KJSPropertyAttributeDontDelete = 8
)
const (
// KJSClassAttributeNone as declared in JavaScriptCore/JSObjectRef.h:69
KJSClassAttributeNone = iota
// KJSClassAttributeNoAutomaticPrototype as declared in JavaScriptCore/JSObjectRef.h:70
KJSClassAttributeNoAutomaticPrototype = 2
)

9
ultralight/doc.go Normal file
View File

@ -0,0 +1,9 @@
// THE AUTOGENERATED LICENSE. ALL THE RIGHTS ARE RESERVED BY ROBOTS.
// WARNING: This file has automatically been generated on Thu, 26 Sep 2019 10:38:04 CDT.
// Code generated by https://git.io/c-for-go. DO NOT EDIT.
/*
Ultralight bindings for golang
*/
package ultralight

211
ultralight/types.go Normal file
View File

@ -0,0 +1,211 @@
// THE AUTOGENERATED LICENSE. ALL THE RIGHTS ARE RESERVED BY ROBOTS.
// WARNING: This file has automatically been generated on Thu, 26 Sep 2019 10:38:04 CDT.
// Code generated by https://git.io/c-for-go. DO NOT EDIT.
package ultralight
/*
#cgo CFLAGS: -I../include
#cgo LDFLAGS: -L -lUltralightCore -lWebCore -lUltralight -lAppCore
#include "AppCore/CAPI.h"
#include <stdlib.h>
#include "cgo_helpers.h"
*/
import "C"
import "unsafe"
// ULApp as declared in AppCore/CAPI.h:33
type ULApp C.ULApp
// ULWindow as declared in AppCore/CAPI.h:34
type ULWindow C.ULWindow
// ULMonitor as declared in AppCore/CAPI.h:35
type ULMonitor C.ULMonitor
// ULOverlay as declared in AppCore/CAPI.h:36
type ULOverlay C.ULOverlay
// ULUpdateCallback type as declared in AppCore/CAPI.h:81
type ULUpdateCallback func(user_data unsafe.Pointer)
// ULCloseCallback type as declared in AppCore/CAPI.h:160
type ULCloseCallback func(user_data unsafe.Pointer)
// ULResizeCallback type as declared in AppCore/CAPI.h:170
type ULResizeCallback func(user_data unsafe.Pointer, width uint32, height uint32)
// ULChar16 type as declared in Ultralight/CAPI.h:43
type ULChar16 uint16
// ULConfig as declared in Ultralight/CAPI.h:50
type ULConfig C.ULConfig
// ULRenderer as declared in Ultralight/CAPI.h:51
type ULRenderer C.ULRenderer
// ULView as declared in Ultralight/CAPI.h:52
type ULView C.ULView
// ULBitmap as declared in Ultralight/CAPI.h:53
type ULBitmap C.ULBitmap
// ULString as declared in Ultralight/CAPI.h:54
type ULString C.ULString
// ULBuffer as declared in Ultralight/CAPI.h:55
type ULBuffer C.ULBuffer
// ULRenderTarget as declared in Ultralight/CAPI.h:56
type ULRenderTarget C.ULRenderTarget
// ULKeyEvent as declared in Ultralight/CAPI.h:57
type ULKeyEvent C.ULKeyEvent
// ULMouseEvent as declared in Ultralight/CAPI.h:58
type ULMouseEvent C.ULMouseEvent
// ULScrollEvent as declared in Ultralight/CAPI.h:59
type ULScrollEvent C.ULScrollEvent
// ULChangeTitleCallback type as declared in Ultralight/CAPI.h:385
type ULChangeTitleCallback func(user_data unsafe.Pointer, caller ULView, title ULString)
// ULChangeURLCallback type as declared in Ultralight/CAPI.h:395
type ULChangeURLCallback func(user_data unsafe.Pointer, caller ULView, url ULString)
// ULChangeTooltipCallback type as declared in Ultralight/CAPI.h:405
type ULChangeTooltipCallback func(user_data unsafe.Pointer, caller ULView, tooltip ULString)
// ULChangeCursorCallback type as declared in Ultralight/CAPI.h:415
type ULChangeCursorCallback func(user_data unsafe.Pointer, caller ULView, cursor ULCursor)
// ULAddConsoleMessageCallback type as declared in Ultralight/CAPI.h:425
type ULAddConsoleMessageCallback func(user_data unsafe.Pointer, caller ULView, source ULMessageSource, level ULMessageLevel, message ULString, line_number uint32, column_number uint32, source_id ULString)
// ULBeginLoadingCallback type as declared in Ultralight/CAPI.h:440
type ULBeginLoadingCallback func(user_data unsafe.Pointer, caller ULView)
// ULFinishLoadingCallback type as declared in Ultralight/CAPI.h:450
type ULFinishLoadingCallback func(user_data unsafe.Pointer, caller ULView)
// ULUpdateHistoryCallback type as declared in Ultralight/CAPI.h:460
type ULUpdateHistoryCallback func(user_data unsafe.Pointer, caller ULView)
// ULDOMReadyCallback type as declared in Ultralight/CAPI.h:470
type ULDOMReadyCallback func(user_data unsafe.Pointer, caller ULView)
// JSContextGroupRef as declared in JavaScriptCore/JSBase.h:40
type JSContextGroupRef C.JSContextGroupRef
// JSContextRef as declared in JavaScriptCore/JSBase.h:43
type JSContextRef C.JSContextRef
// JSGlobalContextRef as declared in JavaScriptCore/JSBase.h:46
type JSGlobalContextRef C.JSGlobalContextRef
// JSStringRef as declared in JavaScriptCore/JSBase.h:49
type JSStringRef C.JSStringRef
// JSClassRef as declared in JavaScriptCore/JSBase.h:52
type JSClassRef C.JSClassRef
// JSPropertyNameArrayRef as declared in JavaScriptCore/JSBase.h:55
type JSPropertyNameArrayRef C.JSPropertyNameArrayRef
// JSPropertyNameAccumulatorRef as declared in JavaScriptCore/JSBase.h:58
type JSPropertyNameAccumulatorRef C.JSPropertyNameAccumulatorRef
// JSTypedArrayBytesDeallocator type as declared in JavaScriptCore/JSBase.h:61
type JSTypedArrayBytesDeallocator func(bytes unsafe.Pointer, deallocatorContext unsafe.Pointer)
// JSValueRef as declared in JavaScriptCore/JSBase.h:66
type JSValueRef C.JSValueRef
// JSObjectRef as declared in JavaScriptCore/JSBase.h:69
type JSObjectRef C.JSObjectRef
// JSPropertyAttributes type as declared in JavaScriptCore/JSObjectRef.h:61
type JSPropertyAttributes uint32
// JSClassAttributes type as declared in JavaScriptCore/JSObjectRef.h:77
type JSClassAttributes uint32
// JSObjectInitializeCallback type as declared in JavaScriptCore/JSObjectRef.h:92
type JSObjectInitializeCallback func(ctx JSContextRef, object JSObjectRef)
// JSObjectFinalizeCallback type as declared in JavaScriptCore/JSObjectRef.h:110
type JSObjectFinalizeCallback func(object JSObjectRef)
// JSObjectHasPropertyCallback type as declared in JavaScriptCore/JSObjectRef.h:130
type JSObjectHasPropertyCallback func(ctx JSContextRef, object JSObjectRef, propertyName JSStringRef) bool
// JSObjectGetPropertyCallback type as declared in JavaScriptCore/JSObjectRef.h:147
type JSObjectGetPropertyCallback func(ctx JSContextRef, object JSObjectRef, propertyName JSStringRef, exception []JSValueRef) JSValueRef
// JSObjectSetPropertyCallback type as declared in JavaScriptCore/JSObjectRef.h:165
type JSObjectSetPropertyCallback func(ctx JSContextRef, object JSObjectRef, propertyName JSStringRef, value JSValueRef, exception []JSValueRef) bool
// JSObjectDeletePropertyCallback type as declared in JavaScriptCore/JSObjectRef.h:182
type JSObjectDeletePropertyCallback func(ctx JSContextRef, object JSObjectRef, propertyName JSStringRef, exception []JSValueRef) bool
// JSObjectGetPropertyNamesCallback type as declared in JavaScriptCore/JSObjectRef.h:199
type JSObjectGetPropertyNamesCallback func(ctx JSContextRef, object JSObjectRef, propertyNames JSPropertyNameAccumulatorRef)
// JSObjectCallAsFunctionCallback type as declared in JavaScriptCore/JSObjectRef.h:220
type JSObjectCallAsFunctionCallback func(ctx JSContextRef, function JSObjectRef, thisObject JSObjectRef, argumentCount uint, arguments []JSValueRef, exception []JSValueRef) JSValueRef
// JSObjectCallAsConstructorCallback type as declared in JavaScriptCore/JSObjectRef.h:240
type JSObjectCallAsConstructorCallback func(ctx JSContextRef, constructor JSObjectRef, argumentCount uint, arguments []JSValueRef, exception []JSValueRef) JSObjectRef
// JSObjectHasInstanceCallback type as declared in JavaScriptCore/JSObjectRef.h:261
type JSObjectHasInstanceCallback func(ctx JSContextRef, constructor JSObjectRef, possibleInstance JSValueRef, exception []JSValueRef) bool
// JSObjectConvertToTypeCallback type as declared in JavaScriptCore/JSObjectRef.h:280
type JSObjectConvertToTypeCallback func(ctx JSContextRef, object JSObjectRef, _type JSType, exception []JSValueRef) JSValueRef
// JSStaticValue as declared in JavaScriptCore/JSObjectRef.h:295
type JSStaticValue struct {
Name string
GetProperty JSObjectGetPropertyCallback
SetProperty JSObjectSetPropertyCallback
Attributes JSPropertyAttributes
ref34655956 *C.JSStaticValue
allocs34655956 interface{}
}
// JSStaticFunction as declared in JavaScriptCore/JSObjectRef.h:308
type JSStaticFunction struct {
Name string
CallAsFunction JSObjectCallAsFunctionCallback
Attributes JSPropertyAttributes
ref6b5f4953 *C.JSStaticFunction
allocs6b5f4953 interface{}
}
// JSClassDefinition as declared in JavaScriptCore/JSObjectRef.h:364
type JSClassDefinition struct {
Version int32
Attributes JSClassAttributes
ClassName string
ParentClass JSClassRef
StaticValues []JSStaticValue
StaticFunctions []JSStaticFunction
Initialize JSObjectInitializeCallback
Finalize JSObjectFinalizeCallback
HasProperty JSObjectHasPropertyCallback
GetProperty JSObjectGetPropertyCallback
SetProperty JSObjectSetPropertyCallback
DeleteProperty JSObjectDeletePropertyCallback
GetPropertyNames JSObjectGetPropertyNamesCallback
CallAsFunction JSObjectCallAsFunctionCallback
CallAsConstructor JSObjectCallAsConstructorCallback
HasInstance JSObjectHasInstanceCallback
ConvertToType JSObjectConvertToTypeCallback
ref192c18d5 *C.JSClassDefinition
allocs192c18d5 interface{}
}
// JSChar type as declared in JavaScriptCore/JSStringRef.h:49
type JSChar uint16

1709
ultralight/ultralight.go Normal file

File diff suppressed because it is too large Load Diff