diff --git a/.circleci/config.yml b/.circleci/config.yml index 7c0598c6b1e8d..85828b6d51edd 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -141,6 +141,20 @@ jobs: - .config/X11/xorg.conf - .config/openbox/autostart - .config/autostart/at-spi-dbus-bus.desktop + build-docs: + <<: *defaults + steps: + - checkout + - run: + name: install pip + command: | + apt-get update -q + apt-get install -q -y python-pip + - run: + name: install sphinx + command: | + pip install sphinx==1.7.8 + - run: make -C site html flake8: <<: *defaults steps: @@ -282,6 +296,7 @@ workflows: build-test: jobs: - flake8 + - build-docs - build - test-other: requires: diff --git a/site/Makefile b/site/Makefile index b23262afff318..7e8fe45a63ce4 100644 --- a/site/Makefile +++ b/site/Makefile @@ -2,7 +2,7 @@ # # You can set these variables from the command line. -SPHINXOPTS = +SPHINXOPTS = -W SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build diff --git a/site/source/conf.py b/site/source/conf.py index 8fe15034c7667..03e2df8474e66 100644 --- a/site/source/conf.py +++ b/site/source/conf.py @@ -389,14 +389,6 @@ # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None} -# HamishW - set highlighting language. -highlight_language = 'cpp' +#highlight_language = 'default' -# HamishW - set domain (cpp) primary_domain = 'cpp' - -# HamishW - tell Breathe about projects. Breathe is tool to convert Doxygen to Python objects, for import into Sphinx. -#breathe_projects = { "myproject": "/home/me/docproj/doxyxml/", "nutshell":"./headers/xml/", } -# HamishW - Specify a default project: -#breathe_default_project = "nutshell" - diff --git a/site/source/docs/api_reference/Filesystem-API.rst b/site/source/docs/api_reference/Filesystem-API.rst index e4e9cd77ef005..752087bad2dbc 100644 --- a/site/source/docs/api_reference/Filesystem-API.rst +++ b/site/source/docs/api_reference/Filesystem-API.rst @@ -6,9 +6,11 @@ File System API File operations in Emscripten are provided by the `FS `_ library. It is used internally for all of Emscripten's **libc** and **libcxx** file I/O. -.. note:: The API is *inspired* by the Linux/POSIX `File System API `_, with each presenting a very similar interface. +.. note:: The API is *inspired* by the Linux/POSIX `File System API `_, with each presenting a very similar interface. - The underlying behaviour is also similar, except where differences between the native and browser environments make this unreasonable. For example, user and group permissions are defined but ignored in :js:func:`FS.open`. + The underlying behaviour is also similar, except where differences between the + native and browser environments make this unreasonable. For example, user and + group permissions are defined but ignored in :js:func:`FS.open`. Emscripten predominantly compiles code that uses synchronous file I/O, so the majority of the ``FS`` member functions offer a synchronous interface (with errors being reported by raising exceptions of type `FS.ErrnoError `_). @@ -16,7 +18,7 @@ File data in Emscripten is partitioned by mounted file systems. Several file sys The automatic tests in `tests/test_core.py `_ (search for ``test_files``) contain many examples of how to use this API. The :ref:`tutorial ` also shows how to pre-load a file so that it can be read from compiled C/C++. -A high level overview of the way File Systems work in Emscripten-ported code is provided in the :ref:`file-system-overview`. +A high level overview of the way File Systems work in Emscripten-ported code is provided in the :ref:`file-system-overview`. Including File System Support ============================= @@ -31,7 +33,7 @@ However, if your C/C++ code doesn't use files, but you want to use them from Jav Persistent data =============== -Applications compiled with Emscripten usually expect synchronous I/O, so Emscripten itself provides file systems with completely synchronous interfaces. +Applications compiled with Emscripten usually expect synchronous I/O, so Emscripten itself provides file systems with completely synchronous interfaces. However, due to JavaScript's event-driven nature, most *persistent* storage options offer only asynchronous interfaces. Emscripten offers :ref:`multiple file systems ` that can be mounted with :js:func:`FS.mount` to help deal with persistence depending on the execution context. @@ -52,7 +54,7 @@ This is the default file system mounted at ``/`` when the runtime is initialized NODEFS ------ -.. note:: This file system is only for use when running inside :term:`node.js`. +.. note:: This file system is only for use when running inside :term:`node.js`. This file system lets a program in *node* map directories (via a mount operation) on the host filesystem to directories in Emscripten's virtual filesystem. It uses node's synchronous `FS API `_ to immediately persist any data written to the Emscripten file system to your local disk. @@ -63,11 +65,11 @@ See `this test `_. + Registers the specified device driver with a set of callbacks. + + :param dev: The specific device driver id, created using :js:func:`makedev`. + :param object ops: The set of callbacks required by the device. For an example, see the `NODEFS default callbacks `_. Setting up standard I/O devices =============================== -Emscripten standard I/O works by going though the virtual ``/dev/stdin``, ``/dev/stdout`` and ``/dev/stderr`` devices. You can set them up using your own I/O functions by calling :js:func:`FS.init`. +Emscripten standard I/O works by going though the virtual ``/dev/stdin``, ``/dev/stdout`` and ``/dev/stderr`` devices. You can set them up using your own I/O functions by calling :js:func:`FS.init`. By default: @@ -121,13 +123,13 @@ By default: .. js:function:: FS.init(input, output, error) - Sets up standard I/O devices for ``stdin``, ``stdout``, and ``stderr``. - - The devices are set up using the following (optional) callbacks. If any of the callbacks throw an exception, it will be caught and handled as if the device malfunctioned. + Sets up standard I/O devices for ``stdin``, ``stdout``, and ``stderr``. - :param input: Input callback. This will be called with no parameters whenever the program attempts to read from ``stdin``. It should return an ASCII character code when data is available, or ``null`` when it isn't. - :param output: Output callback. This will be called with an ASCII character code whenever the program writes to ``stdout``. It may also be called with ``null`` to flush the output. - :param error: Error callback. This is similar to ``output``, except it is called when data is written to ``stderr``. + The devices are set up using the following (optional) callbacks. If any of the callbacks throw an exception, it will be caught and handled as if the device malfunctioned. + + :param input: Input callback. This will be called with no parameters whenever the program attempts to read from ``stdin``. It should return an ASCII character code when data is available, or ``null`` when it isn't. + :param output: Output callback. This will be called with an ASCII character code whenever the program writes to ``stdout``. It may also be called with ``null`` to flush the output. + :param error: Error callback. This is similar to ``output``, except it is called when data is written to ``stderr``. File system API @@ -136,640 +138,628 @@ File system API .. js:function:: FS.mount(type, opts, mountpoint) - Mounts the FS object specified by ``type`` to the directory specified by ``mountpoint``. The ``opts`` object is specific to each file system type. + Mounts the FS object specified by ``type`` to the directory specified by ``mountpoint``. The ``opts`` object is specific to each file system type. + + :param type: The :ref:`file system type `: ``MEMFS``, ``NODEFS``, ``IDBFS`` or ``WORKERFS``. + :param object opts: A generic settings object used by the underlying file system. - :param type: The :ref:`file system type `: ``MEMFS``, ``NODEFS``, ``IDBFS`` or ``WORKERFS``. - :param object opts: A generic settings object used by the underlying file system. - - ``NODFES`` uses the `root` parameter to map the Emscripten directory to the physical directory. For example, to mount the current folder as a NODEFS instance: - - :: - - FS.mkdir('/working'); - FS.mount(NODEFS, { root: '.' }, '/working'); + ``NODFES`` uses the `root` parameter to map the Emscripten directory to the physical directory. For example, to mount the current folder as a NODEFS instance: - ``WORKERFS`` accepts `files` and `blobs` parameters to map a provided flat list of files into the ``mountpoint`` directory: + .. code-block:: javascript - :: + FS.mkdir('/working'); + FS.mount(NODEFS, { root: '.' }, '/working'); - var blob = new Blob(['blob data']); - FS.mkdir('/working'); - FS.mount(WORKERFS, { - blobs: [{ name: 'blob.txt', data: blob }], - files: files, // Array of File objects or FileList - }, '/working'); + ``WORKERFS`` accepts `files` and `blobs` parameters to map a provided flat list of files into the ``mountpoint`` directory: + .. code-block:: javascript - You can also pass in a package of files, created by ``tools/file_packager.py`` with ``--separate-metadata``. You must - provide the metadata as a JSON object, and the data as a blob: + var blob = new Blob(['blob data']); + FS.mkdir('/working'); + FS.mount(WORKERFS, { + blobs: [{ name: 'blob.txt', data: blob }], + files: files, // Array of File objects or FileList + }, '/working'); - :: - // load metadata and blob using XMLHttpRequests, or IndexedDB, or from someplace else - FS.mkdir('/working'); - FS.mount(WORKERFS, { - packages: [{ metadata: meta, blob: blob }] - }, '/working'); + You can also pass in a package of files, created by ``tools/file_packager.py`` with ``--separate-metadata``. You must + provide the metadata as a JSON object, and the data as a blob: + .. code-block:: javascript + + // load metadata and blob using XMLHttpRequests, or IndexedDB, or from someplace else + FS.mkdir('/working'); + FS.mount(WORKERFS, { + packages: [{ metadata: meta, blob: blob }] + }, '/working'); + + + :param string mountpoint: A path to an existing local Emscripten directory where the file system is to be mounted. It can be either an absolute path, or something relative to the current directory. - :param string mountpoint: A path to an existing local Emscripten directory where the file system is to be mounted. It can be either an absolute path, or something relative to the current directory. - .. js:function:: FS.unmount(mountpoint) - Unmounts the specified ``mountpoint``. + Unmounts the specified ``mountpoint``. - :param string mountpoint: The directory to unmount. - + :param string mountpoint: The directory to unmount. .. js:function:: FS.syncfs(populate, callback) - Responsible for iterating and synchronizing all mounted file systems in an asynchronous fashion. - - .. note:: Currently, only the :ref:`filesystem-api-idbfs` file system implements the interfaces needed for synchronization. All other file systems are completely synchronous and don't require synchronization. + Responsible for iterating and synchronizing all mounted file systems in an + asynchronous fashion. + + .. note:: Currently, only the :ref:`filesystem-api-idbfs` file system implements the + interfaces needed for synchronization. All other file systems are completely + synchronous and don't require synchronization. - The ``populate`` flag is used to control the intended direction of the underlying synchronization between Emscripten`s internal data, and the file system's persistent data. + The ``populate`` flag is used to control the intended direction of the + underlying synchronization between Emscripten`s internal data, and the file + system's persistent data. - For example: + For example: - .. code:: javascript + .. code-block:: javascript - function myAppStartup(callback) { - FS.mkdir('/data'); - FS.mount(IDBFS, {}, '/data'); + function myAppStartup(callback) { + FS.mkdir('/data'); + FS.mount(IDBFS, {}, '/data'); - FS.syncfs(true, function (err) { - // handle callback - }); - } + FS.syncfs(true, function (err) { + // handle callback + }); + } - function myAppShutdown(callback) { - FS.syncfs(function (err) { - // handle callback - }); - } + function myAppShutdown(callback) { + FS.syncfs(function (err) { + // handle callback + }); + } - A real example of this functionality can be seen in `test_idbfs_sync.c `_. + A real example of this functionality can be seen in `test_idbfs_sync.c `_. - :param bool populate: ``true`` to initialize Emscripten's file system data with the data from the file system's persistent source, and ``false`` to save Emscripten`s file system data to the file system's persistent source. - :param callback: A notification callback function that is invoked on completion of the synchronization. If an error occurred, it will be provided as a parameter to this function. + :param bool populate: ``true`` to initialize Emscripten's file system data with the data from the file system's persistent source, and ``false`` to save Emscripten`s file system data to the file system's persistent source. + :param callback: A notification callback function that is invoked on completion of the synchronization. If an error occurred, it will be provided as a parameter to this function. .. js:function:: FS.mkdir(path, mode) - Creates a new directory node in the file system. For example: + Creates a new directory node in the file system. For example: - .. code:: javascript + .. code-block:: javascript - FS.mkdir('/data'); - - .. note:: The underlying implementation does not support user or group permissions. The caller is always treated as the owner of the folder, and only permissions relevant to the owner apply. - - :param string path: The path name for the new directory node. - :param int mode: :ref:`File permissions ` for the new node. The default setting (`in octal numeric notation `_) is 0777. + FS.mkdir('/data'); + + .. note:: The underlying implementation does not support user or group permissions. The caller is always treated as the owner of the folder, and only permissions relevant to the owner apply. + + :param string path: The path name for the new directory node. + :param int mode: :ref:`File permissions ` for the new node. The default setting (`in octal numeric notation `_) is 0777. .. js:function:: FS.mkdev(path, mode, dev) - Creates a new device node in the file system referencing the registered device driver (:js:func:`FS.registerDevice`) for ``dev``. For example: + Creates a new device node in the file system referencing the registered device driver (:js:func:`FS.registerDevice`) for ``dev``. For example: - .. code:: javascript + .. code-block:: javascript - var id = FS.makedev(64, 0); - FS.registerDevice(id, {}); - FS.mkdev('/dummy', id); + var id = FS.makedev(64, 0); + FS.registerDevice(id, {}); + FS.mkdev('/dummy', id); - :param string path: The path name for the new device node. - :param int mode: :ref:`File permissions ` for the new node. The default setting (`in octal numeric notation `_) is 0777. - :param int dev: The registered device driver. + :param string path: The path name for the new device node. + :param int mode: :ref:`File permissions ` for the new node. The default setting (`in octal numeric notation `_) is 0777. + :param int dev: The registered device driver. .. js:function:: FS.symlink(oldpath, newpath) - Creates a symlink node at ``newpath`` linking to ``oldpath``. For example: + Creates a symlink node at ``newpath`` linking to ``oldpath``. For example: - .. code:: javascript + .. code-block:: javascript - FS.writeFile('file', 'foobar'); - FS.symlink('file', 'link'); + FS.writeFile('file', 'foobar'); + FS.symlink('file', 'link'); - :param string oldpath: The path name of the file to link to. - :param string newpath: The path to the new symlink node, that points to ``oldpath``. + :param string oldpath: The path name of the file to link to. + :param string newpath: The path to the new symlink node, that points to ``oldpath``. .. js:function:: FS.rename(oldpath, newpath) - Renames the node at ``oldpath`` to ``newpath``. For example: + Renames the node at ``oldpath`` to ``newpath``. For example: - .. code:: javascript + .. code-block:: javascript - FS.writeFile('file', 'foobar'); - FS.rename('file', 'newfile'); + FS.writeFile('file', 'foobar'); + FS.rename('file', 'newfile'); + + :param string oldpath: The old path name. + :param string newpath: The new path name - :param string oldpath: The old path name. - :param string newpath: The new path name - .. js:function:: FS.rmdir(path) - Removes an empty directory located at ``path``. + Removes an empty directory located at ``path``. - Example + Example - .. code:: javascript + .. code-block:: javascript - FS.mkdir('data'); - FS.rmdir('data'); + FS.mkdir('data'); + FS.rmdir('data'); - :param string path: Path of the directory to be removed. + :param string path: Path of the directory to be removed. .. js:function:: FS.unlink(path) - Unlinks the node at ``path``. - - This removes a name from the file system. If that name was the last link to a file (and no processes have the file open) the file is deleted. - - For example: + Unlinks the node at ``path``. + + This removes a name from the file system. If that name was the last link to a file (and no processes have the file open) the file is deleted. - .. code:: javascript + For example: - FS.writeFile('/foobar.txt', 'Hello, world'); - FS.unlink('/foobar.txt'); + .. code-block:: javascript + + FS.writeFile('/foobar.txt', 'Hello, world'); + FS.unlink('/foobar.txt'); + + :param string path: Path of the target node. - :param string path: Path of the target node. - - .. js:function:: FS.readlink(path) - Gets the string value stored in the symbolic link at ``path``. For example: + Gets the string value stored in the symbolic link at ``path``. For example: - .. code:: c + .. code-block:: none - #include - #include + #include + #include - int main() { - MAIN_THREAD_EM_ASM( - FS.writeFile('file', 'foobar'); - FS.symlink('file', 'link'); - console.log(FS.readlink('link')); - ); - return 0; - } + int main() { + MAIN_THREAD_EM_ASM( + FS.writeFile('file', 'foobar'); + FS.symlink('file', 'link'); + console.log(FS.readlink('link')); + ); + return 0; + } - outputs + outputs:: - :: + file - file - - :param string path: Path to the target file. - :returns: The string value stored in the symbolic link at ``path``. - + :param string path: Path to the target file. + :returns: The string value stored in the symbolic link at ``path``. .. js:function:: FS.stat(path) - Gets a JavaScript object containing statistics about the node at ``path``. For example: - - .. code:: c + Gets a JavaScript object containing statistics about the node at ``path``. For example: - #include - #include + .. code-block:: none - int main() { - MAIN_THREAD_EM_ASM( - FS.writeFile('file', 'foobar'); - console.log(FS.stat('file')); - ); - return 0; - } + #include + #include - outputs + int main() { + MAIN_THREAD_EM_ASM( + FS.writeFile('file', 'foobar'); + console.log(FS.stat('file')); + ); + return 0; + } - :: + outputs:: - { - dev: 1, - ino: 13, - mode: 33206, - nlink: 1, - uid: 0, - gid: 0, - rdev: 0, - size: 6, - atime: Mon Nov 25 2013 00:37:27 GMT-0800 (PST), - mtime: Mon Nov 25 2013 00:37:27 GMT-0800 (PST), - ctime: Mon Nov 25 2013 00:37:27 GMT-0800 (PST), - blksize: 4096, - blocks: 1 - } + { + dev: 1, + ino: 13, + mode: 33206, + nlink: 1, + uid: 0, + gid: 0, + rdev: 0, + size: 6, + atime: Mon Nov 25 2013 00:37:27 GMT-0800 (PST), + mtime: Mon Nov 25 2013 00:37:27 GMT-0800 (PST), + ctime: Mon Nov 25 2013 00:37:27 GMT-0800 (PST), + blksize: 4096, + blocks: 1 + } - :param string path: Path to the target file. + :param string path: Path to the target file. .. js:function:: FS.lstat(path) - Identical to :js:func:`FS.stat`, However, if ``path`` is a symbolic link then the returned stats will be for the link itself, not the file that it links to. + Identical to :js:func:`FS.stat`, However, if ``path`` is a symbolic link then the returned stats will be for the link itself, not the file that it links to. - :param string path: Path to the target file. + :param string path: Path to the target file. .. js:function:: FS.chmod(path, mode) - Change the mode flags for ``path`` to ``mode``. - - .. note:: The underlying implementation does not support user or group permissions. The caller is always treated as the owner of the folder, and only permissions relevant to the owner apply. - - For example: + Change the mode flags for ``path`` to ``mode``. - .. code:: javascript + .. note:: The underlying implementation does not support user or group permissions. The caller is always treated as the owner of the folder, and only permissions relevant to the owner apply. - FS.writeFile('forbidden', 'can\'t touch this'); - FS.chmod('forbidden', 0000); + For example: - :param string path: Path to the target file. - :param int mode: The new :ref:`file permissions ` for ``path``, `in octal numeric notation `_. + .. code-block:: javascript + FS.writeFile('forbidden', 'can\'t touch this'); + FS.chmod('forbidden', 0000); + + :param string path: Path to the target file. + :param int mode: The new :ref:`file permissions ` for ``path``, `in octal numeric notation `_. .. js:function:: FS.lchmod(path, mode) - Identical to :js:func:`FS.chmod`. However, if ``path`` is a symbolic link then the mode will be set on the link itself, not the file that it links to. + Identical to :js:func:`FS.chmod`. However, if ``path`` is a symbolic link then the mode will be set on the link itself, not the file that it links to. - :param string path: Path to the target file. - :param int mode: The new :ref:`file permissions ` for ``path``, `in octal numeric notation `_. + :param string path: Path to the target file. + :param int mode: The new :ref:`file permissions ` for ``path``, `in octal numeric notation `_. .. js:function:: FS.fchmod(fd, mode) - Identical to :js:func:`FS.chmod`. However, a raw file descriptor is supplied as ``fd``. - - :param int fd: Descriptor of target file. - :param int mode: The new :ref:`file permissions ` for ``path``, `in octal numeric notation `_. + Identical to :js:func:`FS.chmod`. However, a raw file descriptor is supplied as ``fd``. + :param int fd: Descriptor of target file. + :param int mode: The new :ref:`file permissions ` for ``path``, `in octal numeric notation `_. .. js:function:: FS.chown(path, uid, gid) - Change the ownership of the specified file to the given user or group id. - - .. note:: |note-completeness| + Change the ownership of the specified file to the given user or group id. - :param string path: Path to the target file. - :param int uid: The id of the user to take ownership of the file. - :param int gid: The id of the group to take ownership of the file. + .. note:: |note-completeness| + :param string path: Path to the target file. + :param int uid: The id of the user to take ownership of the file. + :param int gid: The id of the group to take ownership of the file. .. js:function:: FS.lchown(path, uid, gid) - Identical to :js:func:`FS.chown`. However, if ``path`` is a symbolic link then the properties will be set on the link itself, not the file that it links to. - - .. note:: |note-completeness| + Identical to :js:func:`FS.chown`. However, if ``path`` is a symbolic link then the properties will be set on the link itself, not the file that it links to. - :param string path: Path to the target file. - :param int uid: The id of the user to take ownership of the file. - :param int gid: The id of the group to take ownership of the file. + .. note:: |note-completeness| + :param string path: Path to the target file. + :param int uid: The id of the user to take ownership of the file. + :param int gid: The id of the group to take ownership of the file. .. js:function:: FS.fchown(fd, uid, gid) - Identical to :js:func:`FS.chown`. However, a raw file descriptor is supplied as ``fd``. - - .. note:: |note-completeness| + Identical to :js:func:`FS.chown`. However, a raw file descriptor is supplied as ``fd``. + + .. note:: |note-completeness| + + :param int fd: Descriptor of target file. + :param int uid: The id of the user to take ownership of the file. + :param int gid: The id of the group to take ownership of the file. - :param int fd: Descriptor of target file. - :param int uid: The id of the user to take ownership of the file. - :param int gid: The id of the group to take ownership of the file. - .. js:function:: FS.truncate(path, len) - Truncates a file to the specified length. For example: + Truncates a file to the specified length. For example: - .. code:: c + .. code-block:: none - #include - #include + #include + #include - int main() { - MAIN_THREAD_EM_ASM( - FS.writeFile('file', 'foobar'); - FS.truncate('file', 3); - console.log(FS.readFile('file', { encoding: 'utf8' })); - ); - return 0; - } + int main() { + MAIN_THREAD_EM_ASM( + FS.writeFile('file', 'foobar'); + FS.truncate('file', 3); + console.log(FS.readFile('file', { encoding: 'utf8' })); + ); + return 0; + } - outputs + outputs:: + + foo + + :param string path: Path of the file to be truncated. + :param int len: The truncation length for the file. - :: - foo - - :param string path: Path of the file to be truncated. - :param int len: The truncation length for the file. - - - .. js:function:: FS.ftruncate(fd, len) - Truncates the file identified by the ``fd`` to the specified length (``len``). + Truncates the file identified by the ``fd`` to the specified length (``len``). - :param int fd: Descriptor of file to be truncated. - :param int len: The truncation length for the file. + :param int fd: Descriptor of file to be truncated. + :param int len: The truncation length for the file. .. js:function:: FS.utime(path, atime, mtime) - Change the timestamps of the file located at ``path``. The times passed to the arguments are in *milliseconds* since January 1, 1970 (midnight UTC/GMT). - - Note that in the current implementation the stored timestamp is a single value, the maximum of ``atime`` and ``mtime``. - - :param string path: The path of the file to update. - :param int atime: The file modify time (milliseconds). - :param int mtime: The file access time (milliseconds). + Change the timestamps of the file located at ``path``. The times passed to the arguments are in *milliseconds* since January 1, 1970 (midnight UTC/GMT). + + Note that in the current implementation the stored timestamp is a single value, the maximum of ``atime`` and ``mtime``. + + :param string path: The path of the file to update. + :param int atime: The file modify time (milliseconds). + :param int mtime: The file access time (milliseconds). + - .. js:function:: FS.open(path, flags [, mode]) - Opens a file with the specified flags. ``flags`` can be: + Opens a file with the specified flags. ``flags`` can be: + + .. _fs-read-and-write-flags: + + - ``r`` — Open file for reading. + - ``r+`` — Open file for reading and writing. + - ``w`` — Open file for writing. + - ``wx`` — Like ``w`` but fails if path exists. + - ``w+`` — Open file for reading and writing. The file is created if it does not exist or truncated if it exists. + - ``wx+`` — Like ``w+`` but fails if path exists. + - ``a`` — Open file for appending. The file is created if it does not exist. + - ``ax`` — Like ``a`` but fails if path exists. + - ``a+`` — Open file for reading and appending. The file is created if it does not exist. + - ``ax+`` — Like ``a+`` but fails if path exists. + + .. note:: The underlying implementation does not support user or group permissions. The file permissions set in ``mode`` are only used if the file is created. The caller is always treated as the owner of the file, and only those permissions apply. - .. _fs-read-and-write-flags: - - - ``r`` — Open file for reading. - - ``r+`` — Open file for reading and writing. - - ``w`` — Open file for writing. - - ``wx`` — Like ``w`` but fails if path exists. - - ``w+`` — Open file for reading and writing. The file is created if it does not exist or truncated if it exists. - - ``wx+`` — Like ``w+`` but fails if path exists. - - ``a`` — Open file for appending. The file is created if it does not exist. - - ``ax`` — Like ``a`` but fails if path exists. - - ``a+`` — Open file for reading and appending. The file is created if it does not exist. - - ``ax+`` — Like ``a+`` but fails if path exists. - .. note:: The underlying implementation does not support user or group permissions. The file permissions set in ``mode`` are only used if the file is created. The caller is always treated as the owner of the file, and only those permissions apply. + :param string path: The path of the file to open. + :param string flags: Read and write :ref:`flags `. + :param mode: File permission :ref:`flags ` for the file. The default setting (`in octal numeric notation `_) is 0666. + :returns: A stream object. - - :param string path: The path of the file to open. - :param string flags: Read and write :ref:`flags `. - :param mode: File permission :ref:`flags ` for the file. The default setting (`in octal numeric notation `_) is 0666. - :returns: A stream object. - .. js:function:: FS.close(stream) - Closes the file stream. - - :param object stream: The stream to be closed. + Closes the file stream. + + :param object stream: The stream to be closed. .. js:function:: FS.llseek(stream, offset, whence) - Repositions the offset of the stream ``offset`` bytes relative to the beginning, current position, or end of the file, depending on the ``whence`` parameter. - - The ``_llseek()`` function repositions the ``offset`` of the open file associated with the file descriptor ``fd`` to ``(offset_high<<32) | offset_low`` bytes relative to the beginning of the file, the current position in the file, or the end of the file, depending on whether whence is ``SEEK_SET``, ``SEEK_CUR``, or ``SEEK_END``, respectively. It returns the resulting file position in the argument result. - - .. todo:: **HamishW** Above sentence does not make sense. Have requested feedback. + Repositions the offset of the stream ``offset`` bytes relative to the beginning, current position, or end of the file, depending on the ``whence`` parameter. + + The ``_llseek()`` function repositions the ``offset`` of the open file associated with the file descriptor ``fd`` to ``(offset_high<<32) | offset_low`` bytes relative to the beginning of the file, the current position in the file, or the end of the file, depending on whether whence is ``SEEK_SET``, ``SEEK_CUR``, or ``SEEK_END``, respectively. It returns the resulting file position in the argument result. + + .. todo:: **HamishW** Above sentence does not make sense. Have requested feedback. + + :param object stream: The stream for which the offset is to be repositioned. + :param int offset: The offset (in bytes) relative to ``whence``. + :param int whence: Point in file (beginning, current point, end) from which to calculate the offset: ``SEEK_SET`` (0), ``SEEK_CUR`` (1) or ``SEEK_END`` (2) - :param object stream: The stream for which the offset is to be repositioned. - :param int offset: The offset (in bytes) relative to ``whence``. - :param int whence: Point in file (beginning, current point, end) from which to calculate the offset: ``SEEK_SET`` (0), ``SEEK_CUR`` (1) or ``SEEK_END`` (2) - .. js:function:: FS.read(stream, buffer, offset, length [, position]) - Read ``length`` bytes from the stream, storing them into ``buffer`` starting at ``offset``. - - By default, reading starts from the stream's current offset, however, a specific offset can be specified with the ``position`` argument. For example: - - .. code:: javascript - - var stream = FS.open('abinaryfile', 'r'); - var buf = new Uint8Array(4); - FS.read(stream, buf, 0, 4, 0); - FS.close(stream); - - :param object stream: The stream to read from. - :param ArrayBufferView buffer: The buffer to store the read data. - :param int offset: The offset within ``buffer`` to store the data. - :param int length: The length of data to write in ``buffer``. - :param int position: The offset within the stream to read. By default this is the stream's current offset. - - - + Read ``length`` bytes from the stream, storing them into ``buffer`` starting at ``offset``. + + By default, reading starts from the stream's current offset, however, a specific offset can be specified with the ``position`` argument. For example: + + .. code-block:: javascript + + var stream = FS.open('abinaryfile', 'r'); + var buf = new Uint8Array(4); + FS.read(stream, buf, 0, 4, 0); + FS.close(stream); + + :param object stream: The stream to read from. + :param ArrayBufferView buffer: The buffer to store the read data. + :param int offset: The offset within ``buffer`` to store the data. + :param int length: The length of data to write in ``buffer``. + :param int position: The offset within the stream to read. By default this is the stream's current offset. + + + .. js:function:: FS.write(stream, buffer, offset, length[, position]) - Writes ``length`` bytes from ``buffer``, starting at ``offset``. - - By default, writing starts from the stream's current offset, however, a specific offset can be specified with the ``position`` argument. For example: + Writes ``length`` bytes from ``buffer``, starting at ``offset``. - .. code:: javascript + By default, writing starts from the stream's current offset, however, a specific offset can be specified with the ``position`` argument. For example: - var data = new Uint8Array(32); - var stream = FS.open('dummy', 'w+'); - FS.write(stream, data, 0, data.length, 0); - FS.close(stream); + .. code-block:: javascript + + var data = new Uint8Array(32); + var stream = FS.open('dummy', 'w+'); + FS.write(stream, data, 0, data.length, 0); + FS.close(stream); + + :param object stream: The stream to write to. + :param ArrayBufferView buffer: The buffer to write. + :param int offset: The offset within ``buffer`` to write. + :param int length: The length of data to write. + :param int position: The offset within the stream to write. By default this is the stream's current offset. - :param object stream: The stream to write to. - :param ArrayBufferView buffer: The buffer to write. - :param int offset: The offset within ``buffer`` to write. - :param int length: The length of data to write. - :param int position: The offset within the stream to write. By default this is the stream's current offset. - .. js:function:: FS.readFile(path, opts) - Reads the entire file at ``path`` and returns it as a ``string`` (encoding is ``utf8``), or as a new ``Uint8Array`` buffer (encoding is ``binary``). + Reads the entire file at ``path`` and returns it as a ``string`` (encoding is ``utf8``), or as a new ``Uint8Array`` buffer (encoding is ``binary``). + + :param string path: The file to read. + :param object opts: + + - **encoding** (*string*) + Defines the encoding used to return the file contents: ``binary`` | ``utf8`` . The default is ``binary`` + - **flags** (*string*) + Read flags, as defined in :js:func:`FS.open`. The default is 'r'. - :param string path: The file to read. - :param object opts: - - - **encoding** (*string*) - Defines the encoding used to return the file contents: ``binary`` | ``utf8`` . The default is ``binary`` - - **flags** (*string*) - Read flags, as defined in :js:func:`FS.open`. The default is 'r'. - - :returns: The file as a ``string`` or ``Uint8Array`` buffer, depending on the encoding. + :returns: The file as a ``string`` or ``Uint8Array`` buffer, depending on the encoding. .. js:function:: FS.writeFile(path, data, opts) - Writes the entire contents of ``data`` to the file at ``path``. For example: + Writes the entire contents of ``data`` to the file at ``path``. For example: + + .. code-block:: javascript + + FS.writeFile('file', 'foobar'); + var contents = FS.readFile('file', { encoding: 'utf8' }); + + :param string path: The file to which to write ``data``. + :param string|ArrayBufferView data: The data to write. A string will always be decoded as UTF-8. + :param object opts: - .. code:: javascript + - **flags** (*string*) + Write flags, as defined in :js:func:`FS.open`. The default is 'w'. - FS.writeFile('file', 'foobar'); - var contents = FS.readFile('file', { encoding: 'utf8' }); - - :param string path: The file to which to write ``data``. - :param string|ArrayBufferView data: The data to write. A string will always be decoded as UTF-8. - :param object opts: - - - **flags** (*string*) - Write flags, as defined in :js:func:`FS.open`. The default is 'w'. - .. js:function:: FS.createLazyFile(parent, name, url, canRead, canWrite) - Creates a file that will be loaded lazily on first access from a given URL or local file system path, and returns a reference to it. + Creates a file that will be loaded lazily on first access from a given URL or local file system path, and returns a reference to it. - .. warning:: Firefox and Chrome have recently disabled synchronous binary XHRs, which means this cannot work for JavaScript in regular HTML pages (but it works within Web Workers). + .. warning:: Firefox and Chrome have recently disabled synchronous binary XHRs, which means this cannot work for JavaScript in regular HTML pages (but it works within Web Workers). - Example + Example - .. code:: javascript + .. code-block:: javascript + + FS.createLazyFile('/', 'foo', 'other/page.htm', true, false); + FS.createLazyFile('/', 'bar', '/get_file.php?name=baz', true, true); + + + :param parent: The parent folder, either as a path (e.g. `'/usr/lib'`) or an object previously returned from a `FS.createFolder()` or `FS.createPath()` call. + :type parent: string/object + :param string name: The name of the new file. + :param string url: In the browser, this is the URL whose contents will be returned when this file is accessed. In a command line engine like *node.js*, this will be the local (real) file system path from where the contents will be loaded. Note that writes to this file are virtual. + :param bool canRead: Whether the file should have read permissions set from the program's point of view. + :param bool canWrite: Whether the file should have write permissions set from the program's point of view. + :returns: A reference to the new file. - FS.createLazyFile('/', 'foo', 'other/page.htm', true, false); - FS.createLazyFile('/', 'bar', '/get_file.php?name=baz', true, true); - - - :param parent: The parent folder, either as a path (e.g. `'/usr/lib'`) or an object previously returned from a `FS.createFolder()` or `FS.createPath()` call. - :type parent: string/object - :param string name: The name of the new file. - :param string url: In the browser, this is the URL whose contents will be returned when this file is accessed. In a command line engine like *node.js*, this will be the local (real) file system path from where the contents will be loaded. Note that writes to this file are virtual. - :param bool canRead: Whether the file should have read permissions set from the program's point of view. - :param bool canWrite: Whether the file should have write permissions set from the program's point of view. - :returns: A reference to the new file. - .. js:function:: FS.createPreloadedFile(parent, name, url, canRead, canWrite) - Preloads a file asynchronously, and uses preload plugins to prepare its content. You should call this in ``preRun``, ``run()`` will be delayed until all preloaded files are ready. This is how the :ref:`preload-file ` option works in *emcc* when ``--use-preload-plugins`` has been specified (if you use this method by itself, you will need to build the program with that option). - - :param parent: The parent folder, either as a path (e.g. **'/usr/lib'**) or an object previously returned from a `FS.createFolder()` or `FS.createPath()` call. - :type parent: string/object - :param string name: The name of the new file. - :param string url: In the browser, this is the URL whose contents will be returned when the file is accessed. In a command line engine, this will be the local (real) file system path the contents will be loaded from. Note that writes to this file are virtual. - :param bool canRead: Whether the file should have read permissions set from the program's point of view. - :param bool canWrite: Whether the file should have write permissions set from the program's point of view. + Preloads a file asynchronously, and uses preload plugins to prepare its content. You should call this in ``preRun``, ``run()`` will be delayed until all preloaded files are ready. This is how the :ref:`preload-file ` option works in *emcc* when ``--use-preload-plugins`` has been specified (if you use this method by itself, you will need to build the program with that option). + + :param parent: The parent folder, either as a path (e.g. **'/usr/lib'**) or an object previously returned from a `FS.createFolder()` or `FS.createPath()` call. + :type parent: string/object + :param string name: The name of the new file. + :param string url: In the browser, this is the URL whose contents will be returned when the file is accessed. In a command line engine, this will be the local (real) file system path the contents will be loaded from. Note that writes to this file are virtual. + :param bool canRead: Whether the file should have read permissions set from the program's point of view. + :param bool canWrite: Whether the file should have write permissions set from the program's point of view. File types -=========== +========== Emscripten's file system supports regular files, directories, symlinks, character devices, block devices and sockets. Similarly to most Unix systems, all of these file types can be operated on using the higher-level FS operations like :js:func:`FS.read` and :js:func:`FS.write`. .. js:function:: FS.isFile(mode) - Tests if the ``mode`` bitmask represents a file. - - :param mode: A bitmask of possible file properties. - :returns: ``true`` if the ``mode`` bitmask represents a file. - :rtype: bool + Tests if the ``mode`` bitmask represents a file. + + :param mode: A bitmask of possible file properties. + :returns: ``true`` if the ``mode`` bitmask represents a file. + :rtype: bool .. js:function:: FS.isDir(mode) - Tests if the ``mode`` bitmask represents a directory. + Tests if the ``mode`` bitmask represents a directory. - :returns: ``true`` if the ``mode`` bitmask represents a directory. - :rtype: bool + :returns: ``true`` if the ``mode`` bitmask represents a directory. + :rtype: bool .. js:function:: FS.isLink(mode) - Tests if the ``mode`` bitmask represents a symlink. + Tests if the ``mode`` bitmask represents a symlink. - :param mode: A bitmask of possible file properties. - :returns: ``true`` if the ``mode`` bitmask represents a symlink. - :rtype: bool + :param mode: A bitmask of possible file properties. + :returns: ``true`` if the ``mode`` bitmask represents a symlink. + :rtype: bool .. js:function:: FS.isChrdev(mode) - Tests if the ``mode`` bitmask represents a character device. + Tests if the ``mode`` bitmask represents a character device. - :param mode: A bitmask of possible file properties. - :returns: ``true`` if the ``mode`` bitmask represents a character device. - :rtype: bool + :param mode: A bitmask of possible file properties. + :returns: ``true`` if the ``mode`` bitmask represents a character device. + :rtype: bool .. js:function:: FS.isBlkdev(mode) - Tests if the ``mode`` bitmask represents a block device. + Tests if the ``mode`` bitmask represents a block device. - :param mode: A bitmask of possible file properties. - :returns: ``true`` if the ``mode`` bitmask represents a block device. - :rtype: bool + :param mode: A bitmask of possible file properties. + :returns: ``true`` if the ``mode`` bitmask represents a block device. + :rtype: bool .. js:function:: FS.isSocket(mode) - Tests if the ``mode`` bitmask represents a socket. + Tests if the ``mode`` bitmask represents a socket. - :param mode: A bitmask of possible file properties. - :returns: ``true`` if the ``mode`` bitmask represents a socket. - :rtype: bool + :param mode: A bitmask of possible file properties. + :returns: ``true`` if the ``mode`` bitmask represents a socket. + :rtype: bool Paths -======= +===== .. js:function:: FS.cwd() - Gets the current working directory. + Gets the current working directory. + + :returns: The current working directory. - :returns: The current working directory. - - .. js:function:: FS.lookupPath(path, opts) - Looks up the incoming path and returns an object containing both the resolved path and node. - - The options (``opts``) allow you to specify whether the object, its parent component, a symlink, or the item the symlink points to are returned. For example: :: - - var lookup = FS.lookupPath(path, { parent: true }); - - :param string path: The incoming path. - :param object opts: Options for the path: - - - **parent** (*bool*) - If true, stop resolving the path once the penultimate component is reached. - For example, the path ``/foo/bar`` with ``{ parent: true }`` would return an object representing ``/foo``. The default is ``false``. - - **follow** (*bool*) - If true, follow the last component if it is a symlink. - For example, consider a symlink ``/foo/symlink`` that links to ``/foo/notes.txt``. If ``{ follow: true }``, an object representing ``/foo/notes.txt`` would be returned. If ``{ follow: false }``, an object representing the symlink file would be returned. The default is ``false``. - - :returns: an object with the format: - - .. code-block:: javascript - - { - path: resolved_path, - node: resolved_node - } + Looks up the incoming path and returns an object containing both the resolved path and node. + The options (``opts``) allow you to specify whether the object, its parent component, a symlink, or the item the symlink points to are returned. For example: :: + + var lookup = FS.lookupPath(path, { parent: true }); + + :param string path: The incoming path. + :param object opts: Options for the path: + + - **parent** (*bool*) + If true, stop resolving the path once the penultimate component is reached. + For example, the path ``/foo/bar`` with ``{ parent: true }`` would return an object representing ``/foo``. The default is ``false``. + - **follow** (*bool*) + If true, follow the last component if it is a symlink. + For example, consider a symlink ``/foo/symlink`` that links to ``/foo/notes.txt``. If ``{ follow: true }``, an object representing ``/foo/notes.txt`` would be returned. If ``{ follow: false }``, an object representing the symlink file would be returned. The default is ``false``. + + :returns: an object with the format: + + .. code-block:: javascript + + { + path: resolved_path, + node: resolved_node + } .. js:function:: FS.getPath(node) - Gets the absolute path to ``node``, accounting for mounts. - - :param node: The current node. - :returns: The absolute path to ``node``. + Gets the absolute path to ``node``, accounting for mounts. + :param node: The current node. + :returns: The absolute path to ``node``. .. COMMENT (not rendered): Section below is automated copy and replace text. This is useful where we have boilerplate text. - + .. |note-completeness| replace:: This call exists to provide a more "complete" API mapping for ported code. Values set are effectively ignored. diff --git a/site/source/docs/api_reference/bind.h.rst b/site/source/docs/api_reference/bind.h.rst index 49f721779891d..b4a4f2378d655 100644 --- a/site/source/docs/api_reference/bind.h.rst +++ b/site/source/docs/api_reference/bind.h.rst @@ -1,8 +1,8 @@ .. _bind-h: -================================ +=========================== bind.h (under-construction) -================================ +=========================== The C++ APIs in `bind.h `_ define (**HamishW**-Replace with description.) @@ -186,14 +186,6 @@ Functions :returns: **HamishW** Add description. -.. cpp:function:: void* __getDynamicPointerType(void* p) - - **HamishW** Add description. - - :param void* p: **HamishW** Add description. - :returns: **HamishW** Add description. - - .. cpp:function:: void function() .. code-block:: cpp @@ -286,7 +278,7 @@ Value tuples Value structs -====================================== +============= .. cpp:class:: value_object : public internal::noncopyable @@ -314,7 +306,7 @@ Value structs **HamishW** Add description. :param const char* fieldName: **HamishW** Add description. - :param FieldType InstanceType::*field: **HamishW** Add description. + :param FieldType InstanceType\:\:\*field: **HamishW** Add description. :returns: **HamishW** Add description. @@ -339,11 +331,8 @@ Value structs :returns: **HamishW** Add description. - - - Smart pointers -====================================== +============== .. cpp:type:: default_smart_ptr_trait @@ -409,7 +398,7 @@ Smart pointers -.. cpp:type:: smart_ptr_trait> +.. cpp:type:: template smart_ptr_trait> .. code-block:: cpp @@ -447,7 +436,7 @@ Smart pointers **HamishW** Add description. :param PointeeType* p: **HamishW** Add description. Note that ``PointeeType`` is a typename (templated type). - :param internal::EM_VAL v: **HamishW** Add description. + :param internal\:\:EM_VAL v: **HamishW** Add description. :returns: **HamishW** Add description. .. cpp:function:: static PointerType* construct_null() @@ -466,7 +455,7 @@ Classes **HamishW** Add description if needed. Note from source "// abstract classes" -.. cpp:class:: class wrapper : public T, public internal::WrapperBase +.. cpp:class:: wrapper : public T, public internal::WrapperBase .. code-block:: cpp @@ -541,7 +530,7 @@ Classes - .. cpp:function:: HAMISHW_ HELP_Needed + .. cpp:function:: HAMISHW_ HELP_Needed() **HamishW** I don't understand this C++, so not sure how to document. Putting code here for Chad to advise on how to document @@ -683,7 +672,7 @@ Classes .. _embind-class-function-pointer-constructor: - .. cpp:function:: const class_& constructor() const + .. cpp:function:: const class_& constructor(ReturnType (*factory)(Args...), Policies...) const .. code-block:: cpp @@ -730,11 +719,11 @@ Classes :param const char* wrapperClassName: **HamishW** Add description. :param const char* pointerName: **HamishW** Add description. - :param ::emscripten::constructor constructor): **HamishW** Add description. + :param emscripten\:\:constructor constructor): **HamishW** Add description. :returns: |class_-function-returns| - .. cpp:function:: const class_& allow_subclass() const + .. cpp:function:: const class_& allow_subclass(const char* wrapperClassName, ::emscripten::constructor constructor) const .. code-block:: cpp @@ -748,7 +737,7 @@ Classes **HamishW** Add description. Explain how this constructor differs from other one. :param const char* wrapperClassName: **HamishW** Add description. - :param ::emscripten::constructor constructor): **HamishW** Add description. + :param \:\:emscripten\:\:constructor constructor): **HamishW** Add description. :returns: |class_-function-returns| @@ -768,12 +757,12 @@ Classes **HamishW** Check description. Note prototype moved to "prototype" block above because syntax broke Sphinx. Also explain how this method differs from the other overloads. :param const char* methodName: **HamishW** Add description. - :param ReturnType (ClassType::*memberFunction)(Args...): **HamishW** Add description. Note that ``ReturnType`` is a template typename for this function and ``ClassType`` is a template typename for the class. + :param ReturnType (ClassType\:\:\*memberFunction)(Args...): **HamishW** Add description. Note that ``ReturnType`` is a template typename for this function and ``ClassType`` is a template typename for the class. :param typename... Policies: |policies-argument| :returns: |class_-function-returns| - .. cpp:function:: const class_& function() const + .. cpp:function:: const class_& function(const char* methodName, ReturnType (ClassType::*memberFunction)(Args...) const, Policies...) const .. code-block:: cpp @@ -784,12 +773,12 @@ Classes **HamishW** Add description. Note, prototype moved into block above as it broke Sphinx. Also this only differs by a const on the ReturnType from the previous function :param const char* methodName: **HamishW** Add description. - :param ReturnType (ClassType::*memberFunction)(Args...) const: **HamishW** Add description. Note that ``ReturnType`` is a template typename for this function and ``ClassType`` is a template typename for the class. + :param ReturnType (ClassType\:\:\*memberFunction)(Args...) const: **HamishW** Add description. Note that ``ReturnType`` is a template typename for this function and ``ClassType`` is a template typename for the class. :param typename... Policies: |policies-argument| :returns: |class_-function-returns| - .. cpp:function:: const class_& function() const + .. cpp:function:: const class_& function(const char* methodName, ReturnType (*function)(ThisType, Args...), Policies...) const .. code-block:: cpp @@ -816,7 +805,7 @@ Classes **HamishW** Add description. Note, signature copied to prototype block above because proper signature broke Sphinx. Also because it is useful to include the template information. :param const char* fieldName: **HamishW** Add description. - :param const FieldType ClassType::*field: **HamishW** Add description. + :param const FieldType ClassType\:\:\*field: **HamishW** Add description. :returns: |class_-function-returns| @@ -832,7 +821,7 @@ Classes **HamishW** Add description. :param const char* fieldName: **HamishW** Add description. - :param FieldType ClassType::*field: **HamishW** Add description. + :param FieldType ClassType\:\:\*field: **HamishW** Add description. :returns: |class_-function-returns| @@ -900,7 +889,7 @@ Classes **HamishW** Add description. :param const char* fieldName: **HamishW** Add description. - :param FieldType ClassType::*field: **HamishW** Add description. + :param FieldType ClassType\:\:\*field: **HamishW** Add description. :returns: |class_-function-returns| diff --git a/site/source/docs/api_reference/emscripten.h.rst b/site/source/docs/api_reference/emscripten.h.rst index 919b98948fe3b..4a44deb8761ad 100644 --- a/site/source/docs/api_reference/emscripten.h.rst +++ b/site/source/docs/api_reference/emscripten.h.rst @@ -4,13 +4,13 @@ emscripten.h ============ -This page documents the public C++ APIs provided by `emscripten.h `_. +This page documents the public C++ APIs provided by `emscripten.h `_. -Emscripten uses existing/familiar APIs where possible (for example: :term:`SDL`). This API provides C++ support for capabilities that are specific to JavaScript or the browser environment, or for which there is no existing API. +Emscripten uses existing/familiar APIs where possible (for example: :term:`SDL`). This API provides C++ support for capabilities that are specific to JavaScript or the browser environment, or for which there is no existing API. .. contents:: Table of Contents - :local: - :depth: 1 + :local: + :depth: 1 @@ -24,143 +24,169 @@ Defines .. c:macro:: EM_JS(return_type, function_name, arguments, code) - Convenient syntax for JavaScript library functions. - - This allows you to declare JavaScript in your C code as a function, which can - be called like a normal C function. For example, the following C program would - display two alerts if it was compiled with Emscripten and run in the browser: :: - EM_JS(void, two_alerts, (), { - alert('hai'); - alert('bai'); - }); - - int main() { - two_alerts(); - return 0; - } - - Arguments can be passed as normal C arguments, and have the same name in the - JavaScript code. These arguments can either be of type ``int32_t`` or - ``double``. :: - EM_JS(void, take_args, (int x, float y), { - console.log('I received: ' + [x, y]); - }); - - int main() { - take_args(100, 35.5); - return 0; - } - - Null-terminated C strings can also be passed into ``EM_JS`` functions, but to - operate on them, they need to be copied out from the heap to convert to - high-level JavaScript strings. :: - EM_JS(void, say_hello, (const char* str), { - console.log('hello ' + UTF8ToString(str)); - } - - In the same manner, pointers to any type (including ``void *``) can be passed - inside ``EM_JS`` code, where they appear as integers like ``char *`` pointers - above did. Accessing the data can be managed by reading the heap directly. :: - EM_JS(void, read_data, (int* data), { - console.log('Data: ' + HEAP32[data>>2] + ', ' + HEAP32[(data+4)>>2]); - }); - - int main() { - int arr[2] = { 30, 45 }; - read_data(arr); - return 0; - } - - In addition, EM_JS functions can return a value back to C code. The output - value is passed back with a ``return`` statement: :: - EM_JS(int, add_forty_two, (int n), { - return n + 42; - }); - - EM_JS(int, get_total_memory, (), { - return TOTAL_MEMORY; - }); - - int main() { - int x = add_forty_two(100); - int y = get_total_memory(); - // ... - } - - Strings can be returned back to C from JavaScript, but one needs to be careful - about memory management. :: - EM_JS(const char*, get_unicode_str, (), { - var jsString = 'Hello with some exotic Unicode characters: Tässä on yksi lumiukko: ☃, ole hyvä.'; - // 'jsString.length' would return the length of the string as UTF-16 - // units, but Emscripten C strings operate as UTF-8. - var lengthBytes = lengthBytesUTF8(jsString)+1; - var stringOnWasmHeap = _malloc(lengthBytes); - stringToUTF8(jsString, stringOnWasmHeap, lengthBytes+1); - return stringOnWasmHeap; - }); - - int main() { - const char* str = get_unicode_str(); - printf("UTF8 string says: %s\n", str); - // Each call to _malloc() must be paired with free(), or heap memory will leak! - free(str); - return 0; - } + Convenient syntax for JavaScript library functions. + + This allows you to declare JavaScript in your C code as a function, which can + be called like a normal C function. For example, the following C program would + display two alerts if it was compiled with Emscripten and run in the browser: + + .. code-block:: none + + EM_JS(void, two_alerts, (), { + alert('hai'); + alert('bai'); + }); + + int main() { + two_alerts(); + return 0; + } + + Arguments can be passed as normal C arguments, and have the same name in the + JavaScript code. These arguments can either be of type ``int32_t`` or + ``double``. + + .. code-block:: none + + EM_JS(void, take_args, (int x, float y), { + console.log('I received: ' + [x, y]); + }); + + int main() { + take_args(100, 35.5); + return 0; + } + + Null-terminated C strings can also be passed into ``EM_JS`` functions, but to + operate on them, they need to be copied out from the heap to convert to + high-level JavaScript strings. + + .. code-block:: none + + EM_JS(void, say_hello, (const char* str), { + console.log('hello ' + UTF8ToString(str)); + } + + In the same manner, pointers to any type (including ``void *``) can be passed + inside ``EM_JS`` code, where they appear as integers like ``char *`` pointers + above did. Accessing the data can be managed by reading the heap directly. + + .. code-block:: none + + EM_JS(void, read_data, (int* data), { + console.log('Data: ' + HEAP32[data>>2] + ', ' + HEAP32[(data+4)>>2]); + }); + + int main() { + int arr[2] = { 30, 45 }; + read_data(arr); + return 0; + } + + In addition, EM_JS functions can return a value back to C code. The output + value is passed back with a ``return`` statement: + + .. code-block:: none + + EM_JS(int, add_forty_two, (int n), { + return n + 42; + }); + + EM_JS(int, get_total_memory, (), { + return TOTAL_MEMORY; + }); + + int main() { + int x = add_forty_two(100); + int y = get_total_memory(); + // ... + } + + Strings can be returned back to C from JavaScript, but one needs to be careful + about memory management. + + .. code-block:: none + + EM_JS(const char*, get_unicode_str, (), { + var jsString = 'Hello with some exotic Unicode characters: Tässä on yksi lumiukko: ☃, ole hyvä.'; + // 'jsString.length' would return the length of the string as UTF-16 + // units, but Emscripten C strings operate as UTF-8. + var lengthBytes = lengthBytesUTF8(jsString)+1; + var stringOnWasmHeap = _malloc(lengthBytes); + stringToUTF8(jsString, stringOnWasmHeap, lengthBytes+1); + return stringOnWasmHeap; + }); + + int main() { + const char* str = get_unicode_str(); + printf("UTF8 string says: %s\n", str); + // Each call to _malloc() must be paired with free(), or heap memory will leak! + free(str); + return 0; + } .. c:macro:: EM_ASM(...) - Convenient syntax for inline assembly/JavaScript. - - This allows you to declare JavaScript in your C code "inline", which is then executed when your compiled code is run in the browser. For example, the following C code would display two alerts if it was compiled with Emscripten and run in the browser: :: + Convenient syntax for inline assembly/JavaScript. - EM_ASM(alert('hai'); alert('bai')); + This allows you to declare JavaScript in your C code "inline", which is then executed when your compiled code is run in the browser. For example, the following C code would display two alerts if it was compiled with Emscripten and run in the browser: - Arguments can be passed inside the JavaScript code block, where they arrive as variables ``$0``, ``$1`` etc. These arguments can either be of type ``int32_t`` or ``double``. :: + .. code-block:: none - EM_ASM({ - console.log('I received: ' + [$0, $1]); - }, 100, 35.5); + EM_ASM(alert('hai'); alert('bai')); - Note the ``{`` and ``}``. + Arguments can be passed inside the JavaScript code block, where they arrive as variables ``$0``, ``$1`` etc. These arguments can either be of type ``int32_t`` or ``double``. - Null-terminated C strings can also be passed into ``EM_ASM`` blocks, but to operate on them, they need to be copied out from the heap to convert to high-level JavaScript strings. :: + .. code-block:: none - EM_ASM(console.log('hello ' + UTF8ToString($0)), "world!"); + EM_ASM({ + console.log('I received: ' + [$0, $1]); + }, 100, 35.5); - In the same manner, pointers to any type (including ``void *``) can be passed inside ``EM_ASM`` code, where they appear as integers like ``char *`` pointers above did. Accessing the data can be managed by reading the heap directly. :: + Note the ``{`` and ``}``. + + Null-terminated C strings can also be passed into ``EM_ASM`` blocks, but to operate on them, they need to be copied out from the heap to convert to high-level JavaScript strings. - int arr[2] = { 30, 45 }; - EM_ASM({ - console.log('Data: ' + HEAP32[$0>>2] + ', ' + HEAP32[($0+4)>>2]); - }, arr); + .. code-block:: none + + EM_ASM(console.log('hello ' + UTF8ToString($0)), "world!"); + + In the same manner, pointers to any type (including ``void *``) can be passed inside ``EM_ASM`` code, where they appear as integers like ``char *`` pointers above did. Accessing the data can be managed by reading the heap directly. :: - .. note:: - - As of Emscripten ``1.30.4``, the contents of ``EM_ASM`` code blocks appear inside the normal JS file, and as result, Closure compiler and other JavaScript minifiers will be able to operate on them. You may need to use safety quotes in some places (``a['b']`` instead of ``a.b``) to avoid minification fro occurring. - - The C preprocessor does not have an understanding of JavaScript tokens, and as a result, if the ``code`` block contains a comma character ``,``, it may be necessary to wrap the code block inside parentheses. For example, code ``EM_ASM(return [1,2,3].length);`` will not compile, but ``EM_ASM((return [1,2,3].length));`` does. + int arr[2] = { 30, 45 }; + EM_ASM({ + console.log('Data: ' + HEAP32[$0>>2] + ', ' + HEAP32[($0+4)>>2]); + }, arr); + .. note:: + - As of Emscripten ``1.30.4``, the contents of ``EM_ASM`` code blocks appear inside the normal JS file, and as result, Closure compiler and other JavaScript minifiers will be able to operate on them. You may need to use safety quotes in some places (``a['b']`` instead of ``a.b``) to avoid minification fro occurring. + - The C preprocessor does not have an understanding of JavaScript tokens, and as a result, if the ``code`` block contains a comma character ``,``, it may be necessary to wrap the code block inside parentheses. For example, code ``EM_ASM(return [1,2,3].length);`` will not compile, but ``EM_ASM((return [1,2,3].length));`` does. .. c:macro:: EM_ASM_INT(code, ...) - EM_ASM_DOUBLE(code, ...) - - These two functions behave like EM_ASM, but in addition they also return a value back to C code. The output value is passed back with a ``return`` statement: :: - int x = EM_ASM_INT({ - return $0 + 42; - }, 100); + EM_ASM_DOUBLE(code, ...) - int y = EM_ASM_INT(return TOTAL_MEMORY); + These two functions behave like EM_ASM, but in addition they also return a value back to C code. The output value is passed back with a ``return`` statement: + + .. code-block:: none + + int x = EM_ASM_INT({ + return $0 + 42; + }, 100); + + int y = EM_ASM_INT(return TOTAL_MEMORY); Strings can be returned back to C from JavaScript, but one needs to be careful about memory management. :: - char *str = (char*)EM_ASM_INT({ - var jsString = 'Hello with some exotic Unicode characters: Tässä on yksi lumiukko: ☃, ole hyvä.'; - var lengthBytes = lengthBytesUTF8(jsString)+1; // 'jsString.length' would return the length of the string as UTF-16 units, but Emscripten C strings operate as UTF-8. - var stringOnWasmHeap = _malloc(lengthBytes); - stringToUTF8(jsString, stringOnWasmHeap, lengthBytes+1); - return stringOnWasmHeap; - }); - printf("UTF8 string says: %s\n", str); - free(str); // Each call to _malloc() must be paired with free(), or heap memory will leak! + char *str = (char*)EM_ASM_INT({ + var jsString = 'Hello with some exotic Unicode characters: Tässä on yksi lumiukko: ☃, ole hyvä.'; + var lengthBytes = lengthBytesUTF8(jsString)+1; // 'jsString.length' would return the length of the string as UTF-16 units, but Emscripten C strings operate as UTF-8. + var stringOnWasmHeap = _malloc(lengthBytes); + stringToUTF8(jsString, stringOnWasmHeap, lengthBytes+1); + return stringOnWasmHeap; + }); + printf("UTF8 string says: %s\n", str); + free(str); // Each call to _malloc() must be paired with free(), or heap memory will leak! Calling JavaScript From C/C++ @@ -171,309 +197,309 @@ Guide material for the following APIs can be found in :ref:`interacting-with-cod Function pointer types for callbacks ------------------------------------ -The following types are used to define function callback signatures used in a number of functions in this file. +The following types are used to define function callback signatures used in a number of functions in this file. .. c:type:: em_callback_func - General function pointer type for use in callbacks with no parameters. - - Defined as: :: - - typedef void (*em_callback_func)(void) + General function pointer type for use in callbacks with no parameters. + + Defined as: :: + + typedef void (*em_callback_func)(void) + - .. c:type:: em_arg_callback_func - Generic function pointer type for use in callbacks with a single ``void*`` parameter. - - This type is used to define function callbacks that need to pass arbitrary data. For example, :c:func:`emscripten_set_main_loop_arg` sets user-defined data, and passes it to a callback of this type on completion. - - Defined as: :: + Generic function pointer type for use in callbacks with a single ``void*`` parameter. + + This type is used to define function callbacks that need to pass arbitrary data. For example, :c:func:`emscripten_set_main_loop_arg` sets user-defined data, and passes it to a callback of this type on completion. + + Defined as: :: + + typedef void (*em_arg_callback_func)(void*) + - typedef void (*em_arg_callback_func)(void*) - - .. c:type:: em_str_callback_func - General function pointer type for use in callbacks with a C string (``const char *``) parameter. - - This type is used for function callbacks that need to be passed a C string. For example, it is used in :c:func:`emscripten_async_wget` to pass the name of a file that has been asynchronously loaded. - - Defined as: :: + General function pointer type for use in callbacks with a C string (``const char *``) parameter. + + This type is used for function callbacks that need to be passed a C string. For example, it is used in :c:func:`emscripten_async_wget` to pass the name of a file that has been asynchronously loaded. + + Defined as: :: + + typedef void (*em_str_callback_func)(const char *) - typedef void (*em_str_callback_func)(const char *) - Functions --------- .. c:function:: void emscripten_run_script(const char *script) - Interface to the underlying JavaScript engine. This function will ``eval()`` the given script. Note: If -s NO_DYNAMIC_EXECUTION=1 is set, this function will not be available. + Interface to the underlying JavaScript engine. This function will ``eval()`` the given script. Note: If -s NO_DYNAMIC_EXECUTION=1 is set, this function will not be available. + + This function can be called from a pthread, and it is executed in the scope of the Web Worker that is hosting the pthread. To evaluate a function in the scope of the main runtime thread, see the function emscripten_sync_run_in_main_runtime_thread(). - This function can be called from a pthread, and it is executed in the scope of the Web Worker that is hosting the pthread. To evaluate a function in the scope of the main runtime thread, see the function emscripten_sync_run_in_main_runtime_thread(). + :param script: The script to evaluate. + :type script: const char* + :rtype: void - :param script: The script to evaluate. - :type script: const char* - :rtype: void - .. c:function:: int emscripten_run_script_int(const char *script) - Interface to the underlying JavaScript engine. This function will ``eval()`` the given script. Note: If -s NO_DYNAMIC_EXECUTION=1 is set, this function will not be available. + Interface to the underlying JavaScript engine. This function will ``eval()`` the given script. Note: If -s NO_DYNAMIC_EXECUTION=1 is set, this function will not be available. - This function can be called from a pthread, and it is executed in the scope of the Web Worker that is hosting the pthread. To evaluate a function in the scope of the main runtime thread, see the function emscripten_sync_run_in_main_runtime_thread(). + This function can be called from a pthread, and it is executed in the scope of the Web Worker that is hosting the pthread. To evaluate a function in the scope of the main runtime thread, see the function emscripten_sync_run_in_main_runtime_thread(). + + :param script: The script to evaluate. + :type script: const char* + :return: The result of the evaluation, as an integer. + :rtype: int - :param script: The script to evaluate. - :type script: const char* - :return: The result of the evaluation, as an integer. - :rtype: int - .. c:function:: char *emscripten_run_script_string(const char *script) - Interface to the underlying JavaScript engine. This function will ``eval()`` the given script. Note that this overload uses a single buffer shared between calls. Note: If -s NO_DYNAMIC_EXECUTION=1 is set, this function will not be available. + Interface to the underlying JavaScript engine. This function will ``eval()`` the given script. Note that this overload uses a single buffer shared between calls. Note: If -s NO_DYNAMIC_EXECUTION=1 is set, this function will not be available. + + This function can be called from a pthread, and it is executed in the scope of the Web Worker that is hosting the pthread. To evaluate a function in the scope of the main runtime thread, see the function emscripten_sync_run_in_main_runtime_thread(). - This function can be called from a pthread, and it is executed in the scope of the Web Worker that is hosting the pthread. To evaluate a function in the scope of the main runtime thread, see the function emscripten_sync_run_in_main_runtime_thread(). + :param script: The script to evaluate. + :type script: const char* + :return: The result of the evaluation, as a string. + :rtype: char* - :param script: The script to evaluate. - :type script: const char* - :return: The result of the evaluation, as a string. - :rtype: char* - -.. c:function:: void emscripten_async_run_script(const char *script, int millis) +.. c:function:: void emscripten_async_run_script(const char *script, int millis) - Asynchronously run a script, after a specified amount of time. + Asynchronously run a script, after a specified amount of time. - This function can be called from a pthread, and it is executed in the scope of the Web Worker that is hosting the pthread. To evaluate a function in the scope of the main runtime thread, see the function emscripten_sync_run_in_main_runtime_thread(). + This function can be called from a pthread, and it is executed in the scope of the Web Worker that is hosting the pthread. To evaluate a function in the scope of the main runtime thread, see the function emscripten_sync_run_in_main_runtime_thread(). - :param script: The script to evaluate. - :type script: const char* - :param int millis: The amount of time before the script is run, in milliseconds. - :rtype: void + :param script: The script to evaluate. + :type script: const char* + :param int millis: The amount of time before the script is run, in milliseconds. + :rtype: void .. c:function:: void emscripten_async_load_script(const char *script, em_callback_func onload, em_callback_func onerror) - Asynchronously loads a script from a URL. - - This integrates with the run dependencies system, so your script can call ``addRunDependency`` multiple times, prepare various asynchronous tasks, and call ``removeRunDependency`` on them; when all are complete (or if there were no run dependencies to begin with), ``onload`` is called. An example use for this is to load an asset module, that is, the output of the file packager. + Asynchronously loads a script from a URL. + + This integrates with the run dependencies system, so your script can call ``addRunDependency`` multiple times, prepare various asynchronous tasks, and call ``removeRunDependency`` on them; when all are complete (or if there were no run dependencies to begin with), ``onload`` is called. An example use for this is to load an asset module, that is, the output of the file packager. + + This function is currently only available in main browser thread, and it will immediately fail by calling the supplied onerror() handler if called in a pthread. - This function is currently only available in main browser thread, and it will immediately fail by calling the supplied onerror() handler if called in a pthread. + :param script: The script to evaluate. + :type script: const char* + :param em_callback_func onload: A callback function, with no parameters, that is executed when the script has fully loaded. + :param em_callback_func onerror: A callback function, with no parameters, that is executed if there is an error in loading. + :rtype: void - :param script: The script to evaluate. - :type script: const char* - :param em_callback_func onload: A callback function, with no parameters, that is executed when the script has fully loaded. - :param em_callback_func onerror: A callback function, with no parameters, that is executed if there is an error in loading. - :rtype: void - .. _emscripten-h-browser-execution-environment: - + Browser Execution Environment ============================= Guide material for the following APIs can be found in :ref:`emscripten-runtime-environment`. - + Functions --------- - + .. c:function:: void emscripten_set_main_loop(em_callback_func func, int fps, int simulate_infinite_loop) - Set a C function as the main event loop for the calling thread. - - If the main loop function needs to receive user-defined data, use :c:func:`emscripten_set_main_loop_arg` instead. + Set a C function as the main event loop for the calling thread. - The JavaScript environment will call that function at a specified number of frames per second. If called on the main browser thread, setting 0 or a negative value as the ``fps`` will use the browser’s ``requestAnimationFrame`` mechanism to call the main loop function. This is **HIGHLY** recommended if you are doing rendering, as the browser’s ``requestAnimationFrame`` will make sure you render at a proper smooth rate that lines up properly with the browser and monitor. If you do not render at all in your application, then you should pick a specific frame rate that makes sense for your code. - - If ``simulate_infinite_loop`` is true, the function will throw an exception in order to stop execution of the caller. This will lead to the main loop being entered instead of code after the call to :c:func:`emscripten_set_main_loop` being run, which is the closest we can get to simulating an infinite loop (we do something similar in `glutMainLoop `_ in `GLUT `_). If this parameter is ``false``, then the behavior is the same as it was before this parameter was added to the API, which is that execution continues normally. Note that in both cases we do not run global destructors, ``atexit``, etc., since we know the main loop will still be running, but if we do not simulate an infinite loop then the stack will be unwound. That means that if ``simulate_infinite_loop`` is ``false``, and you created an object on the stack, it will be cleaned up before the main loop is called for the first time. - - This function can be called in a pthread, in which case the callback loop will be set up to be called in the context of the calling thread. In order for the loop to work, the calling thread must regularly "yield back" to the browser by exiting from its pthread main function, since the callback will be able to execute only when the calling thread is not executing any other code. This means that running a synchronously blocking main loop is not compatible with the emscripten_set_main_loop() function. + If the main loop function needs to receive user-defined data, use :c:func:`emscripten_set_main_loop_arg` instead. - Since ``requestAnimationFrame()`` API is not available in web workers, when called ``emscripten_set_main_loop()`` in a pthread with ``fps`` <= 0, the effect of syncing up to the display's refresh rate is emulated, and generally will not precisely line up with vsync intervals. + The JavaScript environment will call that function at a specified number of frames per second. If called on the main browser thread, setting 0 or a negative value as the ``fps`` will use the browser’s ``requestAnimationFrame`` mechanism to call the main loop function. This is **HIGHLY** recommended if you are doing rendering, as the browser’s ``requestAnimationFrame`` will make sure you render at a proper smooth rate that lines up properly with the browser and monitor. If you do not render at all in your application, then you should pick a specific frame rate that makes sense for your code. - .. tip:: There can be only *one* main loop function at a time, per thread. To change the main loop function, first :c:func:`cancel ` the current loop, and then call this function to set another. - - .. note:: See :c:func:`emscripten_set_main_loop_expected_blockers`, :c:func:`emscripten_pause_main_loop`, :c:func:`emscripten_resume_main_loop` and :c:func:`emscripten_cancel_main_loop` for information about blocking, pausing, and resuming the main loop of the calling thread. + If ``simulate_infinite_loop`` is true, the function will throw an exception in order to stop execution of the caller. This will lead to the main loop being entered instead of code after the call to :c:func:`emscripten_set_main_loop` being run, which is the closest we can get to simulating an infinite loop (we do something similar in `glutMainLoop `_ in `GLUT `_). If this parameter is ``false``, then the behavior is the same as it was before this parameter was added to the API, which is that execution continues normally. Note that in both cases we do not run global destructors, ``atexit``, etc., since we know the main loop will still be running, but if we do not simulate an infinite loop then the stack will be unwound. That means that if ``simulate_infinite_loop`` is ``false``, and you created an object on the stack, it will be cleaned up before the main loop is called for the first time. - .. note:: Calling this function overrides the effect of any previous calls to :c:func:`emscripten_set_main_loop_timing` in the calling thread by applying the timing mode specified by the parameter ``fps``. To specify a different timing mode for the current thread, call the function :c:func:`emscripten_set_main_loop_timing` after setting up the main loop. - - :param em_callback_func func: C function to set as main event loop for the calling thread. - :param int fps: Number of frames per second that the JavaScript will call the function. Setting ``int <=0`` (recommended) uses the browser’s ``requestAnimationFrame`` mechanism to call the function. - :param int simulate_infinite_loop: If true, this function will throw an exception in order to stop execution of the caller. + This function can be called in a pthread, in which case the callback loop will be set up to be called in the context of the calling thread. In order for the loop to work, the calling thread must regularly "yield back" to the browser by exiting from its pthread main function, since the callback will be able to execute only when the calling thread is not executing any other code. This means that running a synchronously blocking main loop is not compatible with the emscripten_set_main_loop() function. + + Since ``requestAnimationFrame()`` API is not available in web workers, when called ``emscripten_set_main_loop()`` in a pthread with ``fps`` <= 0, the effect of syncing up to the display's refresh rate is emulated, and generally will not precisely line up with vsync intervals. + + .. tip:: There can be only *one* main loop function at a time, per thread. To change the main loop function, first :c:func:`cancel ` the current loop, and then call this function to set another. + + .. note:: See :c:func:`emscripten_set_main_loop_expected_blockers`, :c:func:`emscripten_pause_main_loop`, :c:func:`emscripten_resume_main_loop` and :c:func:`emscripten_cancel_main_loop` for information about blocking, pausing, and resuming the main loop of the calling thread. + + .. note:: Calling this function overrides the effect of any previous calls to :c:func:`emscripten_set_main_loop_timing` in the calling thread by applying the timing mode specified by the parameter ``fps``. To specify a different timing mode for the current thread, call the function :c:func:`emscripten_set_main_loop_timing` after setting up the main loop. + + :param em_callback_func func: C function to set as main event loop for the calling thread. + :param int fps: Number of frames per second that the JavaScript will call the function. Setting ``int <=0`` (recommended) uses the browser’s ``requestAnimationFrame`` mechanism to call the function. + :param int simulate_infinite_loop: If true, this function will throw an exception in order to stop execution of the caller. .. c:function:: void emscripten_set_main_loop_arg(em_arg_callback_func func, void *arg, int fps, int simulate_infinite_loop) - Set a C function as the main event loop for the calling thread, passing it user-defined data. - - .. seealso:: The information in :c:func:`emscripten_set_main_loop` also applies to this function. + Set a C function as the main event loop for the calling thread, passing it user-defined data. + + .. seealso:: The information in :c:func:`emscripten_set_main_loop` also applies to this function. + + :param em_arg_callback_func func: C function to set as main event loop. The function signature must have a ``void*`` parameter for passing the ``arg`` value. + :param void* arg: User-defined data passed to the main loop function, untouched by the API itself. + :param int fps: Number of frames per second at which the JavaScript will call the function. Setting ``int <=0`` (recommended) uses the browser’s ``requestAnimationFrame`` mechanism to call the function. + :param int simulate_infinite_loop: If true, this function will throw an exception in order to stop execution of the caller. - :param em_arg_callback_func func: C function to set as main event loop. The function signature must have a ``void*`` parameter for passing the ``arg`` value. - :param void* arg: User-defined data passed to the main loop function, untouched by the API itself. - :param int fps: Number of frames per second at which the JavaScript will call the function. Setting ``int <=0`` (recommended) uses the browser’s ``requestAnimationFrame`` mechanism to call the function. - :param int simulate_infinite_loop: If true, this function will throw an exception in order to stop execution of the caller. - .. c:function:: void emscripten_push_main_loop_blocker(em_arg_callback_func func, void *arg) - void emscripten_push_uncounted_main_loop_blocker(em_arg_callback_func func, void *arg) - - Add a function that **blocks** the main loop for the calling thread. - - The function is added to the back of a queue of events to be blocked; the main loop will not run until all blockers in the queue complete. - - In the "counted" version, blockers are counted (internally) and ``Module.setStatus`` is called with some text to report progress (``setStatus`` is a general hook that a program can define in order to show processing updates). - - - .. note:: - - Main loop blockers block the main loop from running, and can be counted to show progress. In contrast, ``emscripten_async_calls`` are not counted, do not block the main loop, and can fire at specific time in the future. - - :param em_arg_callback_func func: The main loop blocker function. The function signature must have a ``void*`` parameter for passing the ``arg`` value. - :param void* arg: User-defined arguments to pass to the blocker function. - :rtype: void - + void emscripten_push_uncounted_main_loop_blocker(em_arg_callback_func func, void *arg) + + Add a function that **blocks** the main loop for the calling thread. + + The function is added to the back of a queue of events to be blocked; the main loop will not run until all blockers in the queue complete. + + In the "counted" version, blockers are counted (internally) and ``Module.setStatus`` is called with some text to report progress (``setStatus`` is a general hook that a program can define in order to show processing updates). + + + .. note:: + - Main loop blockers block the main loop from running, and can be counted to show progress. In contrast, ``emscripten_async_calls`` are not counted, do not block the main loop, and can fire at specific time in the future. + + :param em_arg_callback_func func: The main loop blocker function. The function signature must have a ``void*`` parameter for passing the ``arg`` value. + :param void* arg: User-defined arguments to pass to the blocker function. + :rtype: void + .. c:function:: void emscripten_pause_main_loop(void) - void emscripten_resume_main_loop(void) + void emscripten_resume_main_loop(void) + + Pause and resume the main loop for the calling thread. - Pause and resume the main loop for the calling thread. + Pausing and resuming the main loop is useful if your app needs to perform some synchronous operation, for example to load a file from the network. It might be wrong to run the main loop before that finishes (the original code assumes that), so you can break the code up into asynchronous callbacks, but you must pause the main loop until they complete. - Pausing and resuming the main loop is useful if your app needs to perform some synchronous operation, for example to load a file from the network. It might be wrong to run the main loop before that finishes (the original code assumes that), so you can break the code up into asynchronous callbacks, but you must pause the main loop until they complete. - - .. note:: These are fairly low-level functions. :c:func:`emscripten_push_main_loop_blocker` (and friends) provide more convenient alternatives. + .. note:: These are fairly low-level functions. :c:func:`emscripten_push_main_loop_blocker` (and friends) provide more convenient alternatives. .. c:function:: void emscripten_cancel_main_loop(void) - Cancels the main event loop for the calling thread. - - See also :c:func:`emscripten_set_main_loop` and :c:func:`emscripten_set_main_loop_arg` for information about setting and using the main loop. + Cancels the main event loop for the calling thread. + + See also :c:func:`emscripten_set_main_loop` and :c:func:`emscripten_set_main_loop_arg` for information about setting and using the main loop. .. note:: This function cancels the main loop, which means that it will no longer be called. No other changes occur to control flow. In particular, if you started the main loop with the ``simulate_infinite_loop`` option, you can still cancel the main loop, but execution will not continue in the code right after setting the main loop (we do not actually run an infinite loop there - that's not possible in JavaScript, so to simulate an infinite loop we halt execution at that stage, and then the next thing that runs is the main loop itself, so it seems like an infinite loop has begun there; canceling the main loop sort of breaks the metaphor). .. c:function:: int emscripten_set_main_loop_timing(int mode, int value) - Specifies the scheduling mode that the main loop tick function of the calling thread will be called with. + Specifies the scheduling mode that the main loop tick function of the calling thread will be called with. - This function can be used to interactively control the rate at which Emscripten runtime drives the main loop specified by calling the function :c:func:`emscripten_set_main_loop`. In native development, this corresponds with the "swap interval" or the "presentation interval" for 3D rendering. The new tick interval specified by this function takes effect immediately on the existing main loop, and this function must be called only after setting up a main loop via :c:func:`emscripten_set_main_loop`. + This function can be used to interactively control the rate at which Emscripten runtime drives the main loop specified by calling the function :c:func:`emscripten_set_main_loop`. In native development, this corresponds with the "swap interval" or the "presentation interval" for 3D rendering. The new tick interval specified by this function takes effect immediately on the existing main loop, and this function must be called only after setting up a main loop via :c:func:`emscripten_set_main_loop`. :param int mode: The timing mode to use. Allowed values are EM_TIMING_SETTIMEOUT, EM_TIMING_RAF and EM_TIMING_SETIMMEDIATE. - :param int value: The timing value to activate for the main loop. This value interpreted differently according to the ``mode`` parameter: + :param int value: The timing value to activate for the main loop. This value interpreted differently according to the ``mode`` parameter: - - If ``mode`` is EM_TIMING_SETTIMEOUT, then ``value`` specifies the number of milliseconds to wait between subsequent ticks to the main loop and updates occur independent of the vsync rate of the display (vsync off). This method uses the JavaScript ``setTimeout`` function to drive the animation. - - If ``mode`` is EM_TIMING_RAF, then updates are performed using the ``requestAnimationFrame`` function (with vsync enabled), and this value is interpreted as a "swap interval" rate for the main loop. The value of ``1`` specifies the runtime that it should render at every vsync (typically 60fps), whereas the value ``2`` means that the main loop callback should be called only every second vsync (30fps). As a general formula, the value ``n`` means that the main loop is updated at every n'th vsync, or at a rate of ``60/n`` for 60Hz displays, and ``120/n`` for 120Hz displays. - - If ``mode`` is EM_TIMING_SETIMMEDIATE, then updates are performed using the ``setImmediate`` function, or if not available, emulated via ``postMessage``. See `setImmediate on MDN ` for more information. Note that this mode is **strongly not recommended** to be used when deploying Emscripten output to the web, since it depends on an unstable web extension that is in draft status, browsers other than IE do not currently support it, and its implementation has been considered controversial in review. + - If ``mode`` is EM_TIMING_SETTIMEOUT, then ``value`` specifies the number of milliseconds to wait between subsequent ticks to the main loop and updates occur independent of the vsync rate of the display (vsync off). This method uses the JavaScript ``setTimeout`` function to drive the animation. + - If ``mode`` is EM_TIMING_RAF, then updates are performed using the ``requestAnimationFrame`` function (with vsync enabled), and this value is interpreted as a "swap interval" rate for the main loop. The value of ``1`` specifies the runtime that it should render at every vsync (typically 60fps), whereas the value ``2`` means that the main loop callback should be called only every second vsync (30fps). As a general formula, the value ``n`` means that the main loop is updated at every n'th vsync, or at a rate of ``60/n`` for 60Hz displays, and ``120/n`` for 120Hz displays. + - If ``mode`` is EM_TIMING_SETIMMEDIATE, then updates are performed using the ``setImmediate`` function, or if not available, emulated via ``postMessage``. See `setImmediate on MDN ` for more information. Note that this mode is **strongly not recommended** to be used when deploying Emscripten output to the web, since it depends on an unstable web extension that is in draft status, browsers other than IE do not currently support it, and its implementation has been considered controversial in review. - :rtype: int - :return: The value 0 is returned on success, and a nonzero value is returned on failure. A failure occurs if there is no main loop active before calling this function. + :rtype: int + :return: The value 0 is returned on success, and a nonzero value is returned on failure. A failure occurs if there is no main loop active before calling this function. - .. note:: Browsers heavily optimize towards using ``requestAnimationFrame`` for animation instead of the other provided modes. Because of that, for best experience across browsers, calling this function with ``mode=EM_TIMING_RAF`` and ``value=1`` will yield best results. Using the JavaScript ``setTimeout`` function is known to cause stutter and generally worse experience than using the ``requestAnimationFrame`` function. + .. note:: Browsers heavily optimize towards using ``requestAnimationFrame`` for animation instead of the other provided modes. Because of that, for best experience across browsers, calling this function with ``mode=EM_TIMING_RAF`` and ``value=1`` will yield best results. Using the JavaScript ``setTimeout`` function is known to cause stutter and generally worse experience than using the ``requestAnimationFrame`` function. - .. note:: There is a functional difference between ``setTimeout`` and ``requestAnimationFrame``: If the user minimizes the browser window or hides your application tab, browsers will typically stop calling ``requestAnimationFrame`` callbacks, but ``setTimeout``-based main loop will continue to be run, although with heavily throttled intervals. See `setTimeout on MDN ` for more information. + .. note:: There is a functional difference between ``setTimeout`` and ``requestAnimationFrame``: If the user minimizes the browser window or hides your application tab, browsers will typically stop calling ``requestAnimationFrame`` callbacks, but ``setTimeout``-based main loop will continue to be run, although with heavily throttled intervals. See `setTimeout on MDN ` for more information. .. c:function:: void emscripten_get_main_loop_timing(int *mode, int *value) - Returns the current main loop timing mode that is in effect. For interpretation of the values, see the documentation of the function :c:func:`emscripten_set_main_loop_timing`. The timing mode is controlled by calling the functions :c:func:`emscripten_set_main_loop_timing` and :c:func:`emscripten_set_main_loop`. + Returns the current main loop timing mode that is in effect. For interpretation of the values, see the documentation of the function :c:func:`emscripten_set_main_loop_timing`. The timing mode is controlled by calling the functions :c:func:`emscripten_set_main_loop_timing` and :c:func:`emscripten_set_main_loop`. :param mode: If not null, the used timing mode is returned here. :type mode: int* :param value: If not null, the used timing value is returned here. :type value: int* - + .. c:function:: void emscripten_set_main_loop_expected_blockers(int num) - Sets the number of blockers that are about to be pushed. - - The number is used for reporting the *relative progress* through a set of blockers, after which the main loop will continue. - - For example, a game might have to run 10 blockers before starting a new level. The operation would first set this value as '10' and then push the 10 blockers. When the 3\ :sup:`rd` blocker (say) completes, progress is displayed as 3/10. - - :param int num: The number of blockers that are about to be pushed. + Sets the number of blockers that are about to be pushed. + + The number is used for reporting the *relative progress* through a set of blockers, after which the main loop will continue. + + For example, a game might have to run 10 blockers before starting a new level. The operation would first set this value as '10' and then push the 10 blockers. When the 3\ :sup:`rd` blocker (say) completes, progress is displayed as 3/10. + + :param int num: The number of blockers that are about to be pushed. + - .. c:function:: void emscripten_async_call(em_arg_callback_func func, void *arg, int millis) - - Call a C function asynchronously, that is, after returning control to the JavaScript event loop. - - This is done by a ``setTimeout``. - - When building natively this becomes a simple direct call, after ``SDL_Delay`` (you must include **SDL.h** for that). - If ``millis`` is negative, the browser's ``requestAnimationFrame`` mechanism is used. + Call a C function asynchronously, that is, after returning control to the JavaScript event loop. + + This is done by a ``setTimeout``. - :param em_arg_callback_func func: The C function to call asynchronously. The function signature must have a ``void*`` parameter for passing the ``arg`` value. - :param void* arg: User-defined argument to pass to the C function. - :param int millis: Timeout before function is called. + When building natively this becomes a simple direct call, after ``SDL_Delay`` (you must include **SDL.h** for that). + + If ``millis`` is negative, the browser's ``requestAnimationFrame`` mechanism is used. + + :param em_arg_callback_func func: The C function to call asynchronously. The function signature must have a ``void*`` parameter for passing the ``arg`` value. + :param void* arg: User-defined argument to pass to the C function. + :param int millis: Timeout before function is called. .. c:function:: void emscripten_exit_with_live_runtime(void) - Exits the program immediately, but leaves the runtime alive so that you can continue to run code later (so global destructors etc., are not run). Note that the runtime is kept alive automatically when you do an asynchronous operation like :c:func:`emscripten_async_call`, so you don't need to call this function for those cases. + Exits the program immediately, but leaves the runtime alive so that you can continue to run code later (so global destructors etc., are not run). Note that the runtime is kept alive automatically when you do an asynchronous operation like :c:func:`emscripten_async_call`, so you don't need to call this function for those cases. + - .. c:function:: void emscripten_force_exit(int status) - Shuts down the runtime and exits (terminates) the program, as if you called ``exit()``. - - The difference is that ``emscripten_force_exit`` will shut down the runtime even if you previously called :c:func:`emscripten_exit_with_live_runtime` or otherwise kept the runtime alive. In other words, this method gives you the option to completely shut down the runtime after it was kept alive beyond the completion of ``main()``. + Shuts down the runtime and exits (terminates) the program, as if you called ``exit()``. + + The difference is that ``emscripten_force_exit`` will shut down the runtime even if you previously called :c:func:`emscripten_exit_with_live_runtime` or otherwise kept the runtime alive. In other words, this method gives you the option to completely shut down the runtime after it was kept alive beyond the completion of ``main()``. - Note that if ``NO_EXIT_RUNTIME`` is set (which it is by default) then the runtime cannot be shut down, as we do not include the code to do so. Build with ``-s NO_EXIT_RUNTIME=0`` if you want to be able to exit the runtime. + Note that if ``NO_EXIT_RUNTIME`` is set (which it is by default) then the runtime cannot be shut down, as we do not include the code to do so. Build with ``-s NO_EXIT_RUNTIME=0`` if you want to be able to exit the runtime. - :param int status: The same as for the *libc* function `exit() `_. + :param int status: The same as for the *libc* function `exit() `_. .. c:function:: double emscripten_get_device_pixel_ratio(void) - Returns the value of ``window.devicePixelRatio``. + Returns the value of ``window.devicePixelRatio``. - :rtype: double - :return: The pixel ratio or 1.0 if not supported. + :rtype: double + :return: The pixel ratio or 1.0 if not supported. .. c:function:: void emscripten_hide_mouse(void) - Hide the OS mouse cursor over the canvas. + Hide the OS mouse cursor over the canvas. - Note that SDL’s ``SDL_ShowCursor`` command shows and hides the SDL cursor, not the OS one. This command is useful to hide the OS cursor if your app draws its own cursor. + Note that SDL’s ``SDL_ShowCursor`` command shows and hides the SDL cursor, not the OS one. This command is useful to hide the OS cursor if your app draws its own cursor. .. c:function:: void emscripten_set_canvas_size(int width, int height) - Resizes the pixel width and height of the ```` element on the Emscripten web page. - - :param int width: New pixel width of canvas element. - :param int height: New pixel height of canvas element. + Resizes the pixel width and height of the ```` element on the Emscripten web page. + + :param int width: New pixel width of canvas element. + :param int height: New pixel height of canvas element. .. c:function:: void emscripten_get_canvas_size(int * width, int * height, int * isFullscreen) - Gets the current pixel width and height of the ```` element as well as whether the canvas is fullscreen or not. - - :param int* width: Pixel width of canvas element. - :param int* height: New pixel height of canvas element. - :param int* isFullscreen: If True (``*int > 0``), ```` is full screen. + Gets the current pixel width and height of the ```` element as well as whether the canvas is fullscreen or not. + + :param int* width: Pixel width of canvas element. + :param int* height: New pixel height of canvas element. + :param int* isFullscreen: If True (``*int > 0``), ```` is full screen. .. c:function:: double emscripten_get_now(void) - Returns the highest-precision representation of the current time that the browser provides. + Returns the highest-precision representation of the current time that the browser provides. + + This uses either ``Date.now`` or ``performance.now``. The result is not an absolute time, and is only meaningful in comparison to other calls to this function. - This uses either ``Date.now`` or ``performance.now``. The result is not an absolute time, and is only meaningful in comparison to other calls to this function. - - :rtype: double - :return: The current time, in milliseconds (ms). + :rtype: double + :return: The current time, in milliseconds (ms). .. c:function:: float emscripten_random(void) - Generates a random number in the range 0-1. This maps to ``Math.random()``. - - :rtype: float - :return: A random number. + Generates a random number in the range 0-1. This maps to ``Math.random()``. + + :rtype: float + :return: A random number. + - .. _emscripten-h-asynchronous-file-system-api: Emscripten Asynchronous File System API @@ -484,240 +510,240 @@ Typedefs .. c:type:: em_async_wget_onload_func - Function pointer type for the ``onload`` callback of :c:func:`emscripten_async_wget_data` (specific values of the parameters documented in that method). + Function pointer type for the ``onload`` callback of :c:func:`emscripten_async_wget_data` (specific values of the parameters documented in that method). - Defined as: :: + Defined as: :: + + typedef void (*em_async_wget_onload_func)(void*, void*, int) - typedef void (*em_async_wget_onload_func)(void*, void*, int) - .. c:type:: em_async_wget2_onload_func - Function pointer type for the ``onload`` callback of :c:func:`emscripten_async_wget2` (specific values of the parameters documented in that method). + Function pointer type for the ``onload`` callback of :c:func:`emscripten_async_wget2` (specific values of the parameters documented in that method). + + Defined as: :: + + typedef void (*em_async_wget2_onload_func)(void*, const char*) - Defined as: :: - typedef void (*em_async_wget2_onload_func)(void*, const char*) - - .. c:type:: em_async_wget2_onstatus_func - Function pointer type for the ``onerror`` and ``onprogress`` callbacks of :c:func:`emscripten_async_wget2` (specific values of the parameters documented in that method). + Function pointer type for the ``onerror`` and ``onprogress`` callbacks of :c:func:`emscripten_async_wget2` (specific values of the parameters documented in that method). + + Defined as: :: + + typedef void (*em_async_wget2_onstatus_func)(void*, int) + - Defined as: :: - typedef void (*em_async_wget2_onstatus_func)(void*, int) - - - .. c:type:: em_async_wget2_data_onload_func - Function pointer type for the ``onload`` callback of :c:func:`emscripten_async_wget2_data` (specific values of the parameters documented in that method). + Function pointer type for the ``onload`` callback of :c:func:`emscripten_async_wget2_data` (specific values of the parameters documented in that method). + + Defined as: :: + + typedef void (*em_async_wget2_data_onload_func)(void*, void *, unsigned*) - Defined as: :: - typedef void (*em_async_wget2_data_onload_func)(void*, void *, unsigned*) - - .. c:type:: em_async_wget2_data_onerror_func - Function pointer type for the ``onerror`` callback of :c:func:`emscripten_async_wget2_data` (specific values of the parameters documented in that method). + Function pointer type for the ``onerror`` callback of :c:func:`emscripten_async_wget2_data` (specific values of the parameters documented in that method). + + Defined as: :: - Defined as: :: + typedef void (*em_async_wget2_data_onerror_func)(void*, int, const char*) - typedef void (*em_async_wget2_data_onerror_func)(void*, int, const char*) - .. c:type:: em_async_wget2_data_onprogress_func - Function pointer type for the ``onprogress`` callback of :c:func:`emscripten_async_wget2_data` (specific values of the parameters documented in that method). + Function pointer type for the ``onprogress`` callback of :c:func:`emscripten_async_wget2_data` (specific values of the parameters documented in that method). - Defined as: :: + Defined as: :: + + typedef void (*em_async_wget2_data_onprogress_func)(void*, int, int) - typedef void (*em_async_wget2_data_onprogress_func)(void*, int, int) - .. c:type:: em_run_preload_plugins_data_onload_func - Function pointer type for the ``onload`` callback of :c:func:`emscripten_run_preload_plugins_data` (specific values of the parameters documented in that method). + Function pointer type for the ``onload`` callback of :c:func:`emscripten_run_preload_plugins_data` (specific values of the parameters documented in that method). + + Defined as: :: - Defined as: :: + typedef void (*em_run_preload_plugins_data_onload_func)(void*, const char*) - typedef void (*em_run_preload_plugins_data_onload_func)(void*, const char*) - Functions --------- .. c:function:: void emscripten_wget(const char* url, const char* file) - Load file from url in *synchronously*. For the asynchronous version, see the :c:func:`emscripten_async_wget`. + Load file from url in *synchronously*. For the asynchronous version, see the :c:func:`emscripten_async_wget`. + + In addition to fetching the URL from the network, preload plugins are executed so that the data is usable in ``IMG_Load`` and so forth (we synchronously do the work to make the browser decode the image or audio etc.). See :ref:`preloading-files` for more information on preloading files. - In addition to fetching the URL from the network, preload plugins are executed so that the data is usable in ``IMG_Load`` and so forth (we synchronously do the work to make the browser decode the image or audio etc.). See :ref:`preloading-plugins` for more information on preloading files. - - This function is blocking; it won't return until all operations are finished. You can then open and read the file if it succeeded. + This function is blocking; it won't return until all operations are finished. You can then open and read the file if it succeeded. - To use this function, you will need to compile your application with the linker flag ``-s ASYNCIFY=1`` + To use this function, you will need to compile your application with the linker flag ``-s ASYNCIFY=1`` + + :param const char* url: The URL to load. + :param const char* file: The name of the file created and loaded from the URL. If the file already exists it will be overwritten. If the destination directory for the file does not exist on the filesystem, it will be created. A relative pathname may be passed, which will be interpreted relative to the current working directory at the time of the call to this function. - :param const char* url: The URL to load. - :param const char* file: The name of the file created and loaded from the URL. If the file already exists it will be overwritten. If the destination directory for the file does not exist on the filesystem, it will be created. A relative pathname may be passed, which will be interpreted relative to the current working directory at the time of the call to this function. - .. c:function:: void emscripten_async_wget(const char* url, const char* file, em_str_callback_func onload, em_str_callback_func onerror) - - Loads a file from a URL asynchronously. - - In addition to fetching the URL from the network, preload plugins are executed so that the data is usable in ``IMG_Load`` and so forth (we asynchronously do the work to make the browser decode the image or audio etc.). See :ref:`preloading-plugins` for more information on preloading files. - - - When the file is ready the ``onload`` callback will be called. If any error occurs ``onerror`` will be called. The callbacks are called with the file as their argument. - - :param const char* url: The URL to load. - :param const char* file: The name of the file created and loaded from the URL. If the file already exists it will be overwritten. If the destination directory for the file does not exist on the filesystem, it will be created. A relative pathname may be passed, which will be interpreted relative to the current working directory at the time of the call to this function. - :param em_str_callback_func onload: Callback on successful load of the file. The callback function parameter value is: - - - *(const char*)* : The name of the ``file`` that was loaded from the URL. - - :param em_str_callback_func onerror: Callback in the event of failure. The callback function parameter value is: - - - *(const char*)* : The name of the ``file`` that failed to load from the URL. - - - + + Loads a file from a URL asynchronously. + + In addition to fetching the URL from the network, preload plugins are executed so that the data is usable in ``IMG_Load`` and so forth (we asynchronously do the work to make the browser decode the image or audio etc.). See :ref:`preloading-files` for more information on preloading files. + + + When the file is ready the ``onload`` callback will be called. If any error occurs ``onerror`` will be called. The callbacks are called with the file as their argument. + + :param const char* url: The URL to load. + :param const char* file: The name of the file created and loaded from the URL. If the file already exists it will be overwritten. If the destination directory for the file does not exist on the filesystem, it will be created. A relative pathname may be passed, which will be interpreted relative to the current working directory at the time of the call to this function. + :param em_str_callback_func onload: Callback on successful load of the file. The callback function parameter value is: + + - *(const char*)* : The name of the ``file`` that was loaded from the URL. + + :param em_str_callback_func onerror: Callback in the event of failure. The callback function parameter value is: + + - *(const char*)* : The name of the ``file`` that failed to load from the URL. + + + .. c:function:: void emscripten_async_wget_data(const char* url, void *arg, em_async_wget_onload_func onload, em_arg_callback_func onerror) - - Loads a buffer from a URL asynchronously. - - This is the "data" version of :c:func:`emscripten_async_wget`. - - Instead of writing to a file, this function writes to a buffer directly in memory. This avoids the overhead of using the emulated file system; note however that since files are not used, it cannot run preload plugins to set things up for ``IMG_Load`` and so forth (``IMG_Load`` etc. work on files). - - When the file is ready then the ``onload`` callback will be called. If any error occurred ``onerror`` will be called. - - :param url: The URL of the file to load. - :type url: const char* - :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. - :param em_async_wget_onload_func onload: Callback on successful load of the URL into the buffer. The callback function parameter values are: - - - *(void*)* : Equal to ``arg`` (user defined data). - - *(void*)* : A pointer to a buffer with the data. Note that, as with the worker API, the data buffer only lives during the callback; it must be used or copied during that time. - - *(int)* : The size of the buffer, in bytes. - - :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: - - - *(void*)* : Equal to ``arg`` (user defined data). + + Loads a buffer from a URL asynchronously. + + This is the "data" version of :c:func:`emscripten_async_wget`. + + Instead of writing to a file, this function writes to a buffer directly in memory. This avoids the overhead of using the emulated file system; note however that since files are not used, it cannot run preload plugins to set things up for ``IMG_Load`` and so forth (``IMG_Load`` etc. work on files). + + When the file is ready then the ``onload`` callback will be called. If any error occurred ``onerror`` will be called. + + :param url: The URL of the file to load. + :type url: const char* + :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. + :param em_async_wget_onload_func onload: Callback on successful load of the URL into the buffer. The callback function parameter values are: + + - *(void*)* : Equal to ``arg`` (user defined data). + - *(void*)* : A pointer to a buffer with the data. Note that, as with the worker API, the data buffer only lives during the callback; it must be used or copied during that time. + - *(int)* : The size of the buffer, in bytes. + + :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: + + - *(void*)* : Equal to ``arg`` (user defined data). .. c:function:: int emscripten_async_wget2(const char* url, const char* file, const char* requesttype, const char* param, void *arg, em_async_wget2_onload_func onload, em_async_wget2_onstatus_func onerror, em_async_wget2_onstatus_func onprogress) - - Loads a file from a URL asynchronously. - - This is an **experimental** "more feature-complete" version of :c:func:`emscripten_async_wget`. - - In addition to fetching the URL from the network, preload plugins are executed so that the data is usable in ``IMG_Load`` and so forth (we asynchronously do the work to make the browser decode the image, audio, etc.). See :ref:`preloading-plugins` for more information on preloading files. - - - When the file is ready the ``onload`` callback will be called with the object pointers given in ``arg`` and ``file``. During the download the ``onprogress`` callback is called. - - :param url: The URL of the file to load. - :type url: const char* - :param file: The name of the file created and loaded from the URL. If the file already exists it will be overwritten. If the destination directory for the file does not exist on the filesystem, it will be created. A relative pathname may be passed, which will be interpreted relative to the current working directory at the time of the call to this function. - :type file: const char* - :param requesttype: 'GET' or 'POST'. - :type requesttype: const char* - :param param: Request parameters for POST requests (see ``requesttype``). The parameters are specified in the same way as they would be in the URL for an equivalent GET request: e.g. ``key=value&key2=value2``. - :type param: const char* - :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. - :param em_async_wget2_onload_func onload: Callback on successful load of the file. The callback function parameter values are: - - - *(void*)* : Equal to ``arg`` (user defined data). - - *(const char*)* : The ``file`` passed to the original call. - - :param em_async_wget2_onstatus_func onerror: Callback in the event of failure. The callback function parameter values are: - - - *(void*)* : Equal to ``arg`` (user defined data). - - *(int)* : The HTTP status code. - - :param em_async_wget2_onstatus_func onprogress: Callback during load of the file. The callback function parameter values are: - - - *(void*)* : Equal to ``arg`` (user defined data). - - *(int)* : The progress (percentage completed). - - :returns: A handle to request (``int``) that can be used to :c:func:`abort ` the request. - - + + Loads a file from a URL asynchronously. + + This is an **experimental** "more feature-complete" version of :c:func:`emscripten_async_wget`. + + In addition to fetching the URL from the network, preload plugins are executed so that the data is usable in ``IMG_Load`` and so forth (we asynchronously do the work to make the browser decode the image, audio, etc.). See :ref:`preloading-files` for more information on preloading files. + + + When the file is ready the ``onload`` callback will be called with the object pointers given in ``arg`` and ``file``. During the download the ``onprogress`` callback is called. + + :param url: The URL of the file to load. + :type url: const char* + :param file: The name of the file created and loaded from the URL. If the file already exists it will be overwritten. If the destination directory for the file does not exist on the filesystem, it will be created. A relative pathname may be passed, which will be interpreted relative to the current working directory at the time of the call to this function. + :type file: const char* + :param requesttype: 'GET' or 'POST'. + :type requesttype: const char* + :param param: Request parameters for POST requests (see ``requesttype``). The parameters are specified in the same way as they would be in the URL for an equivalent GET request: e.g. ``key=value&key2=value2``. + :type param: const char* + :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. + :param em_async_wget2_onload_func onload: Callback on successful load of the file. The callback function parameter values are: + + - *(void*)* : Equal to ``arg`` (user defined data). + - *(const char*)* : The ``file`` passed to the original call. + + :param em_async_wget2_onstatus_func onerror: Callback in the event of failure. The callback function parameter values are: + + - *(void*)* : Equal to ``arg`` (user defined data). + - *(int)* : The HTTP status code. + + :param em_async_wget2_onstatus_func onprogress: Callback during load of the file. The callback function parameter values are: + + - *(void*)* : Equal to ``arg`` (user defined data). + - *(int)* : The progress (percentage completed). + + :returns: A handle to request (``int``) that can be used to :c:func:`abort ` the request. + + .. c:function:: int emscripten_async_wget2_data(const char* url, const char* requesttype, const char* param, void *arg, int free, em_async_wget2_data_onload_func onload, em_async_wget2_data_onerror_func onerror, em_async_wget2_data_onprogress_func onprogress) - - Loads a buffer from a URL asynchronously. - - This is the "data" version of :c:func:`emscripten_async_wget2`. It is an **experimental** "more feature complete" version of :c:func:`emscripten_async_wget_data`. - - Instead of writing to a file, this function writes to a buffer directly in memory. This avoids the overhead of using the emulated file system; note however that since files are not used, it cannot run preload plugins to set things up for ``IMG_Load`` and so forth (``IMG_Load`` etc. work on files). - - When the file is ready the ``onload`` callback will be called with the object pointers given in ``arg``, a pointer to the buffer in memory, and an unsigned integer containing the size of the buffer. During the download the ``onprogress`` callback is called with progress information. If an error occurs, ``onerror`` will be called with the HTTP status code and a string containing the status description. - - :param url: The URL of the file to load. - :type url: const char* - :param requesttype: 'GET' or 'POST'. - :type requesttype: const char* - :param param: Request parameters for POST requests (see ``requesttype``). The parameters are specified in the same way as they would be in the URL for an equivalent GET request: e.g. ``key=value&key2=value2``. - :type param: const char* - :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. - :param int free: Tells the runtime whether to free the returned buffer after ``onload`` is complete. If ``false`` freeing the buffer is the receiver's responsibility. - :type free: int - :param em_async_wget2_data_onload_func onload: Callback on successful load of the file. The callback function parameter values are: - - - *(void*)* : Equal to ``arg`` (user defined data). - - *(void*)* : A pointer to the buffer in memory. - - *(unsigned)* : The size of the buffer (in bytes). - - :param em_async_wget2_data_onerror_func onerror: Callback in the event of failure. The callback function parameter values are: - - - *(void*)* : Equal to ``arg`` (user defined data). - - *(int)* : The HTTP error code. - - *(const char*)* : A string with the status description. - - :param em_async_wget2_data_onprogress_func onprogress: Callback called (regularly) during load of the file to update progress. The callback function parameter values are: - - - *(void*)* : Equal to ``arg`` (user defined data). - - *(int)* : The number of bytes loaded. - - *(int)* : The total size of the data in bytes, or zero if the size is unavailable. - - :returns: A handle to request (``int``) that can be used to :c:func:`abort ` the request. + + Loads a buffer from a URL asynchronously. + + This is the "data" version of :c:func:`emscripten_async_wget2`. It is an **experimental** "more feature complete" version of :c:func:`emscripten_async_wget_data`. + + Instead of writing to a file, this function writes to a buffer directly in memory. This avoids the overhead of using the emulated file system; note however that since files are not used, it cannot run preload plugins to set things up for ``IMG_Load`` and so forth (``IMG_Load`` etc. work on files). + + When the file is ready the ``onload`` callback will be called with the object pointers given in ``arg``, a pointer to the buffer in memory, and an unsigned integer containing the size of the buffer. During the download the ``onprogress`` callback is called with progress information. If an error occurs, ``onerror`` will be called with the HTTP status code and a string containing the status description. + + :param url: The URL of the file to load. + :type url: const char* + :param requesttype: 'GET' or 'POST'. + :type requesttype: const char* + :param param: Request parameters for POST requests (see ``requesttype``). The parameters are specified in the same way as they would be in the URL for an equivalent GET request: e.g. ``key=value&key2=value2``. + :type param: const char* + :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. + :param int free: Tells the runtime whether to free the returned buffer after ``onload`` is complete. If ``false`` freeing the buffer is the receiver's responsibility. + :type free: int + :param em_async_wget2_data_onload_func onload: Callback on successful load of the file. The callback function parameter values are: + + - *(void*)* : Equal to ``arg`` (user defined data). + - *(void*)* : A pointer to the buffer in memory. + - *(unsigned)* : The size of the buffer (in bytes). + + :param em_async_wget2_data_onerror_func onerror: Callback in the event of failure. The callback function parameter values are: + + - *(void*)* : Equal to ``arg`` (user defined data). + - *(int)* : The HTTP error code. + - *(const char*)* : A string with the status description. + + :param em_async_wget2_data_onprogress_func onprogress: Callback called (regularly) during load of the file to update progress. The callback function parameter values are: + + - *(void*)* : Equal to ``arg`` (user defined data). + - *(int)* : The number of bytes loaded. + - *(int)* : The total size of the data in bytes, or zero if the size is unavailable. + + :returns: A handle to request (``int``) that can be used to :c:func:`abort ` the request. .. c:function:: void emscripten_async_wget2_abort(int handle) - Abort an asynchronous request raised using :c:func:`emscripten_async_wget2` or :c:func:`emscripten_async_wget2_data`. - - :param int handle: A handle to request to be aborted. + Abort an asynchronous request raised using :c:func:`emscripten_async_wget2` or :c:func:`emscripten_async_wget2_data`. + + :param int handle: A handle to request to be aborted. .. c:function:: void emscripten_run_preload_plugins_data(char* data, int size, const char *suffix, void *arg, em_run_preload_plugins_data_onload_func onload, em_arg_callback_func onerror) - - Runs preload plugins on a buffer of data asynchronously. This is a "data" version of :c:func:`emscripten_run_preload_plugins`, which receives raw data as input instead of a filename (this can prevent the need to write data to a file first). See :ref:`preloading-plugins` for more information on preload plugins. - - - When file is loaded then the ``onload`` callback will be called. If any error occurs ``onerror`` will be called. - - ``onload`` also receives a second parameter, which is a 'fake' filename which you can pass into ``IMG_Load`` (it is not an actual file, but it identifies this image for ``IMG_Load`` to be able to process it). Note that the user of this API is responsible for ``free()`` ing the memory allocated for the fake filename. - - :param char* data: The buffer of data to process. - :param suffix: The file suffix, e.g. 'png' or 'jpg'. - :type suffix: const char* - :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. - :param em_run_preload_plugins_data_onload_func onload: Callback on successful processing of the data. The callback function parameter values are: - - - *(void*)* : Equal to ``arg`` (user defined data). - - *(const char*)* : A 'fake' filename which you can pass into ``IMG_Load``. See above for more information. - - :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter value is: - - - *(void*)* : Equal to ``arg`` (user defined data). + + Runs preload plugins on a buffer of data asynchronously. This is a "data" version of :c:func:`emscripten_run_preload_plugins`, which receives raw data as input instead of a filename (this can prevent the need to write data to a file first). See :ref:`preloading-files` for more information on preload plugins. + + + When file is loaded then the ``onload`` callback will be called. If any error occurs ``onerror`` will be called. + + ``onload`` also receives a second parameter, which is a 'fake' filename which you can pass into ``IMG_Load`` (it is not an actual file, but it identifies this image for ``IMG_Load`` to be able to process it). Note that the user of this API is responsible for ``free()`` ing the memory allocated for the fake filename. + + :param char* data: The buffer of data to process. + :param suffix: The file suffix, e.g. 'png' or 'jpg'. + :type suffix: const char* + :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. + :param em_run_preload_plugins_data_onload_func onload: Callback on successful processing of the data. The callback function parameter values are: + + - *(void*)* : Equal to ``arg`` (user defined data). + - *(const char*)* : A 'fake' filename which you can pass into ``IMG_Load``. See above for more information. + + :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter value is: + + - *(void*)* : Equal to ``arg`` (user defined data). Emscripten Asynchronous IndexedDB API @@ -726,118 +752,118 @@ Emscripten Asynchronous IndexedDB API IndexedDB is a browser API that lets you store data persistently, that is, you can save data there and load it later when the user re-visits the web page. IDBFS provides one way to use IndexedDB, through the Emscripten filesystem layer. The ``emscripten_idb_*`` methods listed here provide an alternative API, directly to IndexedDB, thereby avoiding the overhead of the filesystem layer. .. c:function:: void emscripten_idb_async_load(const char *db_name, const char *file_id, void* arg, em_async_wget_onload_func onload, em_arg_callback_func onerror) - - Loads data from local IndexedDB storage asynchronously. This allows use of persistent data, without the overhead of the filesystem layer. - - When the data is ready then the ``onload`` callback will be called. If any error occurred ``onerror`` will be called. - - :param db_name: The IndexedDB database from which to load. - :param file_id: The identifier of the data to load. - :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. - :param em_async_wget_onload_func onload: Callback on successful load of the URL into the buffer. The callback function parameter values are: - - - *(void*)* : Equal to ``arg`` (user defined data). - - *(void*)* : A pointer to a buffer with the data. Note that, as with the worker API, the data buffer only lives during the callback; it must be used or copied during that time. - - *(int)* : The size of the buffer, in bytes. - - :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: - - - *(void*)* : Equal to ``arg`` (user defined data). + + Loads data from local IndexedDB storage asynchronously. This allows use of persistent data, without the overhead of the filesystem layer. + + When the data is ready then the ``onload`` callback will be called. If any error occurred ``onerror`` will be called. + + :param db_name: The IndexedDB database from which to load. + :param file_id: The identifier of the data to load. + :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. + :param em_async_wget_onload_func onload: Callback on successful load of the URL into the buffer. The callback function parameter values are: + + - *(void*)* : Equal to ``arg`` (user defined data). + - *(void*)* : A pointer to a buffer with the data. Note that, as with the worker API, the data buffer only lives during the callback; it must be used or copied during that time. + - *(int)* : The size of the buffer, in bytes. + + :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: + + - *(void*)* : Equal to ``arg`` (user defined data). .. c:function:: void emscripten_idb_async_store(const char *db_name, const char *file_id, void* ptr, int num, void* arg, em_arg_callback_func onstore, em_arg_callback_func onerror); - - Stores data to local IndexedDB storage asynchronously. This allows use of persistent data, without the overhead of the filesystem layer. - - When the data has been stored then the ``onstore`` callback will be called. If any error occurred ``onerror`` will be called. - - :param db_name: The IndexedDB database from which to load. - :param file_id: The identifier of the data to load. - :param ptr: A pointer to the data to store. - :param num: How many bytes to store. - :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. - :param em_arg_callback_func onstore: Callback on successful store of the data buffer to the URL. The callback function parameter values are: - - - *(void*)* : Equal to ``arg`` (user defined data). - - :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: - - - *(void*)* : Equal to ``arg`` (user defined data). - + + Stores data to local IndexedDB storage asynchronously. This allows use of persistent data, without the overhead of the filesystem layer. + + When the data has been stored then the ``onstore`` callback will be called. If any error occurred ``onerror`` will be called. + + :param db_name: The IndexedDB database from which to load. + :param file_id: The identifier of the data to load. + :param ptr: A pointer to the data to store. + :param num: How many bytes to store. + :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. + :param em_arg_callback_func onstore: Callback on successful store of the data buffer to the URL. The callback function parameter values are: + + - *(void*)* : Equal to ``arg`` (user defined data). + + :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: + + - *(void*)* : Equal to ``arg`` (user defined data). + .. c:function:: void emscripten_idb_async_delete(const char *db_name, const char *file_id, void* arg, em_arg_callback_func ondelete, em_arg_callback_func onerror) - - Deletes data from local IndexedDB storage asynchronously. - - When the data has been deleted then the ``ondelete`` callback will be called. If any error occurred ``onerror`` will be called. - - :param db_name: The IndexedDB database. - :param file_id: The identifier of the data. - :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. - :param em_arg_callback_func ondelete: Callback on successful delete - - - *(void*)* : Equal to ``arg`` (user defined data). - - :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: - - - *(void*)* : Equal to ``arg`` (user defined data). + + Deletes data from local IndexedDB storage asynchronously. + + When the data has been deleted then the ``ondelete`` callback will be called. If any error occurred ``onerror`` will be called. + + :param db_name: The IndexedDB database. + :param file_id: The identifier of the data. + :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. + :param em_arg_callback_func ondelete: Callback on successful delete + + - *(void*)* : Equal to ``arg`` (user defined data). + + :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: + + - *(void*)* : Equal to ``arg`` (user defined data). .. c:function:: void emscripten_idb_async_exists(const char *db_name, const char *file_id, void* arg, em_idb_exists_func oncheck, em_arg_callback_func onerror) - - Checks if data with a certain ID exists in the local IndexedDB storage asynchronously. - - When the data has been checked then the ``oncheck`` callback will be called. If any error occurred ``onerror`` will be called. - - :param db_name: The IndexedDB database. - :param file_id: The identifier of the data. - :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. - :param em_idb_exists_func oncheck: Callback on successful check, with arguments - - *(void*)* : Equal to ``arg`` (user defined data). - - *int* : Whether the file exists or not. - - :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: - - - *(void*)* : Equal to ``arg`` (user defined data). + Checks if data with a certain ID exists in the local IndexedDB storage asynchronously. + + When the data has been checked then the ``oncheck`` callback will be called. If any error occurred ``onerror`` will be called. + + :param db_name: The IndexedDB database. + :param file_id: The identifier of the data. + :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. + :param em_idb_exists_func oncheck: Callback on successful check, with arguments + + - *(void*)* : Equal to ``arg`` (user defined data). + - *int* : Whether the file exists or not. + + :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: + + - *(void*)* : Equal to ``arg`` (user defined data). .. c:function:: int emscripten_run_preload_plugins(const char* file, em_str_callback_func onload, em_str_callback_func onerror) - - Runs preload plugins on a file asynchronously. It works on file data already present and performs any required asynchronous operations available as preload plugins, such as decoding images for use in ``IMG_Load``, or decoding audio for use in ``Mix_LoadWAV``. See :ref:`preloading-plugins` for more information on preloading plugins. - - Once the operations are complete, the ``onload`` callback will be called. If any error occurs ``onerror`` will be called. The callbacks are called with the file as their argument. + Runs preload plugins on a file asynchronously. It works on file data already present and performs any required asynchronous operations available as preload plugins, such as decoding images for use in ``IMG_Load``, or decoding audio for use in ``Mix_LoadWAV``. See :ref:`preloading-files` for more information on preloading plugins. - :param file: The name of the file to process. - :type file: const char* - :param em_str_callback_func onload: Callback on successful processing of the file. The callback function parameter value is: - - - *(const char*)* : The name of the ``file`` that was processed. - - :param em_str_callback_func onerror: Callback in the event of failure. The callback function parameter value is: - - - *(const char*)* : The name of the ``file`` for which the operation failed. - - :return: 0 if successful, -1 if the file does not exist - :rtype: int + + Once the operations are complete, the ``onload`` callback will be called. If any error occurs ``onerror`` will be called. The callbacks are called with the file as their argument. + + :param file: The name of the file to process. + :type file: const char* + :param em_str_callback_func onload: Callback on successful processing of the file. The callback function parameter value is: + + - *(const char*)* : The name of the ``file`` that was processed. + + :param em_str_callback_func onerror: Callback in the event of failure. The callback function parameter value is: + + - *(const char*)* : The name of the ``file`` for which the operation failed. + + :return: 0 if successful, -1 if the file does not exist + :rtype: int Compiling -================ +========= .. c:macro:: EMSCRIPTEN_KEEPALIVE - - Forces LLVM to not dead-code-eliminate a function. - - This also exports the function, as if you added it to :ref:`EXPORTED_FUNCTIONS `. - - For example: :: - void EMSCRIPTEN_KEEPALIVE my_function() { printf("I am being kept alive\n"); } + Forces LLVM to not dead-code-eliminate a function. + + This also exports the function, as if you added it to :ref:`EXPORTED_FUNCTIONS `. + + For example: :: + + void EMSCRIPTEN_KEEPALIVE my_function() { printf("I am being kept alive\n"); } + - Worker API ========== @@ -846,91 +872,91 @@ Typedefs .. c:var:: int worker_handle - A wrapper around web workers that lets you create workers and communicate with them. - - Note that the current API is mainly focused on a main thread that sends jobs to workers and waits for responses, i.e., in an asymmetrical manner, there is no current API to send a message without being asked for it from a worker to the main thread. + A wrapper around web workers that lets you create workers and communicate with them. + + Note that the current API is mainly focused on a main thread that sends jobs to workers and waits for responses, i.e., in an asymmetrical manner, there is no current API to send a message without being asked for it from a worker to the main thread. .. c:type:: em_worker_callback_func - Function pointer type for the callback from :c:func:`emscripten_call_worker` (specific values of the parameters documented in that method). + Function pointer type for the callback from :c:func:`emscripten_call_worker` (specific values of the parameters documented in that method). + + Defined as: :: - Defined as: :: + typedef void (*em_worker_callback_func)(char*, int, void*) - typedef void (*em_worker_callback_func)(char*, int, void*) - Functions --------- .. c:function:: worker_handle emscripten_create_worker(const char * url) - - Creates a worker. - - A worker must be compiled separately from the main program, and with the ``BUILD_AS_WORKER`` flag set to 1. - - :param url: The URL of the worker script. - :type url: const char* - :return: A handle to the newly created worker. - :rtype: worker_handle - - + + Creates a worker. + + A worker must be compiled separately from the main program, and with the ``BUILD_AS_WORKER`` flag set to 1. + + :param url: The URL of the worker script. + :type url: const char* + :return: A handle to the newly created worker. + :rtype: worker_handle + + .. c:function:: void emscripten_destroy_worker(worker_handle worker) - Destroys a worker. See :c:func:`emscripten_create_worker` - - :param worker_handle worker: A handle to the worker to be destroyed. + Destroys a worker. See :c:func:`emscripten_create_worker` + + :param worker_handle worker: A handle to the worker to be destroyed. + - .. c:function:: void emscripten_call_worker(worker_handle worker, const char *funcname, char *data, int size, em_worker_callback_func callback, void *arg) - Asynchronously calls a worker. - - The worker function will be called with two parameters: a data pointer, and a size. The data block defined by the pointer and size exists only during the callback: **it cannot be relied upon afterwards**. If you need to keep some of that information outside the callback, then it needs to be copied to a safe location. - - The called worker function can return data, by calling :c:func:`emscripten_worker_respond`. When the worker is called, if a callback was given it will be called with three arguments: a data pointer, a size, and an argument that was provided when calling :c:func:`emscripten_call_worker` (to more easily associate callbacks to calls). The data block defined by the data pointer and size behave like the data block in the worker function — it exists only during the callback. - - :param worker_handle worker: A handle to the worker to be called. - :param funcname: The name of the function in the worker. The function must be a C function (so no C++ name mangling), and must be exported (:ref:`EXPORTED_FUNCTIONS `). - :type funcname: const char* - :param char* data: The address of a block of memory to copy over. - :param int size: The size of the block of memory. - :param em_worker_callback_func callback: Worker callback with the response. This can be ``null``. The callback function parameter values are: - - - *(char*)* : The ``data`` pointer provided in :c:func:`emscripten_call_worker`. - - *(int)* : The ``size`` of the block of data. - - *(void*)* : Equal to ``arg`` (user defined data). - - :param void* arg: An argument (user data) to be passed to the callback + Asynchronously calls a worker. + + The worker function will be called with two parameters: a data pointer, and a size. The data block defined by the pointer and size exists only during the callback: **it cannot be relied upon afterwards**. If you need to keep some of that information outside the callback, then it needs to be copied to a safe location. + + The called worker function can return data, by calling :c:func:`emscripten_worker_respond`. When the worker is called, if a callback was given it will be called with three arguments: a data pointer, a size, and an argument that was provided when calling :c:func:`emscripten_call_worker` (to more easily associate callbacks to calls). The data block defined by the data pointer and size behave like the data block in the worker function — it exists only during the callback. + + :param worker_handle worker: A handle to the worker to be called. + :param funcname: The name of the function in the worker. The function must be a C function (so no C++ name mangling), and must be exported (:ref:`EXPORTED_FUNCTIONS `). + :type funcname: const char* + :param char* data: The address of a block of memory to copy over. + :param int size: The size of the block of memory. + :param em_worker_callback_func callback: Worker callback with the response. This can be ``null``. The callback function parameter values are: + + - *(char*)* : The ``data`` pointer provided in :c:func:`emscripten_call_worker`. + - *(int)* : The ``size`` of the block of data. + - *(void*)* : Equal to ``arg`` (user defined data). + + :param void* arg: An argument (user data) to be passed to the callback .. c:function:: void emscripten_worker_respond(char *data, int size) - void emscripten_worker_respond_provisionally(char *data, int size) + void emscripten_worker_respond_provisionally(char *data, int size) + + Sends a response when in a worker call (that is, when called by the main thread using :c:func:`emscripten_call_worker`). + + Both functions post a message back to the thread which called the worker. The :c:func:`emscripten_worker_respond_provisionally` variant can be invoked multiple times, which will queue up messages to be posted to the worker’s creator. Eventually, the _respond variant must be invoked, which will disallow further messages and free framework resources previously allocated for this worker call. - Sends a response when in a worker call (that is, when called by the main thread using :c:func:`emscripten_call_worker`). - - Both functions post a message back to the thread which called the worker. The :c:func:`emscripten_worker_respond_provisionally` variant can be invoked multiple times, which will queue up messages to be posted to the worker’s creator. Eventually, the _respond variant must be invoked, which will disallow further messages and free framework resources previously allocated for this worker call. + .. note:: Calling the provisional version is optional, but you must call the non-provisional version to avoid leaks. - .. note:: Calling the provisional version is optional, but you must call the non-provisional version to avoid leaks. + :param char* data: The message to be posted. + :param int size: The size of the message, in bytes. - :param char* data: The message to be posted. - :param int size: The size of the message, in bytes. - .. c:function:: int emscripten_get_worker_queue_size(worker_handle worker) - Checks how many responses are being waited for from a worker. - - This only counts calls to :c:func:`emscripten_call_worker` that had a callback (calls with null callbacks are ignored), and where the response has not yet been received. It is a simple way to check on the status of the worker to see how busy it is, and do basic decisions about throttling. - - :param worker_handle worker: The handle to the relevant worker. - :return: The number of responses waited on from a worker. - :rtype: int + Checks how many responses are being waited for from a worker. + + This only counts calls to :c:func:`emscripten_call_worker` that had a callback (calls with null callbacks are ignored), and where the response has not yet been received. It is a simple way to check on the status of the worker to see how busy it is, and do basic decisions about throttling. + + :param worker_handle worker: The handle to the relevant worker. + :return: The number of responses waited on from a worker. + :rtype: int + - Logging utilities ================= @@ -939,124 +965,124 @@ Defines .. c:macro:: EM_LOG_CONSOLE - If specified, logs directly to the browser console/inspector window. If not specified, logs via the application Module. + If specified, logs directly to the browser console/inspector window. If not specified, logs via the application Module. .. c:macro:: EM_LOG_WARN - If specified, prints a warning message. + If specified, prints a warning message. .. c:macro:: EM_LOG_ERROR - If specified, prints an error message. If neither :c:data:`EM_LOG_WARN` or :c:data:`EM_LOG_ERROR` is specified, an info message is printed. :c:data:`EM_LOG_WARN` and :c:data:`EM_LOG_ERROR` are mutually exclusive. + If specified, prints an error message. If neither :c:data:`EM_LOG_WARN` or :c:data:`EM_LOG_ERROR` is specified, an info message is printed. :c:data:`EM_LOG_WARN` and :c:data:`EM_LOG_ERROR` are mutually exclusive. .. c:macro:: EM_LOG_C_STACK - If specified, prints a call stack that contains file names referring to original C sources using source map information. + If specified, prints a call stack that contains file names referring to original C sources using source map information. .. c:macro:: EM_LOG_JS_STACK - If specified, prints a call stack that contains file names referring to lines in the built .js/.html file along with the message. The flags :c:data:`EM_LOG_C_STACK` and :c:data:`EM_LOG_JS_STACK` can be combined to output both untranslated and translated file and line information. - + If specified, prints a call stack that contains file names referring to lines in the built .js/.html file along with the message. The flags :c:data:`EM_LOG_C_STACK` and :c:data:`EM_LOG_JS_STACK` can be combined to output both untranslated and translated file and line information. + .. c:macro:: EM_LOG_DEMANGLE - If specified, C/C++ function names are de-mangled before printing. Otherwise, the mangled post-compilation JavaScript function names are displayed. + If specified, C/C++ function names are de-mangled before printing. Otherwise, the mangled post-compilation JavaScript function names are displayed. .. c:macro:: EM_LOG_NO_PATHS - If specified, the pathnames of the file information in the call stack will be omitted. + If specified, the pathnames of the file information in the call stack will be omitted. .. c:macro:: EM_LOG_FUNC_PARAMS - If specified, prints out the actual values of the parameters the functions were invoked with. - + If specified, prints out the actual values of the parameters the functions were invoked with. + Functions --------- .. c:function:: int emscripten_get_compiler_setting(const char *name) - Returns the value of a compiler setting. - - For example, to return the integer representing the value of ``PRECISE_F32`` during compilation: :: - - emscripten_get_compiler_setting("PRECISE_F32") + Returns the value of a compiler setting. + + For example, to return the integer representing the value of ``PRECISE_F32`` during compilation: :: + + emscripten_get_compiler_setting("PRECISE_F32") - For values containing anything other than an integer, a string is returned (you will need to cast the ``int`` return value to a ``char*``). + For values containing anything other than an integer, a string is returned (you will need to cast the ``int`` return value to a ``char*``). - Some useful things this can do is provide the version of Emscripten (“EMSCRIPTEN_VERSION”), the optimization level (“OPT_LEVEL”), debug level (“DEBUG_LEVEL”), etc. + Some useful things this can do is provide the version of Emscripten (“EMSCRIPTEN_VERSION”), the optimization level (“OPT_LEVEL”), debug level (“DEBUG_LEVEL”), etc. - For this command to work, you must build with the following compiler option (as we do not want to increase the build size with this metadata): :: - - -s RETAIN_COMPILER_SETTINGS=1 + For this command to work, you must build with the following compiler option (as we do not want to increase the build size with this metadata): :: + + -s RETAIN_COMPILER_SETTINGS=1 + + :param name: The compiler setting to return. + :type name: const char* + :returns: The value of the specified setting. Note that for values other than an integer, a string is returned (cast the ``int`` return value to a ``char*``). + :rtype: int - :param name: The compiler setting to return. - :type name: const char* - :returns: The value of the specified setting. Note that for values other than an integer, a string is returned (cast the ``int`` return value to a ``char*``). - :rtype: int - .. c:function:: void emscripten_debugger() - Emits ``debugger``. + Emits ``debugger``. - This is inline in the code, which tells the JavaScript engine to invoke the debugger if it gets there. + This is inline in the code, which tells the JavaScript engine to invoke the debugger if it gets there. .. c:function:: void emscripten_log(int flags, ...) - Prints out a message to the console, optionally with the callstack information. + Prints out a message to the console, optionally with the callstack information. - :param int flags: A binary OR of items from the list of :c:data:`EM_LOG_xxx ` flags that specify printing options. - :param ...: A ``printf``-style "format, ..." parameter list that is parsed according to the ``printf`` formatting rules. + :param int flags: A binary OR of items from the list of :c:data:`EM_LOG_xxx ` flags that specify printing options. + :param ...: A ``printf``-style "format, ..." parameter list that is parsed according to the ``printf`` formatting rules. .. c:function:: int emscripten_get_callstack(int flags, char *out, int maxbytes) - Programmatically obtains the current callstack. - - To query the amount of bytes needed for a callstack without writing it, pass 0 to ``out`` and ``maxbytes``, in which case the function will return the number of bytes (including the terminating zero) that will be needed to hold the full callstack. Note that this might be fully accurate since subsequent calls will carry different line numbers, so it is best to allocate a few bytes extra to be safe. + Programmatically obtains the current callstack. + + To query the amount of bytes needed for a callstack without writing it, pass 0 to ``out`` and ``maxbytes``, in which case the function will return the number of bytes (including the terminating zero) that will be needed to hold the full callstack. Note that this might be fully accurate since subsequent calls will carry different line numbers, so it is best to allocate a few bytes extra to be safe. - :param int flags: A binary OR of items from the list of :c:data:`EM_LOG_xxx ` flags that specify printing options. The flags :c:data:`EM_LOG_CONSOLE`, :c:data:`EM_LOG_WARN` and :c:data:`EM_LOG_ERROR` do not apply in this function and are ignored. - :param char* out: A pointer to a memory region where the callstack string will be written to. The string outputted by this function will always be null-terminated. - :param int maxbytes: The maximum number of bytes that this function can write to the memory pointed to by ``out``. If there is not enough space, the output will be truncated (but always null-terminated). - :returns: The number of bytes written (not number of characters, so this will also include the terminating zero). - :rtype: int + :param int flags: A binary OR of items from the list of :c:data:`EM_LOG_xxx ` flags that specify printing options. The flags :c:data:`EM_LOG_CONSOLE`, :c:data:`EM_LOG_WARN` and :c:data:`EM_LOG_ERROR` do not apply in this function and are ignored. + :param char* out: A pointer to a memory region where the callstack string will be written to. The string outputted by this function will always be null-terminated. + :param int maxbytes: The maximum number of bytes that this function can write to the memory pointed to by ``out``. If there is not enough space, the output will be truncated (but always null-terminated). + :returns: The number of bytes written (not number of characters, so this will also include the terminating zero). + :rtype: int .. c:function:: char *emscripten_get_preloaded_image_data(const char *path, int *w, int *h) - Gets preloaded image data and the size of the image. - - The function returns pointer to loaded image or NULL — the pointer should be ``free()``'d. The width/height of the image are written to the ``w`` and ``h`` parameters if the data is valid. + Gets preloaded image data and the size of the image. - :param path: Full path/filename to the file containing the preloaded image. - :type: const char* - :param int* w: Width of the image (if data is valid). - :param int* h: Height of the image (if data is valid). - :returns: A pointer to the preloaded image or NULL. - :rtype: char* + The function returns pointer to loaded image or NULL — the pointer should be ``free()``'d. The width/height of the image are written to the ``w`` and ``h`` parameters if the data is valid. + + :param path: Full path/filename to the file containing the preloaded image. + :type: const char* + :param int* w: Width of the image (if data is valid). + :param int* h: Height of the image (if data is valid). + :returns: A pointer to the preloaded image or NULL. + :rtype: char* .. c:function:: char *emscripten_get_preloaded_image_data_from_FILE(FILE *file, int *w, int *h) - Gets preloaded image data from a C ``FILE*``. + Gets preloaded image data from a C ``FILE*``. - :param FILE* file: The ``FILE`` containing the preloaded image. - :type: const char* - :param int* w: Width of the image (if data is valid). - :param int* h: Height of the image (if data is valid). - :returns: A pointer to the preloaded image or NULL. - :rtype: char* + :param FILE* file: The ``FILE`` containing the preloaded image. + :type: const char* + :param int* w: Width of the image (if data is valid). + :param int* h: Height of the image (if data is valid). + :returns: A pointer to the preloaded image or NULL. + :rtype: char* .. c:function:: int emscripten_print_double(double x, char *to, signed max) - Prints a double as a string, including a null terminator. This is useful because JS engines have good support for printing out a double in a way that takes the least possible size, but preserves all the information in the double, i.e., it can then be parsed back in a perfectly reversible manner (snprintf etc. do not do so, sadly). + Prints a double as a string, including a null terminator. This is useful because JS engines have good support for printing out a double in a way that takes the least possible size, but preserves all the information in the double, i.e., it can then be parsed back in a perfectly reversible manner (snprintf etc. do not do so, sadly). + + :param double x: The double. + :param char* to: A pre-allocated buffer of sufficient size, or NULL if no output is requested (useful to get the necessary size). + :param signed max: The maximum number of bytes that can be written to the output pointer 'to' (including the null terminator). + :rtype: The number of necessary bytes, not including the null terminator (actually written, if ``to`` is not NULL). - :param double x: The double. - :param char* to: A pre-allocated buffer of sufficient size, or NULL if no output is requested (useful to get the necessary size). - :param signed max: The maximum number of bytes that can be written to the output pointer 'to' (including the null terminator). - :rtype: The number of necessary bytes, not including the null terminator (actually written, if ``to`` is not NULL). - .. _emscripten-api-reference-sockets: Socket event registration @@ -1068,16 +1094,16 @@ Only a single callback function may be registered to handle any given event, so The ``userData`` pointer allows arbitrary data specified during event registration to be passed to the callback, this is particularly useful for passing ``this`` pointers around in Object Oriented code. -In addition to being able to register network callbacks from C it is also possible for native JavaScript code to directly use the underlying mechanism used to implement the callback registration. For example, the following code shows simple logging callbacks that are registered by default when ``SOCKET_DEBUG`` is enabled: +In addition to being able to register network callbacks from C it is also possible for native JavaScript code to directly use the underlying mechanism used to implement the callback registration. For example, the following code shows simple logging callbacks that are registered by default when ``SOCKET_DEBUG`` is enabled: .. code-block:: javascript - Module['websocket']['on']('error', function(error) {console.log('Socket error ' + error);}); - Module['websocket']['on']('open', function(fd) {console.log('Socket open fd = ' + fd);}); - Module['websocket']['on']('listen', function(fd) {console.log('Socket listen fd = ' + fd);}); - Module['websocket']['on']('connection', function(fd) {console.log('Socket connection fd = ' + fd);}); - Module['websocket']['on']('message', function(fd) {console.log('Socket message fd = ' + fd);}); - Module['websocket']['on']('close', function(fd) {console.log('Socket close fd = ' + fd);}); + Module['websocket']['on']('error', function(error) {console.log('Socket error ' + error);}); + Module['websocket']['on']('open', function(fd) {console.log('Socket open fd = ' + fd);}); + Module['websocket']['on']('listen', function(fd) {console.log('Socket listen fd = ' + fd);}); + Module['websocket']['on']('connection', function(fd) {console.log('Socket connection fd = ' + fd);}); + Module['websocket']['on']('message', function(fd) {console.log('Socket message fd = ' + fd);}); + Module['websocket']['on']('close', function(fd) {console.log('Socket close fd = ' + fd);}); Most of the JavaScript callback functions above get passed the file descriptor of the socket that triggered the callback, the on error callback however gets passed an *array* that contains the file descriptor, the error code and an error message. @@ -1089,28 +1115,28 @@ Callback functions .. c:type:: em_socket_callback - Function pointer for :c:func:`emscripten_set_socket_open_callback`, and the other socket functions (except :c:func:`emscripten_set_socket_error_callback`). This is defined as: + Function pointer for :c:func:`emscripten_set_socket_open_callback`, and the other socket functions (except :c:func:`emscripten_set_socket_error_callback`). This is defined as: + + .. code-block:: cpp + + typedef void (*em_socket_callback)(int fd, void *userData); - .. code-block:: cpp + :param int fd: The file descriptor of the socket that triggered the callback. + :param void* userData: The ``userData`` originally passed to the event registration function. - typedef void (*em_socket_callback)(int fd, void *userData); - - :param int fd: The file descriptor of the socket that triggered the callback. - :param void* userData: The ``userData`` originally passed to the event registration function. - .. c:type:: em_socket_error_callback - Function pointer for the :c:func:`emscripten_set_socket_error_callback`, defined as: + Function pointer for the :c:func:`emscripten_set_socket_error_callback`, defined as: - .. code-block:: cpp + .. code-block:: cpp - typedef void (*em_socket_error_callback)(int fd, int err, const char* msg, void *userData); - - :param int fd: The file descriptor of the socket that triggered the callback. - :param int err: The code for the error that occurred. - :param int msg: The message for the error that occurred. - :param void* userData: The ``userData`` originally passed to the event registration function. + typedef void (*em_socket_error_callback)(int fd, int err, const char* msg, void *userData); + + :param int fd: The file descriptor of the socket that triggered the callback. + :param int err: The code for the error that occurred. + :param int msg: The message for the error that occurred. + :param void* userData: The ``userData`` originally passed to the event registration function. @@ -1119,66 +1145,66 @@ Functions .. c:function:: void emscripten_set_socket_error_callback(void *userData, em_socket_error_callback callback) - Triggered by a ``WebSocket`` error. - - See :ref:`emscripten-api-reference-sockets` for more information. - - :param void* userData: Arbitrary user data to be passed to the callback. - :param em_socket_error_callback callback: Pointer to a callback function. The callback returns a file descriptor, error code and message, and the arbitrary ``userData`` passed to this function. + Triggered by a ``WebSocket`` error. + + See :ref:`emscripten-api-reference-sockets` for more information. + + :param void* userData: Arbitrary user data to be passed to the callback. + :param em_socket_error_callback callback: Pointer to a callback function. The callback returns a file descriptor, error code and message, and the arbitrary ``userData`` passed to this function. .. c:function:: void emscripten_set_socket_open_callback(void *userData, em_socket_callback callback) - Triggered when the ``WebSocket`` has opened. + Triggered when the ``WebSocket`` has opened. + + See :ref:`emscripten-api-reference-sockets` for more information. + + :param void* userData: Arbitrary user data to be passed to the callback. + :param em_socket_callback callback: Pointer to a callback function. The callback returns a file descriptor and the arbitrary ``userData`` passed to this function. - See :ref:`emscripten-api-reference-sockets` for more information. - - :param void* userData: Arbitrary user data to be passed to the callback. - :param em_socket_callback callback: Pointer to a callback function. The callback returns a file descriptor and the arbitrary ``userData`` passed to this function. - .. c:function:: void emscripten_set_socket_listen_callback(void *userData, em_socket_callback callback) - Triggered when ``listen`` has been called (synthetic event). + Triggered when ``listen`` has been called (synthetic event). + + See :ref:`emscripten-api-reference-sockets` for more information. + + :param void* userData: Arbitrary user data to be passed to the callback. + :param em_socket_callback callback: Pointer to a callback function. The callback returns a file descriptor and the arbitrary ``userData`` passed to this function. - See :ref:`emscripten-api-reference-sockets` for more information. - - :param void* userData: Arbitrary user data to be passed to the callback. - :param em_socket_callback callback: Pointer to a callback function. The callback returns a file descriptor and the arbitrary ``userData`` passed to this function. - .. c:function:: void emscripten_set_socket_connection_callback(void *userData, em_socket_callback callback) - Triggered when the connection has been established. + Triggered when the connection has been established. + + See :ref:`emscripten-api-reference-sockets` for more information. + + :param void* userData: Arbitrary user data to be passed to the callback. + :param em_socket_callback callback: Pointer to a callback function. The callback returns a file descriptor and the arbitrary ``userData`` passed to this function. - See :ref:`emscripten-api-reference-sockets` for more information. - - :param void* userData: Arbitrary user data to be passed to the callback. - :param em_socket_callback callback: Pointer to a callback function. The callback returns a file descriptor and the arbitrary ``userData`` passed to this function. - .. c:function:: void emscripten_set_socket_message_callback(void *userData, em_socket_callback callback) - Triggered when data is available to be read from the socket. + Triggered when data is available to be read from the socket. + + See :ref:`emscripten-api-reference-sockets` for more information. + + :param void* userData: Arbitrary user data to be passed to the callback. + :param em_socket_callback callback: Pointer to a callback function. The callback returns a file descriptor and the arbitrary ``userData`` passed to this function. + - See :ref:`emscripten-api-reference-sockets` for more information. - - :param void* userData: Arbitrary user data to be passed to the callback. - :param em_socket_callback callback: Pointer to a callback function. The callback returns a file descriptor and the arbitrary ``userData`` passed to this function. - - .. c:function:: void emscripten_set_socket_close_callback(void *userData, em_socket_callback callback) - Triggered when the ``WebSocket`` has closed. + Triggered when the ``WebSocket`` has closed. + + See :ref:`emscripten-api-reference-sockets` for more information. + + :param void* userData: Arbitrary user data to be passed to the callback. + :param em_socket_callback callback: Pointer to a callback function. The callback returns a file descriptor and the arbitrary ``userData`` passed to this function. - See :ref:`emscripten-api-reference-sockets` for more information. - - :param void* userData: Arbitrary user data to be passed to the callback. - :param em_socket_callback callback: Pointer to a callback function. The callback returns a file descriptor and the arbitrary ``userData`` passed to this function. - Unaligned types =============== @@ -1186,19 +1212,19 @@ Typedefs --------- .. c:type:: emscripten_align1_short - emscripten_align2_int - emscripten_align1_int - emscripten_align2_float - emscripten_align1_float - emscripten_align4_double - emscripten_align2_double - emscripten_align1_double + emscripten_align2_int + emscripten_align1_int + emscripten_align2_float + emscripten_align1_float + emscripten_align4_double + emscripten_align2_double + emscripten_align1_double - Unaligned types. These may be used to force LLVM to emit unaligned loads/stores in places in your code where :ref:`SAFE_HEAP ` found an unaligned operation. - - For usage examples see `tests/core/test_set_align.c `_. - - .. note:: It is better to avoid unaligned operations, but if you are reading from a packed stream of bytes or such, these types may be useful! + Unaligned types. These may be used to force LLVM to emit unaligned loads/stores in places in your code where :ref:`SAFE_HEAP ` found an unaligned operation. + + For usage examples see `tests/core/test_set_align.c `_. + + .. note:: It is better to avoid unaligned operations, but if you are reading from a packed stream of bytes or such, these types may be useful! Emterpreter-Async functions @@ -1211,69 +1237,69 @@ Sleeping .. c:function:: void emscripten_sleep(unsigned int ms) - Sleep for `ms` milliseconds. This is a normal "synchronous" sleep, which blocks all other operations while it runs. In other words, if - there are other async events waiting to happen, they will not happen during this sleep, which makes sense as conceptually this code is - on the stack (that's how it looks in the C source code). If you do want things to happen while sleeping, see ``emscripten_sleep_with_yield``. + Sleep for `ms` milliseconds. This is a normal "synchronous" sleep, which blocks all other operations while it runs. In other words, if + there are other async events waiting to happen, they will not happen during this sleep, which makes sense as conceptually this code is + on the stack (that's how it looks in the C source code). If you do want things to happen while sleeping, see ``emscripten_sleep_with_yield``. .. c:function:: void emscripten_sleep_with_yield(unsigned int ms) - Sleep for `ms` milliseconds, while allowing other asynchronous operations, e.g. caused by ``emscripten_async_call``, to run normally, during - this sleep. Note that this method **does** still block the main loop, as otherwise it could recurse, if you are calling this method from it. - Even so, you should use this method carefully: the order of execution is potentially very confusing this way. + Sleep for `ms` milliseconds, while allowing other asynchronous operations, e.g. caused by ``emscripten_async_call``, to run normally, during + this sleep. Note that this method **does** still block the main loop, as otherwise it could recurse, if you are calling this method from it. + Even so, you should use this method carefully: the order of execution is potentially very confusing this way. Network ------- .. c:function:: void emscripten_wget_data(const char* url, void** pbuffer, int* pnum, int *perror); - Synchronously fetches data off the network, and stores it to a buffer in memory, which is allocated for you. **You must free the buffer, or it will leak!** + Synchronously fetches data off the network, and stores it to a buffer in memory, which is allocated for you. **You must free the buffer, or it will leak!** - :param url: The URL to fetch from - :param pbuffer: An out parameter that will be filled with a pointer to a buffer containing the data that is downloaded. This space has been malloced for you, **and you must free it, or it will leak!** - :param pnum: An out parameter that will be filled with the size of the downloaded data. - :param perror: An out parameter that will be filled with a non-zero value if an error occurred. + :param url: The URL to fetch from + :param pbuffer: An out parameter that will be filled with a pointer to a buffer containing the data that is downloaded. This space has been malloced for you, **and you must free it, or it will leak!** + :param pnum: An out parameter that will be filled with the size of the downloaded data. + :param perror: An out parameter that will be filled with a non-zero value if an error occurred. IndexedDB --------- .. c:function:: void emscripten_idb_load(const char *db_name, const char *file_id, void** pbuffer, int* pnum, int *perror); - Synchronously fetches data from IndexedDB, and stores it to a buffer in memory, which is allocated for you. **You must free the buffer, or it will leak!** + Synchronously fetches data from IndexedDB, and stores it to a buffer in memory, which is allocated for you. **You must free the buffer, or it will leak!** - :param db_name: The name of the database to load from - :param file_id: The name of the file to load - :param pbuffer: An out parameter that will be filled with a pointer to a buffer containing the data that is downloaded. This space has been malloced for you, **and you must free it, or it will leak!** - :param pnum: An out parameter that will be filled with the size of the downloaded data. - :param perror: An out parameter that will be filled with a non-zero value if an error occurred. + :param db_name: The name of the database to load from + :param file_id: The name of the file to load + :param pbuffer: An out parameter that will be filled with a pointer to a buffer containing the data that is downloaded. This space has been malloced for you, **and you must free it, or it will leak!** + :param pnum: An out parameter that will be filled with the size of the downloaded data. + :param perror: An out parameter that will be filled with a non-zero value if an error occurred. .. c:function:: void emscripten_idb_store(const char *db_name, const char *file_id, void* buffer, int num, int *perror); - Synchronously stores data to IndexedDB. + Synchronously stores data to IndexedDB. - :param db_name: The name of the database to store to - :param file_id: The name of the file to store - :param buffer: A pointer to the data to store - :param num: How many bytes to store - :param perror: An out parameter that will be filled with a non-zero value if an error occurred. + :param db_name: The name of the database to store to + :param file_id: The name of the file to store + :param buffer: A pointer to the data to store + :param num: How many bytes to store + :param perror: An out parameter that will be filled with a non-zero value if an error occurred. .. c:function:: void emscripten_idb_delete(const char *db_name, const char *file_id, int *perror); - Synchronously deletes data from IndexedDB. + Synchronously deletes data from IndexedDB. - :param db_name: The name of the database to delete from - :param file_id: The name of the file to delete - :param perror: An out parameter that will be filled with a non-zero value if an error occurred. + :param db_name: The name of the database to delete from + :param file_id: The name of the file to delete + :param perror: An out parameter that will be filled with a non-zero value if an error occurred. .. c:function:: void emscripten_idb_exists(const char *db_name, const char *file_id, int* pexists, int *perror); - Synchronously checks if a file exists in IndexedDB. + Synchronously checks if a file exists in IndexedDB. + + :param db_name: The name of the database to check in + :param file_id: The name of the file to check + :param pexists: An out parameter that will be filled with a non-zero value if the file exists in that database. + :param perror: An out parameter that will be filled with a non-zero value if an error occurred. - :param db_name: The name of the database to check in - :param file_id: The name of the file to check - :param pexists: An out parameter that will be filled with a non-zero value if the file exists in that database. - :param perror: An out parameter that will be filled with a non-zero value if an error occurred. - Asyncify functions ================== diff --git a/site/source/docs/api_reference/html5.h.rst b/site/source/docs/api_reference/html5.h.rst index 4eb37b25b15ec..7b300dfdfa45e 100644 --- a/site/source/docs/api_reference/html5.h.rst +++ b/site/source/docs/api_reference/html5.h.rst @@ -1,42 +1,40 @@ .. _html5-h: -======== +======= html5.h -======== +======= -The C++ APIs in `html5.h `_ define the Emscripten low-level glue bindings to interact with HTML5 events from native code. +The C++ APIs in `html5.h `_ define the Emscripten low-level glue bindings to interact with HTML5 events from native code. .. tip:: The C++ APIs map closely to their :ref:`equivalent HTML5 JavaScript APIs `. The HTML5 specifications listed below provide additional detailed reference "over and above" the information provided in this document. - In addition, the :ref:`test-example-code-html5-api` can be reviewed to see how the code is used. + In addition, the :ref:`test-example-code-html5-api` can be reviewed to see how the code is used. -.. _specifications-html5-api: +.. _specifications-html5-api: The HTML5 specifications for APIs that are mapped by **html5.h** include: - - `DOM Level 3 Events: Keyboard, Mouse, Mouse Wheel, Resize, Scroll, Focus `_. - - `Device Orientation Events for gyro and accelerometer `_. - - `Screen Orientation Events for portrait/landscape handling `_. - - `Fullscreen Events for browser canvas fullscreen modes transitioning `_. - - `Pointer Lock Events for relative-mode mouse motion control `_. - - `Vibration API for mobile device haptic vibration feedback control `_. - - `Page Visibility Events for power management control `_. - - `Touch Events `_. - - `Gamepad API `_. - - `Beforeunload event `_. - - `WebGL context events `_ - - + - `DOM Level 3 Events: Keyboard, Mouse, Mouse Wheel, Resize, Scroll, Focus `_. + - `Device Orientation Events for gyro and accelerometer `_. + - `Screen Orientation Events for portrait/landscape handling `_. + - `Fullscreen Events for browser canvas fullscreen modes transitioning `_. + - `Pointer Lock Events for relative-mode mouse motion control `_. + - `Vibration API for mobile device haptic vibration feedback control `_. + - `Page Visibility Events for power management control `_. + - `Touch Events `_. + - `Gamepad API `_. + - `Beforeunload event `_. + - `WebGL context events `_ .. contents:: Table of Contents :local: :depth: 1 - + How to use this API =================== - -Most of these APIs use an event-based architecture; functionality is accessed by registering a callback function that will be called when the event occurs. + +Most of these APIs use an event-based architecture; functionality is accessed by registering a callback function that will be called when the event occurs. .. note:: The Gamepad API is currently an exception, as only a polling API is available. For some APIs, both an event-based and a polling-based model are exposed. @@ -45,67 +43,67 @@ Most of these APIs use an event-based architecture; functionality is accessed by Registration functions ---------------------- -The typical format of registration functions is as follows (some methods may omit various parameters): +The typical format of registration functions is as follows (some methods may omit various parameters): + + .. code-block:: cpp - .. code-block:: cpp + EMSCRIPTEN_RESULT emscripten_set_some_callback( + const char *target, // ID of the target HTML element. + void *userData, // User-defined data to be passed to the callback. + EM_BOOL useCapture, // Whether or not to use capture. + em_someevent_callback_func callback // Callback function. + ); - EMSCRIPTEN_RESULT emscripten_set_some_callback( - const char *target, // ID of the target HTML element. - void *userData, // User-defined data to be passed to the callback. - EM_BOOL useCapture, // Whether or not to use capture. - em_someevent_callback_func callback // Callback function. - ); +.. _target-parameter-html5-api: -.. _target-parameter-html5-api: - The ``target`` parameter is the ID of the HTML element to which the callback registration is to be applied. This field has the following special meanings: - - ``0`` or ``NULL``: A default element is chosen automatically based on the event type, which should be reasonable most of the time. - - ``#window``: The event listener is applied to the JavaScript ``window`` object. - - ``#document``: The event listener is applied to the JavaScript ``document`` object. - - ``#screen``: The event listener is applied to the JavaScript ``window.screen`` object. - - ``#canvas``: The event listener is applied to the Emscripten default WebGL canvas element. - - Any other string without a leading hash "#" sign: The event listener is applied to the element on the page with the given ID. + - ``0`` or ``NULL``: A default element is chosen automatically based on the event type, which should be reasonable most of the time. + - ``#window``: The event listener is applied to the JavaScript ``window`` object. + - ``#document``: The event listener is applied to the JavaScript ``document`` object. + - ``#screen``: The event listener is applied to the JavaScript ``window.screen`` object. + - ``#canvas``: The event listener is applied to the Emscripten default WebGL canvas element. + - Any other string without a leading hash "#" sign: The event listener is applied to the element on the page with the given ID. + +.. _userdata-parameter-html5-api: -.. _userdata-parameter-html5-api: - The ``userData`` parameter is a user-defined value that is passed (unchanged) to the registered event callback. This can be used to, for example, pass a pointer to a C++ class or similarly to enclose the C API in a clean object-oriented manner. -.. _usecapture-parameter-html5-api: +.. _usecapture-parameter-html5-api: The ``useCapture`` parameter maps to ``useCapture`` in `EventTarget.addEventListener `_. It indicates whether or not to initiate *capture*: if ``true`` the callback will be invoked only for the DOM capture and target phases; if ``false`` the callback will be triggered during the target and bubbling phases. See `DOM Level 3 Events `_ for a more detailed explanation. Most functions return the result using the type :c:data:`EMSCRIPTEN_RESULT`. Zero and positive values denote success. Negative values signal failure. None of the functions fail or abort by throwing a JavaScript or C++ exception. If a particular browser does not support the given feature, the value :c:data:`EMSCRIPTEN_RESULT_NOT_SUPPORTED` will be returned at the time the callback is registered. - + Callback functions ------------------ When the event occurs the callback is invoked with the relevant event "type" (for example :c:data:`EMSCRIPTEN_EVENT_CLICK`), a ``struct`` containing the details of the event that occurred, and the ``userData`` that was originally passed to the registration function. The general format of the callback function is: :: - typedef EM_BOOL (*em_someevent_callback_func) // Callback function. Return true if event is "consumed". - ( - int eventType, // The type of event. - const EmscriptenSomeEvent *someEvent, // Information about the event. - void *userData // User data passed from the registration function. - ); + typedef EM_BOOL (*em_someevent_callback_func) // Callback function. Return true if event is "consumed". + ( + int eventType, // The type of event. + const EmscriptenSomeEvent *someEvent, // Information about the event. + void *userData // User data passed from the registration function. + ); -.. _callback-handler-return-em_bool-html5-api: +.. _callback-handler-return-em_bool-html5-api: Callback handlers that return an :c:data:`EM_BOOL` may specify ``true`` to signal that the handler *consumed* the event (this suppresses the default action for that event by calling its ``.preventDefault();`` member). Returning ``false`` indicates that the event was not consumed — the default browser event action is carried out and the event is allowed to pass on/bubble up as normal. Calling a registration function with a ``null`` pointer for the callback causes a de-registration of that callback from the given ``target`` element. All event handlers are also automatically unregistered when the C ``exit()`` function is invoked during the ``atexit`` handler pass. Either use the function :c:func:`emscripten_set_main_loop` or set ``Module.noExitRuntime = true;`` to make sure that leaving ``main()`` will not immediately cause an ``exit()`` and clean up the event handlers. -.. _web-security-functions-html5-api: +.. _web-security-functions-html5-api: Functions affected by web security ---------------------------------- Some functions, including :c:func:`emscripten_request_pointerlock` and :c:func:`emscripten_request_fullscreen`, are affected by web security. -While the functions can be called anywhere, the actual "requests" can only be raised inside the handler for a user-generated event (for example a key, mouse or touch press/release). +While the functions can be called anywhere, the actual "requests" can only be raised inside the handler for a user-generated event (for example a key, mouse or touch press/release). When porting code, it may be difficult to ensure that the functions are called inside appropriate event handlers (so that the requests are raised immediately). As a convenience, developers can set ``deferUntilInEventHandler=true`` to automatically defer insecure requests until the user next presses a keyboard or mouse button. This simplifies porting, but often results in a poorer user experience. For example, the user must click once on the canvas to hide the pointer or transition to full screen. @@ -119,10 +117,10 @@ Test/Example code The HTML5 test code demonstrates how to use this API: - - `test_html5.c `_ - - `test_html5_fullscreen.c `_ - - `test_html5_mouse.c `_ - + - `test_html5.c `_ + - `test_html5_fullscreen.c `_ + - `test_html5_mouse.c `_ + General types ============= @@ -130,207 +128,207 @@ General types .. c:macro:: EM_BOOL - This is the Emscripten type for a ``bool``. - Possible values: - - .. c:macro:: EM_TRUE + This is the Emscripten type for a ``bool``. + Possible values: - This is the Emscripten value for ``true``. + .. c:macro:: EM_TRUE - .. c:macro:: EM_FALSE + This is the Emscripten value for ``true``. + + .. c:macro:: EM_FALSE + + This is the Emscripten value for ``false``. - This is the Emscripten value for ``false``. - .. c:macro:: EM_UTF8 - This is the Emscripten type for a UTF8 string (maps to a ``char``). This is used for node names, element ids, etc. + This is the Emscripten type for a UTF8 string (maps to a ``char``). This is used for node names, element ids, etc. + - Function result values ====================== Most functions in this API return a result of type :c:data:`EMSCRIPTEN_RESULT`. None of the functions fail or abort by throwing a JavaScript or C++ exception. If a particular browser does not support the given feature, the value :c:data:`EMSCRIPTEN_RESULT_NOT_SUPPORTED` will be returned at the time the callback is registered. - + .. c:macro:: EMSCRIPTEN_RESULT - This type is used to return the result of most functions in this API. Zero and positive values denote success, while negative values signal failure. Possible values are listed below. - - - .. c:macro:: EMSCRIPTEN_RESULT_SUCCESS + This type is used to return the result of most functions in this API. Zero and positive values denote success, while negative values signal failure. Possible values are listed below. + + + .. c:macro:: EMSCRIPTEN_RESULT_SUCCESS + + The operation succeeded. - The operation succeeded. + .. c:macro:: EMSCRIPTEN_RESULT_DEFERRED - .. c:macro:: EMSCRIPTEN_RESULT_DEFERRED + The requested operation cannot be completed now for :ref:`web security reasons`, and has been deferred for completion in the next event handler. - The requested operation cannot be completed now for :ref:`web security reasons`, and has been deferred for completion in the next event handler. - - .. c:macro:: EMSCRIPTEN_RESULT_NOT_SUPPORTED + .. c:macro:: EMSCRIPTEN_RESULT_NOT_SUPPORTED - The given operation is not supported by this browser or the target element. This value will be returned at the time the callback is registered if the operation is not supported. - + The given operation is not supported by this browser or the target element. This value will be returned at the time the callback is registered if the operation is not supported. - .. c:macro:: EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED - The requested operation could not be completed now for :ref:`web security reasons`. It failed because the user requested the operation not be deferred. + .. c:macro:: EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED - .. c:macro:: EMSCRIPTEN_RESULT_INVALID_TARGET + The requested operation could not be completed now for :ref:`web security reasons`. It failed because the user requested the operation not be deferred. - The operation failed because the specified target element is invalid. + .. c:macro:: EMSCRIPTEN_RESULT_INVALID_TARGET - .. c:macro:: EMSCRIPTEN_RESULT_UNKNOWN_TARGET + The operation failed because the specified target element is invalid. - The operation failed because the specified target element was not found. + .. c:macro:: EMSCRIPTEN_RESULT_UNKNOWN_TARGET - .. c:macro:: EMSCRIPTEN_RESULT_INVALID_PARAM + The operation failed because the specified target element was not found. - The operation failed because an invalid parameter was passed to the function. + .. c:macro:: EMSCRIPTEN_RESULT_INVALID_PARAM - .. c:macro:: EMSCRIPTEN_RESULT_FAILED + The operation failed because an invalid parameter was passed to the function. - Generic failure result message, returned if no specific result is available. + .. c:macro:: EMSCRIPTEN_RESULT_FAILED - .. c:macro:: EMSCRIPTEN_RESULT_NO_DATA + Generic failure result message, returned if no specific result is available. + + .. c:macro:: EMSCRIPTEN_RESULT_NO_DATA + + The operation failed because no data is currently available. - The operation failed because no data is currently available. - Keys ==== Defines -------- +------- .. c:macro:: EMSCRIPTEN_EVENT_KEYPRESS - EMSCRIPTEN_EVENT_KEYDOWN - EMSCRIPTEN_EVENT_KEYUP - + EMSCRIPTEN_EVENT_KEYDOWN + EMSCRIPTEN_EVENT_KEYUP + Emscripten key events. - + .. c:macro:: DOM_KEY_LOCATION - The location of the key on the keyboard; one of the values below. + The location of the key on the keyboard; one of the values below. - .. c:macro:: DOM_KEY_LOCATION_STANDARD - DOM_KEY_LOCATION_LEFT - DOM_KEY_LOCATION_RIGHT - DOM_KEY_LOCATION_NUMPAD + .. c:macro:: DOM_KEY_LOCATION_STANDARD + DOM_KEY_LOCATION_LEFT + DOM_KEY_LOCATION_RIGHT + DOM_KEY_LOCATION_NUMPAD - Locations of the key on the keyboard. + Locations of the key on the keyboard. Struct ------- +------ .. c:type:: EmscriptenKeyboardEvent - The event structure passed in `keyboard events `_: ``keypress``, ``keydown`` and ``keyup``. - - Note that since the `DOM Level 3 Events spec `_ is very recent at the time of writing (2014-03), uniform support for the different fields in the spec is still in flux. Be sure to check the results in multiple browsers. See the `unmerged pull request #2222 `_ for an example of how to interpret the legacy key events. - - - .. c:member:: EM_UTF8 key - - The printed representation of the pressed key. - - Maximum size 32 ``char`` (i.e. ``EM_UTF8 key[32]``). - - .. c:member:: EM_UTF8 code - - A string that identifies the physical key being pressed. The value is not affected by the current keyboard layout or modifier state, so a particular key will always return the same value. - - Maximum size 32 ``char`` (i.e. ``EM_UTF8 code[32]``). - - .. c:member:: unsigned long location - - Indicates the location of the key on the keyboard. One of the :c:data:`DOM_KEY_LOCATION ` values. - - .. c:member:: EM_BOOL ctrlKey - EM_BOOL shiftKey - EM_BOOL altKey - EM_BOOL metaKey - - Specifies which modifiers were active during the key event. - - .. c:member:: EM_BOOL repeat - - Specifies if this keyboard event represents a repeated press. - - .. c:member:: EM_UTF8 locale - - A locale string indicating the configured keyboard locale. This may be an empty string if the browser or device doesn't know the keyboard's locale. - - Maximum size 32 char (i.e. ``EM_UTF8 locale[32]``). - - .. c:member:: EM_UTF8 charValue - - The following fields are values from previous versions of the DOM key events specifications. See `the character representation of the key `_. This is the field ``char`` from the docs, but renamed to ``charValue`` to avoid a C reserved word. - - Maximum size 32 ``char`` (i.e. ``EM_UTF8 charValue[32]``). - - .. warning:: This attribute has been dropped from DOM Level 3 events. - - .. c:member:: unsigned long charCode - - The Unicode reference number of the key; this attribute is used only by the keypress event. For keys whose ``char`` attribute contains multiple characters, this is the Unicode value of the first character in that attribute. - - .. warning:: This attribute is deprecated, you should use the field ``key`` instead, if available. - - .. c:member:: unsigned long keyCode - - A system and implementation dependent numerical code identifying the unmodified value of the pressed key. - - .. warning:: This attribute is deprecated, you should use the field ``key`` instead, if available. - - - .. c:member:: unsigned long which - - A system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as ``keyCode``. - - .. warning:: This attribute is deprecated, you should use the field ``key`` instead, if available. Note thought that while this field is deprecated, the cross-browser support for ``which`` may be better than for the other fields, so experimentation is recommended. Read issue https://github.com/kripken/emscripten/issues/2817 for more information. - - + The event structure passed in `keyboard events `_: ``keypress``, ``keydown`` and ``keyup``. + + Note that since the `DOM Level 3 Events spec `_ is very recent at the time of writing (2014-03), uniform support for the different fields in the spec is still in flux. Be sure to check the results in multiple browsers. See the `unmerged pull request #2222 `_ for an example of how to interpret the legacy key events. + + + .. c:member:: EM_UTF8 key + + The printed representation of the pressed key. + + Maximum size 32 ``char`` (i.e. ``EM_UTF8 key[32]``). + + .. c:member:: EM_UTF8 code + + A string that identifies the physical key being pressed. The value is not affected by the current keyboard layout or modifier state, so a particular key will always return the same value. + + Maximum size 32 ``char`` (i.e. ``EM_UTF8 code[32]``). + + .. c:member:: unsigned long location + + Indicates the location of the key on the keyboard. One of the :c:data:`DOM_KEY_LOCATION ` values. + + .. c:member:: EM_BOOL ctrlKey + EM_BOOL shiftKey + EM_BOOL altKey + EM_BOOL metaKey + + Specifies which modifiers were active during the key event. + + .. c:member:: EM_BOOL repeat + + Specifies if this keyboard event represents a repeated press. + + .. c:member:: EM_UTF8 locale + + A locale string indicating the configured keyboard locale. This may be an empty string if the browser or device doesn't know the keyboard's locale. + + Maximum size 32 char (i.e. ``EM_UTF8 locale[32]``). + + .. c:member:: EM_UTF8 charValue + + The following fields are values from previous versions of the DOM key events specifications. See `the character representation of the key `_. This is the field ``char`` from the docs, but renamed to ``charValue`` to avoid a C reserved word. + + Maximum size 32 ``char`` (i.e. ``EM_UTF8 charValue[32]``). + + .. warning:: This attribute has been dropped from DOM Level 3 events. + + .. c:member:: unsigned long charCode + + The Unicode reference number of the key; this attribute is used only by the keypress event. For keys whose ``char`` attribute contains multiple characters, this is the Unicode value of the first character in that attribute. + + .. warning:: This attribute is deprecated, you should use the field ``key`` instead, if available. + + .. c:member:: unsigned long keyCode + + A system and implementation dependent numerical code identifying the unmodified value of the pressed key. + + .. warning:: This attribute is deprecated, you should use the field ``key`` instead, if available. + + + .. c:member:: unsigned long which + + A system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as ``keyCode``. + + .. warning:: This attribute is deprecated, you should use the field ``key`` instead, if available. Note thought that while this field is deprecated, the cross-browser support for ``which`` may be better than for the other fields, so experimentation is recommended. Read issue https://github.com/kripken/emscripten/issues/2817 for more information. + + Callback functions ------------------ .. c:type:: em_key_callback_func - Function pointer for the :c:func:`keypress callback functions `, defined as: + Function pointer for the :c:func:`keypress callback functions `, defined as: + + .. code-block:: cpp + + typedef EM_BOOL (*em_key_callback_func)(int eventType, const EmscriptenKeyboardEvent *keyEvent, void *userData); + + :param int eventType: The type of :c:data:`key event `. + :param keyEvent: Information about the key event that occurred. + :type keyEvent: const EmscriptenKeyboardEvent* + :param void* userData: The ``userData`` originally passed to the registration function. + :returns: |callback-handler-return-value-doc| + :rtype: |EM_BOOL| - .. code-block:: cpp - typedef EM_BOOL (*em_key_callback_func)(int eventType, const EmscriptenKeyboardEvent *keyEvent, void *userData); - - :param int eventType: The type of :c:data:`key event `. - :param keyEvent: Information about the key event that occurred. - :type keyEvent: const EmscriptenKeyboardEvent* - :param void* userData: The ``userData`` originally passed to the registration function. - :returns: |callback-handler-return-value-doc| - :rtype: |EM_BOOL| - - Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_keypress_callback(const char *target, void *userData, EM_BOOL useCapture, em_key_callback_func callback) - EMSCRIPTEN_RESULT emscripten_set_keydown_callback(const char *target, void *userData, EM_BOOL useCapture, em_key_callback_func callback) - EMSCRIPTEN_RESULT emscripten_set_keyup_callback(const char *target, void *userData, EM_BOOL useCapture, em_key_callback_func callback) - - Registers a callback function for receiving browser-generated keyboard input events. - - :param target: |target-parameter-doc| - :type target: const char* - :param void* userData: |userData-parameter-doc| - :param EM_BOOL useCapture: |useCapture-parameter-doc| - :param em_key_callback_func callback: |callback-function-parameter-doc| - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| - - :see also: - - https://developer.mozilla.org/en/DOM/Event/UIEvent/KeyEvent - - http://www.javascriptkit.com/jsref/eventkeyboardmouse.shtml + EMSCRIPTEN_RESULT emscripten_set_keydown_callback(const char *target, void *userData, EM_BOOL useCapture, em_key_callback_func callback) + EMSCRIPTEN_RESULT emscripten_set_keyup_callback(const char *target, void *userData, EM_BOOL useCapture, em_key_callback_func callback) + + Registers a callback function for receiving browser-generated keyboard input events. + + :param target: |target-parameter-doc| + :type target: const char* + :param void* userData: |userData-parameter-doc| + :param EM_BOOL useCapture: |useCapture-parameter-doc| + :param em_key_callback_func callback: |callback-function-parameter-doc| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| + + :see also: + - https://developer.mozilla.org/en/DOM/Event/UIEvent/KeyEvent + - http://www.javascriptkit.com/jsref/eventkeyboardmouse.shtml Mouse ===== @@ -339,82 +337,82 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_CLICK - EMSCRIPTEN_EVENT_MOUSEDOWN - EMSCRIPTEN_EVENT_MOUSEUP - EMSCRIPTEN_EVENT_DBLCLICK - EMSCRIPTEN_EVENT_MOUSEMOVE - EMSCRIPTEN_EVENT_MOUSEENTER - EMSCRIPTEN_EVENT_MOUSELEAVE - + EMSCRIPTEN_EVENT_MOUSEDOWN + EMSCRIPTEN_EVENT_MOUSEUP + EMSCRIPTEN_EVENT_DBLCLICK + EMSCRIPTEN_EVENT_MOUSEMOVE + EMSCRIPTEN_EVENT_MOUSEENTER + EMSCRIPTEN_EVENT_MOUSELEAVE + Emscripten mouse events. Struct ------- +------ .. c:type:: EmscriptenMouseEvent - The event structure passed in `mouse events `_: `click `_, `mousedown `_, `mouseup `_, `dblclick `_, `mousemove `_, `mouseenter `_ and `mouseleave `_. - - - .. c:member:: double timestamp; - - A timestamp of when this data was generated by the browser. This is an absolute wallclock time in milliseconds. - - .. c:member:: long screenX - long screenY - - The coordinates relative to the browser screen coordinate system. - - .. c:member:: long clientX - long clientY - - The coordinates relative to the viewport associated with the event. - - - .. c:member:: EM_BOOL ctrlKey - EM_BOOL shiftKey - EM_BOOL altKey - EM_BOOL metaKey - - Specifies which modifiers were active during the mouse event. - - - .. c:member:: unsigned short button - - Identifies which pointer device button changed state (see `MouseEvent.button `_): - - - 0 : Left button - - 1 : Middle button (if present) - - 2 : Right button - - - .. c:member:: unsigned short buttons - - A bitmask that indicates which combinations of mouse buttons were being held down at the time of the event. - - .. c:member:: long movementX - long movementY; - - If pointer lock is active, these two extra fields give relative mouse movement since the last event. - - .. c:member:: long targetX - long targetY - - These fields give the mouse coordinates mapped relative to the coordinate space of the target DOM element receiving the input events (Emscripten-specific extension). - - - .. c:member:: long canvasX - long canvasY - - These fields give the mouse coordinates mapped to the Emscripten canvas client area (Emscripten-specific extension). - - - .. c:member:: long padding - - Internal, and can be ignored. - - .. note:: Implementers only: pad this struct to multiple of 8 bytes to make ``WheelEvent`` unambiguously align to 8 bytes. + The event structure passed in `mouse events `_: `click `_, `mousedown `_, `mouseup `_, `dblclick `_, `mousemove `_, `mouseenter `_ and `mouseleave `_. + + + .. c:member:: double timestamp; + + A timestamp of when this data was generated by the browser. This is an absolute wallclock time in milliseconds. + + .. c:member:: long screenX + long screenY + + The coordinates relative to the browser screen coordinate system. + + .. c:member:: long clientX + long clientY + + The coordinates relative to the viewport associated with the event. + + + .. c:member:: EM_BOOL ctrlKey + EM_BOOL shiftKey + EM_BOOL altKey + EM_BOOL metaKey + + Specifies which modifiers were active during the mouse event. + + + .. c:member:: unsigned short button + + Identifies which pointer device button changed state (see `MouseEvent.button `_): + + - 0 : Left button + - 1 : Middle button (if present) + - 2 : Right button + + + .. c:member:: unsigned short buttons + + A bitmask that indicates which combinations of mouse buttons were being held down at the time of the event. + + .. c:member:: long movementX + long movementY; + + If pointer lock is active, these two extra fields give relative mouse movement since the last event. + + .. c:member:: long targetX + long targetY + + These fields give the mouse coordinates mapped relative to the coordinate space of the target DOM element receiving the input events (Emscripten-specific extension). + + + .. c:member:: long canvasX + long canvasY + + These fields give the mouse coordinates mapped to the Emscripten canvas client area (Emscripten-specific extension). + + + .. c:member:: long padding + + Internal, and can be ignored. + + .. note:: Implementers only: pad this struct to multiple of 8 bytes to make ``WheelEvent`` unambiguously align to 8 bytes. Callback functions @@ -422,54 +420,54 @@ Callback functions .. c:type:: em_mouse_callback_func - Function pointer for the :c:func:`mouse event callback functions `, defined as: + Function pointer for the :c:func:`mouse event callback functions `, defined as: + + .. code-block:: cpp - .. code-block:: cpp + typedef EM_BOOL (*em_mouse_callback_func)(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData); + + :param int eventType: The type of :c:data:`mouse event `. + :param mouseEvent: Information about the mouse event that occurred. + :type mouseEvent: const EmscriptenMouseEvent* + :param void* userData: The ``userData`` originally passed to the registration function. + :returns: |callback-handler-return-value-doc| + :rtype: |EM_BOOL| - typedef EM_BOOL (*em_mouse_callback_func)(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData); - - :param int eventType: The type of :c:data:`mouse event `. - :param mouseEvent: Information about the mouse event that occurred. - :type mouseEvent: const EmscriptenMouseEvent* - :param void* userData: The ``userData`` originally passed to the registration function. - :returns: |callback-handler-return-value-doc| - :rtype: |EM_BOOL| - Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_click_callback(const char *target, void *userData, EM_BOOL useCapture, em_mouse_callback_func callback) - EMSCRIPTEN_RESULT emscripten_set_mousedown_callback(const char *target, void *userData, EM_BOOL useCapture, em_mouse_callback_func callback) - EMSCRIPTEN_RESULT emscripten_set_mouseup_callback(const char *target, void *userData, EM_BOOL useCapture, em_mouse_callback_func callback) - EMSCRIPTEN_RESULT emscripten_set_dblclick_callback(const char *target, void *userData, EM_BOOL useCapture, em_mouse_callback_func callback) - EMSCRIPTEN_RESULT emscripten_set_mousemove_callback(const char *target, void *userData, EM_BOOL useCapture, em_mouse_callback_func callback) - EMSCRIPTEN_RESULT emscripten_set_mouseenter_callback(const char *target, void *userData, EM_BOOL useCapture, em_mouse_callback_func callback) - EMSCRIPTEN_RESULT emscripten_set_mouseleave_callback(const char *target, void *userData, EM_BOOL useCapture, em_mouse_callback_func callback) - - Registers a callback function for receiving browser-generated `mouse input events `_. - - :param target: |target-parameter-doc| - :type target: const char* - :param void* userData: |userData-parameter-doc| - :param EM_BOOL useCapture: |useCapture-parameter-doc| - :param em_mouse_callback_func callback: |callback-function-parameter-doc| - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| - - - + EMSCRIPTEN_RESULT emscripten_set_mousedown_callback(const char *target, void *userData, EM_BOOL useCapture, em_mouse_callback_func callback) + EMSCRIPTEN_RESULT emscripten_set_mouseup_callback(const char *target, void *userData, EM_BOOL useCapture, em_mouse_callback_func callback) + EMSCRIPTEN_RESULT emscripten_set_dblclick_callback(const char *target, void *userData, EM_BOOL useCapture, em_mouse_callback_func callback) + EMSCRIPTEN_RESULT emscripten_set_mousemove_callback(const char *target, void *userData, EM_BOOL useCapture, em_mouse_callback_func callback) + EMSCRIPTEN_RESULT emscripten_set_mouseenter_callback(const char *target, void *userData, EM_BOOL useCapture, em_mouse_callback_func callback) + EMSCRIPTEN_RESULT emscripten_set_mouseleave_callback(const char *target, void *userData, EM_BOOL useCapture, em_mouse_callback_func callback) + + Registers a callback function for receiving browser-generated `mouse input events `_. + + :param target: |target-parameter-doc| + :type target: const char* + :param void* userData: |userData-parameter-doc| + :param EM_BOOL useCapture: |useCapture-parameter-doc| + :param em_mouse_callback_func callback: |callback-function-parameter-doc| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| + + + .. c:function:: EMSCRIPTEN_RESULT emscripten_get_mouse_status(EmscriptenMouseEvent *mouseState) - Returns the most recently received mouse event state. - - Note that for this function call to succeed, :c:func:`emscripten_set_xxx_callback ` must have first been called with one of the mouse event types and a non-zero callback function pointer to enable the Mouse state capture. + Returns the most recently received mouse event state. + + Note that for this function call to succeed, :c:func:`emscripten_set_xxx_callback ` must have first been called with one of the mouse event types and a non-zero callback function pointer to enable the Mouse state capture. + + :param EmscriptenMouseEvent* mouseState: The most recently received mouse event state. + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| - :param EmscriptenMouseEvent* mouseState: The most recently received mouse event state. - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| - Wheel @@ -479,44 +477,44 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_WHEEL - + Emscripten wheel event. - + .. c:macro:: DOM_DELTA_PIXEL - The units of measurement for the delta must be pixels (from `spec `_). - + The units of measurement for the delta must be pixels (from `spec `_). + .. c:macro:: DOM_DELTA_LINE - The units of measurement for the delta must be individual lines of text (from `spec `_). - + The units of measurement for the delta must be individual lines of text (from `spec `_). + .. c:macro:: DOM_DELTA_PAGE - The units of measurement for the delta must be pages, either defined as a single screen or as a demarcated page (from `spec `_). + The units of measurement for the delta must be pages, either defined as a single screen or as a demarcated page (from `spec `_). + - Struct ------- +------ .. c:type:: EmscriptenWheelEvent - The event structure passed in `mousewheel events `_. - - .. c:member:: EmscriptenMouseEvent mouse - - Specifies general mouse information related to this event. - - .. c:member:: double deltaX - double deltaY - double deltaZ - - Movement of the wheel on each of the axis. Note that these values may be fractional, so you should avoid simply casting them to integer, or it might result - in scroll values of 0. The positive Y scroll direction is when scrolling the page downwards (page CSS pixel +Y direction), which corresponds to scrolling - the mouse wheel downwards (away from the screen) on Windows, Linux, and also on OSX when the 'natural scroll' option is disabled. - - .. c:member:: unsigned long deltaMode - - One of the :c:data:`DOM_DELTA_` values that indicates the units of measurement for the delta values. + The event structure passed in `mousewheel events `_. + + .. c:member:: EmscriptenMouseEvent mouse + + Specifies general mouse information related to this event. + + .. c:member:: double deltaX + double deltaY + double deltaZ + + Movement of the wheel on each of the axis. Note that these values may be fractional, so you should avoid simply casting them to integer, or it might result + in scroll values of 0. The positive Y scroll direction is when scrolling the page downwards (page CSS pixel +Y direction), which corresponds to scrolling + the mouse wheel downwards (away from the screen) on Windows, Linux, and also on OSX when the 'natural scroll' option is disabled. + + .. c:member:: unsigned long deltaMode + + One of the :c:data:`DOM_DELTA_` values that indicates the units of measurement for the delta values. Callback functions @@ -524,35 +522,35 @@ Callback functions .. c:type:: em_wheel_callback_func - Function pointer for the :c:func:`wheel event callback functions `, defined as: + Function pointer for the :c:func:`wheel event callback functions `, defined as: + + .. code-block:: cpp + + typedef EM_BOOL (*em_wheel_callback_func)(int eventType, const EmscriptenWheelEvent *wheelEvent, void *userData); + + :param int eventType: The type of wheel event (:c:data:`EMSCRIPTEN_EVENT_WHEEL`). + :param wheelEvent: Information about the wheel event that occurred. + :type wheelEvent: const EmscriptenWheelEvent* + :param void* userData: The ``userData`` originally passed to the registration function. + :returns: |callback-handler-return-value-doc| + :rtype: |EM_BOOL| - .. code-block:: cpp - typedef EM_BOOL (*em_wheel_callback_func)(int eventType, const EmscriptenWheelEvent *wheelEvent, void *userData); - - :param int eventType: The type of wheel event (:c:data:`EMSCRIPTEN_EVENT_WHEEL`). - :param wheelEvent: Information about the wheel event that occurred. - :type wheelEvent: const EmscriptenWheelEvent* - :param void* userData: The ``userData`` originally passed to the registration function. - :returns: |callback-handler-return-value-doc| - :rtype: |EM_BOOL| - - Functions ---------- - +--------- + .. c:function:: EMSCRIPTEN_RESULT emscripten_set_wheel_callback(const char *target, void *userData, EM_BOOL useCapture, em_wheel_callback_func callback) - - Registers a callback function for receiving browser-generated `mousewheel events `_. - :param target: |target-parameter-doc| - :type target: const char* - :param void* userData: |userData-parameter-doc| - :param EM_BOOL useCapture: |useCapture-parameter-doc| - :param em_wheel_callback_func callback: |callback-function-parameter-doc| - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + Registers a callback function for receiving browser-generated `mousewheel events `_. + + :param target: |target-parameter-doc| + :type target: const char* + :param void* userData: |userData-parameter-doc| + :param EM_BOOL useCapture: |useCapture-parameter-doc| + :param em_wheel_callback_func callback: |callback-function-parameter-doc| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| @@ -563,42 +561,42 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_RESIZE - EMSCRIPTEN_EVENT_SCROLL - + EMSCRIPTEN_EVENT_SCROLL + Emscripten UI events. - + Struct ------- +------ .. c:type:: EmscriptenUiEvent - The event structure passed in DOM element `UIEvent `_ events: `resize `_ and `scroll `_. - - - .. c:member:: long detail - - Specifies additional detail/information about this event. - - .. c:member:: int documentBodyClientWidth - int documentBodyClientHeight - - The clientWidth/clientHeight of the ``document.body`` element. - - .. c:member:: int windowInnerWidth - int windowInnerHeight - - The innerWidth/innerHeight of the browser window. - - .. c:member:: int windowOuterWidth - int windowOuterHeight; - - The outerWidth/outerHeight of the browser window. - - .. c:member:: int scrollTop - int scrollLeft - - The page scroll position. + The event structure passed in DOM element `UIEvent `_ events: `resize `_ and `scroll `_. + + + .. c:member:: long detail + + Specifies additional detail/information about this event. + + .. c:member:: int documentBodyClientWidth + int documentBodyClientHeight + + The clientWidth/clientHeight of the ``document.body`` element. + + .. c:member:: int windowInnerWidth + int windowInnerHeight + + The innerWidth/innerHeight of the browser window. + + .. c:member:: int windowOuterWidth + int windowOuterHeight; + + The outerWidth/outerHeight of the browser window. + + .. c:member:: int scrollTop + int scrollLeft + + The page scroll position. Callback functions @@ -606,43 +604,43 @@ Callback functions .. c:type:: em_ui_callback_func - Function pointer for the :c:func:`UI event callback functions `, defined as: + Function pointer for the :c:func:`UI event callback functions `, defined as: + + .. code-block:: cpp + + typedef EM_BOOL (*em_ui_callback_func)(int eventType, const EmscriptenUiEvent *uiEvent, void *userData); + + :param int eventType: The type of UI event (:c:data:`EMSCRIPTEN_EVENT_RESIZE`). + :param uiEvent: Information about the UI event that occurred. + :type uiEvent: const EmscriptenUiEvent* + :param void* userData: The ``userData`` originally passed to the registration function. + :returns: |callback-handler-return-value-doc| + :rtype: |EM_BOOL| - .. code-block:: cpp - typedef EM_BOOL (*em_ui_callback_func)(int eventType, const EmscriptenUiEvent *uiEvent, void *userData); - - :param int eventType: The type of UI event (:c:data:`EMSCRIPTEN_EVENT_RESIZE`). - :param uiEvent: Information about the UI event that occurred. - :type uiEvent: const EmscriptenUiEvent* - :param void* userData: The ``userData`` originally passed to the registration function. - :returns: |callback-handler-return-value-doc| - :rtype: |EM_BOOL| - - Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_resize_callback(const char *target, void *userData, EM_BOOL useCapture, em_ui_callback_func callback) - EMSCRIPTEN_RESULT emscripten_set_scroll_callback(const char *target, void *userData, EM_BOOL useCapture, em_ui_callback_func callback) - - Registers a callback function for receiving DOM element `resize `_ and `scroll `_ events. - - .. note:: - - - For the ``resize`` callback, pass in target = 0 to get ``resize`` events from the ``Window`` object. - - The DOM3 Events specification only requires that the ``Window`` object sends resize events. It is valid to register a ``resize`` callback on other DOM elements, but the browser is not required to fire ``resize`` events for these. - - :param target: |target-parameter-doc| - :type target: const char* - :param void* userData: |userData-parameter-doc| - :param EM_BOOL useCapture: |useCapture-parameter-doc| - :param em_ui_callback_func callback: |callback-function-parameter-doc| - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| - - - + EMSCRIPTEN_RESULT emscripten_set_scroll_callback(const char *target, void *userData, EM_BOOL useCapture, em_ui_callback_func callback) + + Registers a callback function for receiving DOM element `resize `_ and `scroll `_ events. + + .. note:: + + - For the ``resize`` callback, pass in target = 0 to get ``resize`` events from the ``Window`` object. + - The DOM3 Events specification only requires that the ``Window`` object sends resize events. It is valid to register a ``resize`` callback on other DOM elements, but the browser is not required to fire ``resize`` events for these. + + :param target: |target-parameter-doc| + :type target: const char* + :param void* userData: |userData-parameter-doc| + :param EM_BOOL useCapture: |useCapture-parameter-doc| + :param em_ui_callback_func callback: |callback-function-parameter-doc| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| + + + Focus ===== @@ -651,74 +649,74 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_BLUR - EMSCRIPTEN_EVENT_FOCUS - EMSCRIPTEN_EVENT_FOCUSIN - EMSCRIPTEN_EVENT_FOCUSOUT - + EMSCRIPTEN_EVENT_FOCUS + EMSCRIPTEN_EVENT_FOCUSIN + EMSCRIPTEN_EVENT_FOCUSOUT + Emscripten focus events. - + Struct ------- +------ .. c:type:: EmscriptenFocusEvent - The event structure passed in DOM element `blur `_, `focus `_, `focusin `_ and `focusout `_ events. - - .. c:member:: EM_UTF8 nodeName - - The `nodeName `_ of the target HTML Element. - - Maximum size 128 ``char`` (i.e. ``EM_UTF8 nodeName[128]``). - - .. c:member:: EM_UTF8 id - - The ID of the target element. - - Maximum size 128 ``char`` (i.e. ``EM_UTF8 id[128]``). - - - + The event structure passed in DOM element `blur `_, `focus `_, `focusin `_ and `focusout `_ events. + + .. c:member:: EM_UTF8 nodeName + + The `nodeName `_ of the target HTML Element. + + Maximum size 128 ``char`` (i.e. ``EM_UTF8 nodeName[128]``). + + .. c:member:: EM_UTF8 id + + The ID of the target element. + + Maximum size 128 ``char`` (i.e. ``EM_UTF8 id[128]``). + + + Callback functions ------------------ .. c:type:: em_focus_callback_func - Function pointer for the :c:func:`focus event callback functions `, defined as: + Function pointer for the :c:func:`focus event callback functions `, defined as: + + .. code-block:: cpp + + typedef EM_BOOL (*em_focus_callback_func)(int eventType, const EmscriptenFocusEvent *focusEvent, void *userData); + + :param int eventType: The type of focus event (:c:data:`EMSCRIPTEN_EVENT_BLUR`). + :param focusEvent: Information about the focus event that occurred. + :type focusEvent: const EmscriptenFocusEvent* + :param void* userData: The ``userData`` originally passed to the registration function. + :returns: |callback-handler-return-value-doc| + :rtype: |EM_BOOL| - .. code-block:: cpp - typedef EM_BOOL (*em_focus_callback_func)(int eventType, const EmscriptenFocusEvent *focusEvent, void *userData); - - :param int eventType: The type of focus event (:c:data:`EMSCRIPTEN_EVENT_BLUR`). - :param focusEvent: Information about the focus event that occurred. - :type focusEvent: const EmscriptenFocusEvent* - :param void* userData: The ``userData`` originally passed to the registration function. - :returns: |callback-handler-return-value-doc| - :rtype: |EM_BOOL| - - Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_blur_callback(const char *target, void *userData, EM_BOOL useCapture, em_focus_callback_func callback) - EMSCRIPTEN_RESULT emscripten_set_focus_callback(const char *target, void *userData, EM_BOOL useCapture, em_focus_callback_func callback) - EMSCRIPTEN_RESULT emscripten_set_focusin_callback(const char *target, void *userData, EM_BOOL useCapture, em_focus_callback_func callback) - EMSCRIPTEN_RESULT emscripten_set_focusout_callback(const char *target, void *userData, EM_BOOL useCapture, em_focus_callback_func callback) - - Registers a callback function for receiving DOM element `blur `_, `focus `_, `focusin `_ and `focusout `_ events. - - :param target: |target-parameter-doc| - :type target: const char* - :param void* userData: |userData-parameter-doc| - :param EM_BOOL useCapture: |useCapture-parameter-doc| - :param em_focus_callback_func callback: |callback-function-parameter-doc| - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| - - - + EMSCRIPTEN_RESULT emscripten_set_focus_callback(const char *target, void *userData, EM_BOOL useCapture, em_focus_callback_func callback) + EMSCRIPTEN_RESULT emscripten_set_focusin_callback(const char *target, void *userData, EM_BOOL useCapture, em_focus_callback_func callback) + EMSCRIPTEN_RESULT emscripten_set_focusout_callback(const char *target, void *userData, EM_BOOL useCapture, em_focus_callback_func callback) + + Registers a callback function for receiving DOM element `blur `_, `focus `_, `focusin `_ and `focusout `_ events. + + :param target: |target-parameter-doc| + :type target: const char* + :param void* userData: |userData-parameter-doc| + :param EM_BOOL useCapture: |useCapture-parameter-doc| + :param em_focus_callback_func callback: |callback-function-parameter-doc| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| + + + Device orientation ================== @@ -726,41 +724,41 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_DEVICEORIENTATION - + Emscripten ``deviceorientation`` events. Struct ------- +------ .. c:type:: EmscriptenDeviceOrientationEvent - The event structure passed in the `deviceorientation `_ event. - - - .. c:member:: double timestamp - - Absolute wallclock time when the event occurred (in milliseconds). - - .. c:member:: double alpha - double beta - double gamma - - The `orientation `_ of the device in terms of the transformation from a coordinate frame fixed on the Earth to a coordinate frame fixed in the device. - - The image (source: `dev.opera.com `_) and definitions below illustrate the co-ordinate frame: - - - :c:type:`~EmscriptenDeviceOrientationEvent.alpha`: the rotation of the device around the Z axis. - - :c:type:`~EmscriptenDeviceOrientationEvent.beta`: the rotation of the device around the X axis. - - :c:type:`~EmscriptenDeviceOrientationEvent.gamma`: the rotation of the device around the Y axis. - - .. image:: device-orientation-axes.png - :target: https://developer.mozilla.org/en-US/Apps/Build/gather_and_modify_data/responding_to_device_orientation_changes#Device_Orientation_API - :alt: Image of device showing X, Y, Z axes - - - .. c:member:: EM_BOOL absolute - - If ``false``, the orientation is only relative to some other base orientation, not to the fixed coordinate frame. + The event structure passed in the `deviceorientation `_ event. + + + .. c:member:: double timestamp + + Absolute wallclock time when the event occurred (in milliseconds). + + .. c:member:: double alpha + double beta + double gamma + + The `orientation `_ of the device in terms of the transformation from a coordinate frame fixed on the Earth to a coordinate frame fixed in the device. + + The image (source: `dev.opera.com `_) and definitions below illustrate the co-ordinate frame: + + - :c:type:`~EmscriptenDeviceOrientationEvent.alpha`: the rotation of the device around the Z axis. + - :c:type:`~EmscriptenDeviceOrientationEvent.beta`: the rotation of the device around the X axis. + - :c:type:`~EmscriptenDeviceOrientationEvent.gamma`: the rotation of the device around the Y axis. + + .. image:: device-orientation-axes.png + :target: https://developer.mozilla.org/en-US/Apps/Build/gather_and_modify_data/responding_to_device_orientation_changes#Device_Orientation_API + :alt: Image of device showing X, Y, Z axes + + + .. c:member:: EM_BOOL absolute + + If ``false``, the orientation is only relative to some other base orientation, not to the fixed coordinate frame. Callback functions @@ -768,47 +766,47 @@ Callback functions .. c:type:: em_deviceorientation_callback_func - Function pointer for the :c:func:`orientation event callback functions `, defined as: + Function pointer for the :c:func:`orientation event callback functions `, defined as: + + .. code-block:: cpp + + typedef EM_BOOL (*em_deviceorientation_callback_func)(int eventType, const EmscriptenDeviceOrientationEvent *deviceOrientationEvent, void *userData); + + :param int eventType: The type of orientation event (:c:data:`EMSCRIPTEN_EVENT_DEVICEORIENTATION`). + :param deviceOrientationEvent: Information about the orientation event that occurred. + :type deviceOrientationEvent: const EmscriptenDeviceOrientationEvent* + :param void* userData: The ``userData`` originally passed to the registration function. + :returns: |callback-handler-return-value-doc| + :rtype: |EM_BOOL| - .. code-block:: cpp - typedef EM_BOOL (*em_deviceorientation_callback_func)(int eventType, const EmscriptenDeviceOrientationEvent *deviceOrientationEvent, void *userData); - - :param int eventType: The type of orientation event (:c:data:`EMSCRIPTEN_EVENT_DEVICEORIENTATION`). - :param deviceOrientationEvent: Information about the orientation event that occurred. - :type deviceOrientationEvent: const EmscriptenDeviceOrientationEvent* - :param void* userData: The ``userData`` originally passed to the registration function. - :returns: |callback-handler-return-value-doc| - :rtype: |EM_BOOL| - - Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_deviceorientation_callback(void *userData, EM_BOOL useCapture, em_deviceorientation_callback_func callback) - - Registers a callback function for receiving the `deviceorientation `_ event. - :param void* userData: |userData-parameter-doc| - :param EM_BOOL useCapture: |useCapture-parameter-doc| - :param em_deviceorientation_callback_func callback: |callback-function-parameter-doc| - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + Registers a callback function for receiving the `deviceorientation `_ event. + + :param void* userData: |userData-parameter-doc| + :param EM_BOOL useCapture: |useCapture-parameter-doc| + :param em_deviceorientation_callback_func callback: |callback-function-parameter-doc| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: EMSCRIPTEN_RESULT emscripten_get_deviceorientation_status(EmscriptenDeviceOrientationEvent *orientationState) - Returns the most recently received ``deviceorientation`` event state. - - Note that for this function call to succeed, :c:func:`emscripten_set_deviceorientation_callback` must have first been called with one of the mouse event types and a non-zero callback function pointer to enable the ``deviceorientation`` state capture. + Returns the most recently received ``deviceorientation`` event state. + + Note that for this function call to succeed, :c:func:`emscripten_set_deviceorientation_callback` must have first been called with one of the mouse event types and a non-zero callback function pointer to enable the ``deviceorientation`` state capture. + + :param orientationState: The most recently received ``deviceorientation`` event state. + :type orientationState: EmscriptenDeviceOrientationEvent* + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| - :param orientationState: The most recently received ``deviceorientation`` event state. - :type orientationState: EmscriptenDeviceOrientationEvent* - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| - Device motion ============= @@ -817,7 +815,7 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_DEVICEMOTION - + Emscripten `devicemotion `_ event. @@ -826,81 +824,81 @@ Struct .. c:type:: EmscriptenDeviceMotionEvent - The event structure passed in the `devicemotion `_ event. - - .. c:member:: double timestamp - - Absolute wallclock time when the event occurred (milliseconds). + The event structure passed in the `devicemotion `_ event. + + .. c:member:: double timestamp + + Absolute wallclock time when the event occurred (milliseconds). + + + .. c:member:: double accelerationX + double accelerationY + double accelerationZ + + Acceleration of the device excluding gravity. - .. c:member:: double accelerationX - double accelerationY - double accelerationZ - - Acceleration of the device excluding gravity. + .. c:member:: double accelerationIncludingGravityX + double accelerationIncludingGravityY + double accelerationIncludingGravityZ - - .. c:member:: double accelerationIncludingGravityX - double accelerationIncludingGravityY - double accelerationIncludingGravityZ + Acceleration of the device including gravity. - Acceleration of the device including gravity. + .. c:member:: double rotationRateAlpha + double rotationRateBeta + double rotationRateGamma + + The rotational delta of the device. - .. c:member:: double rotationRateAlpha - double rotationRateBeta - double rotationRateGamma - - The rotational delta of the device. - Callback functions ------------------ .. c:type:: em_devicemotion_callback_func - Function pointer for the :c:func:`devicemotion event callback functions `, defined as: + Function pointer for the :c:func:`devicemotion event callback functions `, defined as: + + .. code-block:: cpp + + typedef EM_BOOL (*em_devicemotion_callback_func)(int eventType, const EmscriptenDeviceMotionEvent *deviceMotionEvent, void *userData); + + :param int eventType: The type of devicemotion event (:c:data:`EMSCRIPTEN_EVENT_DEVICEMOTION`). + :param deviceMotionEvent: Information about the devicemotion event that occurred. + :type deviceMotionEvent: const EmscriptenDeviceMotionEvent* + :param void* userData: The ``userData`` originally passed to the registration function. + :returns: |callback-handler-return-value-doc| + :rtype: |EM_BOOL| - .. code-block:: cpp - typedef EM_BOOL (*em_devicemotion_callback_func)(int eventType, const EmscriptenDeviceMotionEvent *deviceMotionEvent, void *userData); - - :param int eventType: The type of devicemotion event (:c:data:`EMSCRIPTEN_EVENT_DEVICEMOTION`). - :param deviceMotionEvent: Information about the devicemotion event that occurred. - :type deviceMotionEvent: const EmscriptenDeviceMotionEvent* - :param void* userData: The ``userData`` originally passed to the registration function. - :returns: |callback-handler-return-value-doc| - :rtype: |EM_BOOL| - - Functions ---------- - +--------- + .. c:function:: EMSCRIPTEN_RESULT emscripten_set_devicemotion_callback(void *userData, EM_BOOL useCapture, em_devicemotion_callback_func callback) - - Registers a callback function for receiving the `devicemotion `_ event. - :param void* userData: |userData-parameter-doc| - :param EM_BOOL useCapture: |useCapture-parameter-doc| - :param em_devicemotion_callback_func callback: |callback-function-parameter-doc| - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + Registers a callback function for receiving the `devicemotion `_ event. + + :param void* userData: |userData-parameter-doc| + :param EM_BOOL useCapture: |useCapture-parameter-doc| + :param em_devicemotion_callback_func callback: |callback-function-parameter-doc| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: EMSCRIPTEN_RESULT emscripten_get_devicemotion_status(EmscriptenDeviceMotionEvent *motionState) - Returns the most recently received `devicemotion `_ event state. - - Note that for this function call to succeed, :c:func:`emscripten_set_devicemotion_callback` must have first been called with one of the mouse event types and a non-zero callback function pointer to enable the ``devicemotion`` state capture. + Returns the most recently received `devicemotion `_ event state. + + Note that for this function call to succeed, :c:func:`emscripten_set_devicemotion_callback` must have first been called with one of the mouse event types and a non-zero callback function pointer to enable the ``devicemotion`` state capture. + + :param motionState: The most recently received ``devicemotion`` event state. + :type motionState: EmscriptenDeviceMotionEvent* + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| - :param motionState: The most recently received ``devicemotion`` event state. - :type motionState: EmscriptenDeviceMotionEvent* - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| - Orientation =========== @@ -909,104 +907,104 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_ORIENTATIONCHANGE - + Emscripten `orientationchange `_ event. - - + + .. c:macro:: EMSCRIPTEN_ORIENTATION_PORTRAIT_PRIMARY - Primary portrait mode orientation. + Primary portrait mode orientation. .. c:macro:: EMSCRIPTEN_ORIENTATION_PORTRAIT_SECONDARY - Secondary portrait mode orientation. - + Secondary portrait mode orientation. + .. c:macro:: EMSCRIPTEN_ORIENTATION_LANDSCAPE_PRIMARY - Primary landscape mode orientation. - + Primary landscape mode orientation. + .. c:macro:: EMSCRIPTEN_ORIENTATION_LANDSCAPE_SECONDARY - Secondary landscape mode orientation. + Secondary landscape mode orientation. + - Struct ------ .. c:type:: EmscriptenOrientationChangeEvent - The event structure passed in the `orientationchange `_ event. - - - .. c:member:: int orientationIndex - - One of the :c:type:`EM_ORIENTATION_PORTRAIT_xxx ` fields, or -1 if unknown. + The event structure passed in the `orientationchange `_ event. + + + .. c:member:: int orientationIndex + + One of the :c:type:`EM_ORIENTATION_PORTRAIT_xxx ` fields, or -1 if unknown. + + .. c:member:: int orientationAngle + + Emscripten-specific extension: Some browsers refer to ``window.orientation``, so report that as well. + + Orientation angle in degrees. 0: "default orientation", i.e. default upright orientation to hold the mobile device in. Could be either landscape or portrait. - .. c:member:: int orientationAngle - - Emscripten-specific extension: Some browsers refer to ``window.orientation``, so report that as well. - - Orientation angle in degrees. 0: "default orientation", i.e. default upright orientation to hold the mobile device in. Could be either landscape or portrait. - Callback functions ------------------ .. c:type:: em_orientationchange_callback_func - Function pointer for the :c:func:`orientationchange event callback functions `, defined as: + Function pointer for the :c:func:`orientationchange event callback functions `, defined as: + + .. code-block:: cpp - .. code-block:: cpp + typedef EM_BOOL (*em_orientationchange_callback_func)(int eventType, const EmscriptenOrientationChangeEvent *orientationChangeEvent, void *userData); + + :param int eventType: The type of orientationchange event (:c:data:`EMSCRIPTEN_EVENT_ORIENTATIONCHANGE`). + :param orientationChangeEvent: Information about the orientationchange event that occurred. + :type orientationChangeEvent: const EmscriptenOrientationChangeEvent* + :param void* userData: The ``userData`` originally passed to the registration function. + :returns: |callback-handler-return-value-doc| + :rtype: |EM_BOOL| - typedef EM_BOOL (*em_orientationchange_callback_func)(int eventType, const EmscriptenOrientationChangeEvent *orientationChangeEvent, void *userData); - - :param int eventType: The type of orientationchange event (:c:data:`EMSCRIPTEN_EVENT_ORIENTATIONCHANGE`). - :param orientationChangeEvent: Information about the orientationchange event that occurred. - :type orientationChangeEvent: const EmscriptenOrientationChangeEvent* - :param void* userData: The ``userData`` originally passed to the registration function. - :returns: |callback-handler-return-value-doc| - :rtype: |EM_BOOL| - Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_orientationchange_callback(void *userData, EM_BOOL useCapture, em_orientationchange_callback_func callback) - - Registers a callback function for receiving the `orientationchange `_ event. - :param void* userData: |userData-parameter-doc| - :param EM_BOOL useCapture: |useCapture-parameter-doc| - :param em_orientationchange_callback_func callback: |callback-function-parameter-doc| - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + Registers a callback function for receiving the `orientationchange `_ event. + + :param void* userData: |userData-parameter-doc| + :param EM_BOOL useCapture: |useCapture-parameter-doc| + :param em_orientationchange_callback_func callback: |callback-function-parameter-doc| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: EMSCRIPTEN_RESULT emscripten_get_orientation_status(EmscriptenOrientationChangeEvent *orientationStatus) - Returns the current device orientation state. + Returns the current device orientation state. + + :param orientationStatus: The most recently received orientation state. + :type orientationStatus: EmscriptenOrientationChangeEvent* + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| - :param orientationStatus: The most recently received orientation state. - :type orientationStatus: EmscriptenOrientationChangeEvent* - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| - .. c:function:: EMSCRIPTEN_RESULT emscripten_lock_orientation(int allowedOrientations) - Locks the screen orientation to the given set of :c:data:`allowed orientations `. + Locks the screen orientation to the given set of :c:data:`allowed orientations `. - :param int allowedOrientations: A bitfield set of :c:data:`EMSCRIPTEN_ORIENTATION_xxx ` flags. - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :param int allowedOrientations: A bitfield set of :c:data:`EMSCRIPTEN_ORIENTATION_xxx ` flags. + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: EMSCRIPTEN_RESULT emscripten_unlock_orientation(void) - Removes the orientation lock so the screen can turn to any orientation. + Removes the orientation lock so the screen can turn to any orientation. - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| @@ -1017,235 +1015,235 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_FULLSCREENCHANGE - + Emscripten `fullscreenchange `_ event. .. c:macro:: EMSCRIPTEN_FULLSCREEN_SCALE - An enum-like type which specifies how the Emscripten runtime should treat the CSS size of the target element when displaying it in fullscreen mode via calls to functions - :c:func:`emscripten_request_fullscreen_strategy` and :c:func:`emscripten_enter_soft_fullscreen`. + An enum-like type which specifies how the Emscripten runtime should treat the CSS size of the target element when displaying it in fullscreen mode via calls to functions + :c:func:`emscripten_request_fullscreen_strategy` and :c:func:`emscripten_enter_soft_fullscreen`. .. c:macro:: EMSCRIPTEN_FULLSCREEN_SCALE_DEFAULT - Specifies that the DOM element should not be resized by Emscripten runtime when transitioning between fullscreen and windowed modes. The browser will be responsible for + Specifies that the DOM element should not be resized by Emscripten runtime when transitioning between fullscreen and windowed modes. The browser will be responsible for scaling the DOM element to the fullscreen size. The proper browser behavior in this mode is to stretch the element to fit the full display ignoring aspect ratio, but at the time of writing, browsers implement different behavior here. See the discussion at https://github.com/kripken/emscripten/issues/2556 for more information. .. c:macro:: EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH - Specifies that the Emscripten runtime should explicitly stretch the CSS size of the target element to cover the whole screen when transitioning to fullscreen mode. This - will change the aspect ratio of the displayed content. + Specifies that the Emscripten runtime should explicitly stretch the CSS size of the target element to cover the whole screen when transitioning to fullscreen mode. This + will change the aspect ratio of the displayed content. .. c:macro:: EMSCRIPTEN_FULLSCREEN_SCALE_ASPECT - Specifies that the Emscripten runtime should explicitly scale the CSS size of the target element to cover the whole screen, while adding either vertical or horizontal - black letterbox padding to preserve the aspect ratio of the content. The aspect ratio that is used here is the render target size of the canvas element. To change the - desired aspect ratio, call :c:func:`emscripten_set_canvas_size` before entering fullscreen mode. + Specifies that the Emscripten runtime should explicitly scale the CSS size of the target element to cover the whole screen, while adding either vertical or horizontal + black letterbox padding to preserve the aspect ratio of the content. The aspect ratio that is used here is the render target size of the canvas element. To change the + desired aspect ratio, call :c:func:`emscripten_set_canvas_size` before entering fullscreen mode. .. c:macro:: EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE - An enum-like type which specifies how the Emscripten runtime should treat the pixel size (render target resolution) of the target canvas element when displaying it in - fullscreen mode via calls to functions :c:func:`emscripten_request_fullscreen_strategy` and :c:func:`emscripten_enter_soft_fullscreen`. To better understand the - underlying distinction between the CSS size of a canvas element versus the render target size of a canvas element, see https://www.khronos.org/webgl/wiki/HandlingHighDPI. + An enum-like type which specifies how the Emscripten runtime should treat the pixel size (render target resolution) of the target canvas element when displaying it in + fullscreen mode via calls to functions :c:func:`emscripten_request_fullscreen_strategy` and :c:func:`emscripten_enter_soft_fullscreen`. To better understand the + underlying distinction between the CSS size of a canvas element versus the render target size of a canvas element, see https://www.khronos.org/webgl/wiki/HandlingHighDPI. .. c:macro:: EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_NONE - Specifies that the Emscripten runtime should not do any changes to the render target resolution of the target canvas element that is displayed in fullscreen mode. Use - this mode when your application is set up to render to a single fixed resolution that cannot be changed under any condition. + Specifies that the Emscripten runtime should not do any changes to the render target resolution of the target canvas element that is displayed in fullscreen mode. Use + this mode when your application is set up to render to a single fixed resolution that cannot be changed under any condition. .. c:macro:: EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF - Specifies that the Emscripten runtime should resize the render target of the canvas element to match 1:1 with the CSS size of the element in fullscreen mode. On high DPI - displays (`window.devicePixelRatio` > 1), the CSS size is not the same as the physical screen resolution of the device. Call :c:func:`emscripten_get_device_pixel_ratio` - to obtain the pixel ratio between CSS pixels and actual device pixels of the screen. Use this mode when you want to render to a pixel resolution that is DPI-independent. + Specifies that the Emscripten runtime should resize the render target of the canvas element to match 1:1 with the CSS size of the element in fullscreen mode. On high DPI + displays (`window.devicePixelRatio` > 1), the CSS size is not the same as the physical screen resolution of the device. Call :c:func:`emscripten_get_device_pixel_ratio` + to obtain the pixel ratio between CSS pixels and actual device pixels of the screen. Use this mode when you want to render to a pixel resolution that is DPI-independent. .. c:macro:: EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_HIDEF - Specifies that the Emscripten runtime should resize the canvas render target size to match 1:1 with the physical screen resolution on the device. This corresponds to high - definition displays on retina iOS and other mobile and desktop devices with high DPI. Use this mode to match and render 1:1 to the native display resolution. + Specifies that the Emscripten runtime should resize the canvas render target size to match 1:1 with the physical screen resolution on the device. This corresponds to high + definition displays on retina iOS and other mobile and desktop devices with high DPI. Use this mode to match and render 1:1 to the native display resolution. .. c:macro:: EMSCRIPTEN_FULLSCREEN_FILTERING - An enum-like type that specifies what kind of image filtering algorithm to apply to the element when it is presented in fullscreen mode. + An enum-like type that specifies what kind of image filtering algorithm to apply to the element when it is presented in fullscreen mode. .. c:macro:: EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT - Specifies that the image filtering mode should not be changed from the existing setting in the CSS style. + Specifies that the image filtering mode should not be changed from the existing setting in the CSS style. .. c:macro:: EMSCRIPTEN_FULLSCREEN_FILTERING_NEAREST - Applies a CSS style to the element that displays the content using a nearest-neighbor image filtering algorithm in fullscreen mode. + Applies a CSS style to the element that displays the content using a nearest-neighbor image filtering algorithm in fullscreen mode. .. c:macro:: EMSCRIPTEN_FULLSCREEN_FILTERING_BILINEAR - Applies a CSS style to the element that displays the content using a bilinear image filtering algorithm in fullscreen mode. This is the default browser behavior. + Applies a CSS style to the element that displays the content using a bilinear image filtering algorithm in fullscreen mode. This is the default browser behavior. Struct ------ .. c:type:: EmscriptenFullscreenChangeEvent - The event structure passed in the `fullscreenchange `_ event. - - .. c:member:: EM_BOOL isFullscreen - - Specifies whether an element on the browser page is currently fullscreen. - - - .. c:member:: EM_BOOL fullscreenEnabled - - Specifies if the current page has the ability to display elements fullscreen. - - .. c:member:: EM_UTF8 nodeName - - The `nodeName `_ of the target HTML Element that is in full screen mode. - - Maximum size 128 ``char`` (i.e. ``EM_UTF8 nodeName[128]``). - - If ``isFullscreen`` is ``false``, then ``nodeName``, ``id`` and ``elementWidth`` and ``elementHeight`` specify information about the element that just exited fullscreen mode. - - - .. c:member:: EM_UTF8 id - - The ID of the target HTML element that is in full screen mode. - - Maximum size 128 ``char`` (i.e. ``EM_UTF8 id[128]``). - - - .. c:member:: int elementWidth - int elementHeight - - The new pixel size of the element that changed fullscreen status. - - - .. c:member:: int screenWidth - int screenHeight - - The size of the whole screen, in pixels. + The event structure passed in the `fullscreenchange `_ event. + + .. c:member:: EM_BOOL isFullscreen + + Specifies whether an element on the browser page is currently fullscreen. + + + .. c:member:: EM_BOOL fullscreenEnabled + + Specifies if the current page has the ability to display elements fullscreen. + + .. c:member:: EM_UTF8 nodeName + + The `nodeName `_ of the target HTML Element that is in full screen mode. + + Maximum size 128 ``char`` (i.e. ``EM_UTF8 nodeName[128]``). + + If ``isFullscreen`` is ``false``, then ``nodeName``, ``id`` and ``elementWidth`` and ``elementHeight`` specify information about the element that just exited fullscreen mode. + + + .. c:member:: EM_UTF8 id + + The ID of the target HTML element that is in full screen mode. + + Maximum size 128 ``char`` (i.e. ``EM_UTF8 id[128]``). + + + .. c:member:: int elementWidth + int elementHeight + + The new pixel size of the element that changed fullscreen status. + + + .. c:member:: int screenWidth + int screenHeight + + The size of the whole screen, in pixels. .. c:type:: EmscriptenFullscreenStrategy - The options structure that is passed in to functions :c:func:`emscripten_request_fullscreen_strategy` and :c:func:`emscripten_enter_soft_fullscreen` to configure how the target - element should be displayed in fullscreen mode. + The options structure that is passed in to functions :c:func:`emscripten_request_fullscreen_strategy` and :c:func:`emscripten_enter_soft_fullscreen` to configure how the target + element should be displayed in fullscreen mode. + + .. c:member:: EMSCRIPTEN_FULLSCREEN_SCALE scaleMode - .. c:member:: EMSCRIPTEN_FULLSCREEN_SCALE scaleMode + Specifies the rule how the CSS size (the displayed size) of the target element is resized when displayed in fullscreen mode. - Specifies the rule how the CSS size (the displayed size) of the target element is resized when displayed in fullscreen mode. + .. c:member:: EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE canvasResolutionScaleMode - .. c:member:: EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE canvasResolutionScaleMode + Specifies how the render target size (the pixel resolution) of the target element is adjusted when displayed in fullscreen mode. - Specifies how the render target size (the pixel resolution) of the target element is adjusted when displayed in fullscreen mode. + .. c:member:: EMSCRIPTEN_FULLSCREEN_FILTERING filteringMode - .. c:member:: EMSCRIPTEN_FULLSCREEN_FILTERING filteringMode + Specifies the image filtering algorithm to apply to the element in fullscreen mode. - Specifies the image filtering algorithm to apply to the element in fullscreen mode. + .. c:member:: em_canvasresized_callback_func canvasResizedCallback - .. c:member:: em_canvasresized_callback_func canvasResizedCallback + If nonzero, points to a user-provided callback function which will be called whenever either the CSS or the canvas render target size changes. Use this callback to reliably + obtain information about canvas resize events. - If nonzero, points to a user-provided callback function which will be called whenever either the CSS or the canvas render target size changes. Use this callback to reliably - obtain information about canvas resize events. + .. c:member:: void *canvasResizedCallbackUserData - .. c:member:: void *canvasResizedCallbackUserData + Stores a custom data field which will be passed to all calls to the user-provided callback function. - Stores a custom data field which will be passed to all calls to the user-provided callback function. - Callback functions ------------------ .. c:type:: em_fullscreenchange_callback_func - Function pointer for the :c:func:`fullscreen event callback functions `, defined as: + Function pointer for the :c:func:`fullscreen event callback functions `, defined as: + + .. code-block:: cpp - .. code-block:: cpp + typedef EM_BOOL (*em_fullscreenchange_callback_func)(int eventType, const EmscriptenFullscreenChangeEvent *fullscreenChangeEvent, void *userData); + + :param int eventType: The type of fullscreen event (:c:data:`EMSCRIPTEN_EVENT_FULLSCREENCHANGE`). + :param fullscreenChangeEvent: Information about the fullscreen event that occurred. + :type fullscreenChangeEvent: const EmscriptenFullscreenChangeEvent* + :param void* userData: The ``userData`` originally passed to the registration function. + :returns: |callback-handler-return-value-doc| + :rtype: |EM_BOOL| - typedef EM_BOOL (*em_fullscreenchange_callback_func)(int eventType, const EmscriptenFullscreenChangeEvent *fullscreenChangeEvent, void *userData); - - :param int eventType: The type of fullscreen event (:c:data:`EMSCRIPTEN_EVENT_FULLSCREENCHANGE`). - :param fullscreenChangeEvent: Information about the fullscreen event that occurred. - :type fullscreenChangeEvent: const EmscriptenFullscreenChangeEvent* - :param void* userData: The ``userData`` originally passed to the registration function. - :returns: |callback-handler-return-value-doc| - :rtype: |EM_BOOL| - Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_fullscreenchange_callback(const char *target, void *userData, EM_BOOL useCapture, em_fullscreenchange_callback_func callback) - - Registers a callback function for receiving the `fullscreenchange `_ event. - - :param target: |target-parameter-doc| - :type target: const char* - :param void* userData: |userData-parameter-doc| - :param EM_BOOL useCapture: |useCapture-parameter-doc| - :param em_fullscreenchange_callback_func callback: |callback-function-parameter-doc| - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + + Registers a callback function for receiving the `fullscreenchange `_ event. + + :param target: |target-parameter-doc| + :type target: const char* + :param void* userData: |userData-parameter-doc| + :param EM_BOOL useCapture: |useCapture-parameter-doc| + :param em_fullscreenchange_callback_func callback: |callback-function-parameter-doc| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: EMSCRIPTEN_RESULT emscripten_get_fullscreen_status(EmscriptenFullscreenChangeEvent *fullscreenStatus) - Returns the current page `fullscreen `_ state. + Returns the current page `fullscreen `_ state. - :param fullscreenStatus: The most recently received fullscreen state. - :type fullscreenStatus: EmscriptenFullscreenChangeEvent* - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :param fullscreenStatus: The most recently received fullscreen state. + :type fullscreenStatus: EmscriptenFullscreenChangeEvent* + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: EMSCRIPTEN_RESULT emscripten_request_fullscreen(const char *target, EM_BOOL deferUntilInEventHandler) - Requests the given target element to transition to full screen mode. - - .. note:: This function can be called anywhere, but for web security reasons its associated *request* can only be raised inside the event handler for a user-generated event (for example a key, mouse or touch press/release). This has implications for porting and the value of ``deferUntilInEventHandler`` — see :ref:`web-security-functions-html5-api` for more information. + Requests the given target element to transition to full screen mode. + + .. note:: This function can be called anywhere, but for web security reasons its associated *request* can only be raised inside the event handler for a user-generated event (for example a key, mouse or touch press/release). This has implications for porting and the value of ``deferUntilInEventHandler`` — see :ref:`web-security-functions-html5-api` for more information. + + .. note:: This function only performs a fullscreen request without changing any parameters of the DOM element that is to be displayed in fullscreen mode. At the time of writing, there are differences in how browsers present elements in fullscreen mode. For more information, read the discussion at https://github.com/kripken/emscripten/issues/2556. To display an element in fullscreen mode in a way that is consistent across browsers, prefer calling the function :c:func:`emscripten_request_fullscreen_strategy` instead. This function is best called only in scenarios where the preconfigured presets defined by :c:func:`emscripten_request_fullscreen_strategy` conflict with the developer's use case in some way. + + :param target: |target-parameter-doc| + :type target: const char* + :param EM_BOOL deferUntilInEventHandler: If ``true`` requests made outside of a user-generated event handler are automatically deferred until the user next presses a keyboard or mouse button. If ``false`` the request will fail if called outside of a user-generated event handler. - .. note:: This function only performs a fullscreen request without changing any parameters of the DOM element that is to be displayed in fullscreen mode. At the time of writing, there are differences in how browsers present elements in fullscreen mode. For more information, read the discussion at https://github.com/kripken/emscripten/issues/2556. To display an element in fullscreen mode in a way that is consistent across browsers, prefer calling the function :c:func:`emscripten_request_fullscreen_strategy` instead. This function is best called only in scenarios where the preconfigured presets defined by :c:func:`emscripten_request_fullscreen_strategy` conflict with the developer's use case in some way. + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: **EMSCRIPTEN_RESULT** - :param target: |target-parameter-doc| - :type target: const char* - :param EM_BOOL deferUntilInEventHandler: If ``true`` requests made outside of a user-generated event handler are automatically deferred until the user next presses a keyboard or mouse button. If ``false`` the request will fail if called outside of a user-generated event handler. - - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: **EMSCRIPTEN_RESULT** - .. c:function:: EMSCRIPTEN_RESULT emscripten_request_fullscreen_strategy(const char *target, EM_BOOL deferUntilInEventHandler, const EmscriptenFullscreenStrategy *fullscreenStrategy) - Requests the given target element to transition to full screen mode, using a custom presentation mode for the element. This function is otherwise the same as :c:func:`emscripten_request_fullscreen`, but this function adds options to control how resizing and aspect ratio, and ensures that the behavior is consistent across browsers. + Requests the given target element to transition to full screen mode, using a custom presentation mode for the element. This function is otherwise the same as :c:func:`emscripten_request_fullscreen`, but this function adds options to control how resizing and aspect ratio, and ensures that the behavior is consistent across browsers. - .. note:: This function makes changes to the DOM to satisfy consistent presentation across browsers. These changes have been designed to intrude as little as possible, and the changes are cleared once windowed browsing is restored. If any of these changes are conflicting, see the function :c:func:`emscripten_request_fullscreen` instead, which performs a bare fullscreen request without any modifications to the DOM. + .. note:: This function makes changes to the DOM to satisfy consistent presentation across browsers. These changes have been designed to intrude as little as possible, and the changes are cleared once windowed browsing is restored. If any of these changes are conflicting, see the function :c:func:`emscripten_request_fullscreen` instead, which performs a bare fullscreen request without any modifications to the DOM. - :param fullscreenStrategy: [in] Points to a configuration structure filled by the caller which specifies display options for the fullscreen mode. - :type fullscreenStrategy: const EmscriptenFullscreenStrategy* + :param fullscreenStrategy: [in] Points to a configuration structure filled by the caller which specifies display options for the fullscreen mode. + :type fullscreenStrategy: const EmscriptenFullscreenStrategy* .. c:function:: EMSCRIPTEN_RESULT emscripten_exit_fullscreen(void) - Returns back to windowed browsing mode from a proper fullscreen mode. + Returns back to windowed browsing mode from a proper fullscreen mode. - Do not call this function to attempt to return to windowed browsing mode from a soft fullscreen mode, or vice versa. + Do not call this function to attempt to return to windowed browsing mode from a soft fullscreen mode, or vice versa. - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: EMSCRIPTEN_RESULT emscripten_enter_soft_fullscreen(const char *target, const EmscriptenFullscreenStrategy *fullscreenStrategy) - Enters a "soft" fullscreen mode, where the given target element is displayed in the whole client area of the page and all other elements are hidden, but does not actually request fullscreen mode for the browser. This function is useful in cases where the actual Fullscreen API is not desirable or needed, for example in packaged apps for Firefox OS, where applications essentially already cover the whole screen. + Enters a "soft" fullscreen mode, where the given target element is displayed in the whole client area of the page and all other elements are hidden, but does not actually request fullscreen mode for the browser. This function is useful in cases where the actual Fullscreen API is not desirable or needed, for example in packaged apps for Firefox OS, where applications essentially already cover the whole screen. - Pressing the esc button does not automatically exit the soft fullscreen mode. To return to windowed presentation mode, manually call the function :c:func:`emscripten_exit_soft_fullscreen`. + Pressing the esc button does not automatically exit the soft fullscreen mode. To return to windowed presentation mode, manually call the function :c:func:`emscripten_exit_soft_fullscreen`. .. c:function:: EMSCRIPTEN_RESULT emscripten_exit_soft_fullscreen() - Returns back to windowed browsing mode from a soft fullscreen mode. Do not call this function to attempt to return to windowed browsing mode from a real fullscreen mode, or vice versa. + Returns back to windowed browsing mode from a soft fullscreen mode. Do not call this function to attempt to return to windowed browsing mode from a real fullscreen mode, or vice versa. -Pointerlock +Pointerlock =========== Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_POINTERLOCKCHANGE - + Emscripten `pointerlockchange `_ event. .. c:macro:: EMSCRIPTEN_EVENT_POINTERLOCKERROR @@ -1257,24 +1255,24 @@ Struct .. c:type:: EmscriptenPointerlockChangeEvent - The event structure passed in the `pointerlockchange `_ event. + The event structure passed in the `pointerlockchange `_ event. + + + .. c:member:: EM_BOOL isActive - - .. c:member:: EM_BOOL isActive - - Specifies whether an element on the browser page currently has pointer lock enabled. + Specifies whether an element on the browser page currently has pointer lock enabled. - .. c:member:: EM_UTF8 nodeName - - The `nodeName `_ of the target HTML Element that has the pointer lock active. - - Maximum size 128 ``char`` (i.e. ``EM_UTF8 nodeName[128]``). - - .. c:member:: EM_UTF8 id - - The ID of the target HTML element that has the pointer lock active. - - Maximum size 128 ``char`` (i.e. ``EM_UTF8 id[128]``). + .. c:member:: EM_UTF8 nodeName + + The `nodeName `_ of the target HTML Element that has the pointer lock active. + + Maximum size 128 ``char`` (i.e. ``EM_UTF8 nodeName[128]``). + + .. c:member:: EM_UTF8 id + + The ID of the target HTML element that has the pointer lock active. + + Maximum size 128 ``char`` (i.e. ``EM_UTF8 id[128]``). Callback functions @@ -1282,99 +1280,98 @@ Callback functions .. c:type:: em_pointerlockchange_callback_func - Function pointer for the :c:func:`pointerlockchange event callback functions `, defined as: + Function pointer for the :c:func:`pointerlockchange event callback functions `, defined as: + + .. code-block:: cpp - .. code-block:: cpp + typedef EM_BOOL (*em_pointerlockchange_callback_func)(int eventType, const EmscriptenPointerlockChangeEvent *pointerlockChangeEvent, void *userData); - typedef EM_BOOL (*em_pointerlockchange_callback_func)(int eventType, const EmscriptenPointerlockChangeEvent *pointerlockChangeEvent, void *userData); - - :param int eventType: The type of pointerlockchange event (:c:data:`EMSCRIPTEN_EVENT_POINTERLOCKCHANGE`). - :param pointerlockChangeEvent: Information about the pointerlockchange event that occurred. - :type pointerlockChangeEvent: const EmscriptenPointerlockChangeEvent* - :param void* userData: The ``userData`` originally passed to the registration function. - :returns: |callback-handler-return-value-doc| - :rtype: |EM_BOOL| + :param int eventType: The type of pointerlockchange event (:c:data:`EMSCRIPTEN_EVENT_POINTERLOCKCHANGE`). + :param pointerlockChangeEvent: Information about the pointerlockchange event that occurred. + :type pointerlockChangeEvent: const EmscriptenPointerlockChangeEvent* + :param void* userData: The ``userData`` originally passed to the registration function. + :returns: |callback-handler-return-value-doc| + :rtype: |EM_BOOL| .. c:type:: em_pointerlockerror_callback_func - Function pointer for the :c:func:`pointerlockerror event callback functions `, defined as: + Function pointer for the :c:func:`pointerlockerror event callback functions `, defined as: - .. code-block:: cpp + .. code-block:: cpp + + typedef EM_BOOL (*em_pointerlockerror_callback_func)(int eventType, const void *reserved, void *userData); + + :param int eventType: The type of pointerlockerror event (:c:data:`EMSCRIPTEN_EVENT_POINTERLOCKERROR`). + :param const void* reserved: Reserved for future use; pass in 0. + :param void* userData: The ``userData`` originally passed to the registration function. + :returns: |callback-handler-return-value-doc| + :rtype: |EM_BOOL| - typedef EM_BOOL (*em_pointerlockerror_callback_func)(int eventType, const void *reserved, void *userData); - :param int eventType: The type of pointerlockerror event (:c:data:`EMSCRIPTEN_EVENT_POINTERLOCKERROR`). - :param const void* reserved: Reserved for future use; pass in 0. - :param void* userData: The ``userData`` originally passed to the registration function. - :returns: |callback-handler-return-value-doc| - :rtype: |EM_BOOL| - - Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_pointerlockchange_callback(const char *target, void *userData, EM_BOOL useCapture, em_pointerlockchange_callback_func callback) - - Registers a callback function for receiving the `pointerlockchange `_ event. - - Pointer lock hides the mouse cursor and exclusively gives the target element relative mouse movement events via the `mousemove `_ event. - :param target: |target-parameter-doc| - :type target: const char* - :param void* userData: |userData-parameter-doc| - :param EM_BOOL useCapture: |useCapture-parameter-doc| - :param em_pointerlockchange_callback_func callback: |callback-function-parameter-doc| - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + Registers a callback function for receiving the `pointerlockchange `_ event. + + Pointer lock hides the mouse cursor and exclusively gives the target element relative mouse movement events via the `mousemove `_ event. + + :param target: |target-parameter-doc| + :type target: const char* + :param void* userData: |userData-parameter-doc| + :param EM_BOOL useCapture: |useCapture-parameter-doc| + :param em_pointerlockchange_callback_func callback: |callback-function-parameter-doc| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: EMSCRIPTEN_RESULT emscripten_set_pointerlockerror_callback(const char *target, void *userData, EM_BOOL useCapture, em_pointerlockerror_callback_func callback) - Registers a callback function for receiving the `pointerlockerror `_ event. + Registers a callback function for receiving the `pointerlockerror `_ event. - :param target: |target-parameter-doc| - :type target: const char* - :param void* userData: |userData-parameter-doc| - :param EM_BOOL useCapture: |useCapture-parameter-doc| - :param em_pointerlockerror_callback_func callback: |callback-function-parameter-doc| - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :param target: |target-parameter-doc| + :type target: const char* + :param void* userData: |userData-parameter-doc| + :param EM_BOOL useCapture: |useCapture-parameter-doc| + :param em_pointerlockerror_callback_func callback: |callback-function-parameter-doc| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: EMSCRIPTEN_RESULT emscripten_get_pointerlock_status(EmscriptenPointerlockChangeEvent *pointerlockStatus) - Returns the current page pointerlock state. + Returns the current page pointerlock state. + + :param EmscriptenPointerlockChangeEvent* pointerlockStatus: The most recently received pointerlock state. + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| - :param EmscriptenPointerlockChangeEvent* pointerlockStatus: The most recently received pointerlock state. - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| - .. c:function:: EMSCRIPTEN_RESULT emscripten_request_pointerlock(const char *target, EM_BOOL deferUntilInEventHandler) - Requests the given target element to grab pointerlock. - - .. note:: This function can be called anywhere, but for web security reasons its associated *request* can only be raised inside the event handler for a user-generated event (for example a key, mouse or touch press/release). This has implications for porting and the value of ``deferUntilInEventHandler`` — see :ref:`web-security-functions-html5-api` for more information. + Requests the given target element to grab pointerlock. + + .. note:: This function can be called anywhere, but for web security reasons its associated *request* can only be raised inside the event handler for a user-generated event (for example a key, mouse or touch press/release). This has implications for porting and the value of ``deferUntilInEventHandler`` — see :ref:`web-security-functions-html5-api` for more information. - - :param target: |target-parameter-doc| - :type target: const char* - :param EM_BOOL deferUntilInEventHandler: If ``true`` requests made outside of a user-generated event handler are automatically deferred until the user next presses a keyboard or mouse button. If ``false`` the request will fail if called outside of a user-generated event handler. - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + + :param target: |target-parameter-doc| + :type target: const char* + :param EM_BOOL deferUntilInEventHandler: If ``true`` requests made outside of a user-generated event handler are automatically deferred until the user next presses a keyboard or mouse button. If ``false`` the request will fail if called outside of a user-generated event handler. + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: EMSCRIPTEN_RESULT emscripten_exit_pointerlock(void) - Exits pointer lock state and restores the mouse cursor to be visible again. + Exits pointer lock state and restores the mouse cursor to be visible again. - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| - Visibility @@ -1384,25 +1381,24 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_VISIBILITYCHANGE - - Emscripten `visibilitychange `_ event. + Emscripten `visibilitychange `__ event. .. c:macro:: EMSCRIPTEN_VISIBILITY_HIDDEN - The document is `hidden `_ (not visible). - + The document is `hidden `_ (not visible). + .. c:macro:: EMSCRIPTEN_VISIBILITY_VISIBLE - The document is at least partially `visible `_. + The document is at least partially `visible `_. .. c:macro:: EMSCRIPTEN_VISIBILITY_PRERENDER - The document is loaded off screen and not visible (`prerender `_). + The document is loaded off screen and not visible (`prerender `_). .. c:macro:: EMSCRIPTEN_VISIBILITY_UNLOADED - The document is to be `unloaded `_. + The document is to be `unloaded `_. Struct @@ -1410,59 +1406,58 @@ Struct .. c:type:: EmscriptenVisibilityChangeEvent - The event structure passed in the `visibilitychange `_ event. - - - .. c:member:: EM_BOOL hidden - - If true, the current browser page is now hidden. - + The event structure passed in the `visibilitychange `__ event. + + .. c:member:: EM_BOOL hidden + + If true, the current browser page is now hidden. + + + .. c:member:: int visibilityState + + Specifies a more fine-grained state of the current page visibility status. One of the :c:type:`EMSCRIPTEN_VISIBILITY_ ` values. - .. c:member:: int visibilityState - - Specifies a more fine-grained state of the current page visibility status. One of the :c:type:`EMSCRIPTEN_VISIBILITY_ ` values. - Callback functions ------------------ .. c:type:: em_visibilitychange_callback_func - Function pointer for the :c:func:`visibilitychange event callback functions `, defined as: + Function pointer for the :c:func:`visibilitychange event callback functions `, defined as: + + .. code-block:: cpp - .. code-block:: cpp + typedef EM_BOOL (*em_visibilitychange_callback_func)(int eventType, const EmscriptenVisibilityChangeEvent *visibilityChangeEvent, void *userData); + + :param int eventType: The type of ``visibilitychange`` event (:c:data:`EMSCRIPTEN_VISIBILITY_HIDDEN`). + :param visibilityChangeEvent: Information about the ``visibilitychange`` event that occurred. + :type visibilityChangeEvent: const EmscriptenVisibilityChangeEvent* + :param void* userData: The ``userData`` originally passed to the registration function. + :returns: |callback-handler-return-value-doc| + :rtype: |EM_BOOL| - typedef EM_BOOL (*em_visibilitychange_callback_func)(int eventType, const EmscriptenVisibilityChangeEvent *visibilityChangeEvent, void *userData); - - :param int eventType: The type of ``visibilitychange`` event (:c:data:`EMSCRIPTEN_VISIBILITY_HIDDEN`). - :param visibilityChangeEvent: Information about the ``visibilitychange`` event that occurred. - :type visibilityChangeEvent: const EmscriptenVisibilityChangeEvent* - :param void* userData: The ``userData`` originally passed to the registration function. - :returns: |callback-handler-return-value-doc| - :rtype: |EM_BOOL| - Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_visibilitychange_callback(void *userData, EM_BOOL useCapture, em_visibilitychange_callback_func callback) - - Registers a callback function for receiving the `visibilitychange `_ event. - :param void* userData: |userData-parameter-doc| - :param EM_BOOL useCapture: |useCapture-parameter-doc| - :param em_visibilitychange_callback_func callback: |callback-function-parameter-doc| - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + Registers a callback function for receiving the `visibilitychange `_ event. + + :param void* userData: |userData-parameter-doc| + :param EM_BOOL useCapture: |useCapture-parameter-doc| + :param em_visibilitychange_callback_func callback: |callback-function-parameter-doc| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: EMSCRIPTEN_RESULT emscripten_get_visibility_status(EmscriptenVisibilityChangeEvent *visibilityStatus) - Returns the current page visibility state. + Returns the current page visibility state. - :param EmscriptenVisibilityChangeEvent* visibilityStatus: The most recently received page visibility state. - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :param EmscriptenVisibilityChangeEvent* visibilityStatus: The most recently received page visibility state. + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| @@ -1473,119 +1468,119 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_TOUCHSTART - EMSCRIPTEN_EVENT_TOUCHEND - EMSCRIPTEN_EVENT_TOUCHMOVE - EMSCRIPTEN_EVENT_TOUCHCANCEL - + EMSCRIPTEN_EVENT_TOUCHEND + EMSCRIPTEN_EVENT_TOUCHMOVE + EMSCRIPTEN_EVENT_TOUCHCANCEL + Emscripten touch events. - + Struct ------ .. c:type:: EmscriptenTouchPoint - Specifies the status of a single `touch point `_ on the page. - - .. c:member:: long identifier - - An identification number for each touch point. - - .. c:member:: long screenX - long screenY - - The touch coordinate relative to the whole screen origin, in pixels. - - .. c:member:: long clientX - long clientY - - The touch coordinate relative to the viewport, in pixels. - - .. c:member:: long pageX - long pageY - - The touch coordinate relative to the viewport, in pixels, and including any scroll offset. - - .. c:member:: EM_BOOL isChanged - - Specifies whether the touch point changed during this event. - - .. c:member:: EM_BOOL onTarget - - Specifies whether this touch point is still above the original target on which it was initially pressed. - - .. c:member:: long targetX - long targetY - - These fields give the touch coordinates mapped relative to the coordinate space of the target DOM element receiving the input events (Emscripten-specific extension). - - .. c:member:: long canvasX - long canvasY - - The touch coordinates mapped to the Emscripten canvas client area, in pixels (Emscripten-specific extension). - - - + Specifies the status of a single `touch point `_ on the page. + + .. c:member:: long identifier + + An identification number for each touch point. + + .. c:member:: long screenX + long screenY + + The touch coordinate relative to the whole screen origin, in pixels. + + .. c:member:: long clientX + long clientY + + The touch coordinate relative to the viewport, in pixels. + + .. c:member:: long pageX + long pageY + + The touch coordinate relative to the viewport, in pixels, and including any scroll offset. + + .. c:member:: EM_BOOL isChanged + + Specifies whether the touch point changed during this event. + + .. c:member:: EM_BOOL onTarget + + Specifies whether this touch point is still above the original target on which it was initially pressed. + + .. c:member:: long targetX + long targetY + + These fields give the touch coordinates mapped relative to the coordinate space of the target DOM element receiving the input events (Emscripten-specific extension). + + .. c:member:: long canvasX + long canvasY + + The touch coordinates mapped to the Emscripten canvas client area, in pixels (Emscripten-specific extension). + + + .. c:type:: EmscriptenTouchEvent - Specifies the data of a single `touchevent `_. - - .. c:member:: int numTouches - - The number of valid elements in the touches array. - - - .. c:member:: EM_BOOL ctrlKey - EM_BOOL shiftKey - EM_BOOL altKey - EM_BOOL metaKey - - Specifies which modifiers were active during the touch event. - - .. c:member:: EmscriptenTouchPoint touches[32] - - An array of currently active touches, one for each finger. - - - + Specifies the data of a single `touchevent `_. + + .. c:member:: int numTouches + + The number of valid elements in the touches array. + + + .. c:member:: EM_BOOL ctrlKey + EM_BOOL shiftKey + EM_BOOL altKey + EM_BOOL metaKey + + Specifies which modifiers were active during the touch event. + + .. c:member:: EmscriptenTouchPoint touches[32] + + An array of currently active touches, one for each finger. + + + Callback functions ------------------ .. c:type:: em_touch_callback_func - Function pointer for the :c:func:`touch event callback functions `, defined as: + Function pointer for the :c:func:`touch event callback functions `, defined as: + + .. code-block:: cpp + + typedef EM_BOOL (*em_touch_callback_func)(int eventType, const EmscriptenTouchEvent *touchEvent, void *userData); + + :param int eventType: The type of touch event (:c:data:`EMSCRIPTEN_EVENT_TOUCHSTART`). + :param touchEvent: Information about the touch event that occurred. + :type touchEvent: const EmscriptenTouchEvent* + :param void* userData: The ``userData`` originally passed to the registration function. + :returns: |callback-handler-return-value-doc| + :rtype: |EM_BOOL| - .. code-block:: cpp - typedef EM_BOOL (*em_touch_callback_func)(int eventType, const EmscriptenTouchEvent *touchEvent, void *userData); - - :param int eventType: The type of touch event (:c:data:`EMSCRIPTEN_EVENT_TOUCHSTART`). - :param touchEvent: Information about the touch event that occurred. - :type touchEvent: const EmscriptenTouchEvent* - :param void* userData: The ``userData`` originally passed to the registration function. - :returns: |callback-handler-return-value-doc| - :rtype: |EM_BOOL| - - Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_touchstart_callback(const char *target, void *userData, EM_BOOL useCapture, em_touch_callback_func callback) - EMSCRIPTEN_RESULT emscripten_set_touchend_callback(const char *target, void *userData, EM_BOOL useCapture, em_touch_callback_func callback) - EMSCRIPTEN_RESULT emscripten_set_touchmove_callback(const char *target, void *userData, EM_BOOL useCapture, em_touch_callback_func callback) - EMSCRIPTEN_RESULT emscripten_set_touchcancel_callback(const char *target, void *userData, EM_BOOL useCapture, em_touch_callback_func callback) + EMSCRIPTEN_RESULT emscripten_set_touchend_callback(const char *target, void *userData, EM_BOOL useCapture, em_touch_callback_func callback) + EMSCRIPTEN_RESULT emscripten_set_touchmove_callback(const char *target, void *userData, EM_BOOL useCapture, em_touch_callback_func callback) + EMSCRIPTEN_RESULT emscripten_set_touchcancel_callback(const char *target, void *userData, EM_BOOL useCapture, em_touch_callback_func callback) - Registers a callback function for receiving `touch events `_ : `touchstart `_, `touchend `_, `touchmove `_ and `touchcancel `_. + Registers a callback function for receiving `touch events `__ : `touchstart `_, `touchend `_, `touchmove `_ and `touchcancel `_. - :param target: |target-parameter-doc| - :type target: const char* - :param void* userData: |userData-parameter-doc| - :param EM_BOOL useCapture: |useCapture-parameter-doc| - :param em_touch_callback_func callback: |callback-function-parameter-doc| - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :param target: |target-parameter-doc| + :type target: const char* + :param void* userData: |userData-parameter-doc| + :param EM_BOOL useCapture: |useCapture-parameter-doc| + :param em_touch_callback_func callback: |callback-function-parameter-doc| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| @@ -1596,9 +1591,9 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_GAMEPADCONNECTED - EMSCRIPTEN_EVENT_GAMEPADDISCONNECTED - - Emscripten `gamepad `_ events. + EMSCRIPTEN_EVENT_GAMEPADDISCONNECTED + + Emscripten gamepad_ events. Struct @@ -1606,116 +1601,125 @@ Struct .. c:type:: EmscriptenGamepadEvent - Represents the current snapshot state of a `gamepad `_. - - - .. c:member:: double timestamp - - Absolute wallclock time when the data was recorded (milliseconds). - - .. c:member:: int numAxes - - The number of valid axis entries in the ``axis`` array. - - .. c:member:: int numButtons - - The number of valid button entries in the analogButton and digitalButton arrays. - - .. c:member:: double axis[64] - - The analog state of the gamepad axes, in the range [-1, 1]. - - - .. c:member:: double analogButton[64] - - The analog state of the gamepad buttons, in the range [0, 1]. - - - .. c:member:: EM_BOOL digitalButton[64] - - The digital state of the gamepad buttons, either 0 or 1. - - .. c:member:: EM_BOOL connected - - Specifies whether this gamepad is connected to the browser page. - - .. c:member:: long index - - An ordinal associated with this gamepad, zero-based. - - .. c:member:: EM_UTF8 id - - An ID for the brand or style of the connected gamepad device. Typically, this will include the USB vendor and a product ID. - - Maximum size 64 ``char`` (i.e. ``EM_UTF8 id[128]``). - - .. c:member:: EM_UTF8 mapping - - A string that identifies the layout or control mapping of this device. - - Maximum size 128 ``char`` (i.e. ``EM_UTF8 mapping[128]``). - - - + Represents the current snapshot state of a gamepad_. + + + .. c:member:: double timestamp + + Absolute wallclock time when the data was recorded (milliseconds). + + .. c:member:: int numAxes + + The number of valid axis entries in the ``axis`` array. + + .. c:member:: int numButtons + + The number of valid button entries in the analogButton and digitalButton arrays. + + .. c:member:: double axis[64] + + The analog state of the gamepad axes, in the range [-1, 1]. + + + .. c:member:: double analogButton[64] + + The analog state of the gamepad buttons, in the range [0, 1]. + + + .. c:member:: EM_BOOL digitalButton[64] + + The digital state of the gamepad buttons, either 0 or 1. + + .. c:member:: EM_BOOL connected + + Specifies whether this gamepad is connected to the browser page. + + .. c:member:: long index + + An ordinal associated with this gamepad, zero-based. + + .. c:member:: EM_UTF8 id + + An ID for the brand or style of the connected gamepad device. Typically, this will include the USB vendor and a product ID. + + Maximum size 64 ``char`` (i.e. ``EM_UTF8 id[128]``). + + .. c:member:: EM_UTF8 mapping + + A string that identifies the layout or control mapping of this device. + + Maximum size 128 ``char`` (i.e. ``EM_UTF8 mapping[128]``). + + + Callback functions ------------------ .. c:type:: em_gamepad_callback_func - Function pointer for the :c:func:`gamepad event callback functions `, defined as: - - .. code-block:: cpp - - typedef EM_BOOL (*em_gamepad_callback_func)(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData) - - :param int eventType: The type of gamepad event (:c:data:`EMSCRIPTEN_EVENT_GAMEPADCONNECTED`). - :param gamepadEvent: Information about the gamepad event that occurred. - :type gamepadEvent: const EmscriptenGamepadEvent* - :param void* userData: The ``userData`` originally passed to the registration function. - :returns: |callback-handler-return-value-doc| - :rtype: |EM_BOOL| - - - + Function pointer for the :c:func:`gamepad event callback functions `, defined as: + + .. code-block:: cpp + + typedef EM_BOOL (*em_gamepad_callback_func)(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData) + + :param int eventType: The type of gamepad event (:c:data:`EMSCRIPTEN_EVENT_GAMEPADCONNECTED`). + :param gamepadEvent: Information about the gamepad event that occurred. + :type gamepadEvent: const EmscriptenGamepadEvent* + :param void* userData: The ``userData`` originally passed to the registration function. + :returns: |callback-handler-return-value-doc| + :rtype: |EM_BOOL| + + + Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_gamepadconnected_callback(void *userData, EM_BOOL useCapture, em_gamepad_callback_func callback) - EMSCRIPTEN_RESULT emscripten_set_gamepaddisconnected_callback(void *userData, EM_BOOL useCapture, em_gamepad_callback_func callback) - - Registers a callback function for receiving the `gamepad `_ events: `gamepadconnected `_ and `gamepaddisconnected `_. + EMSCRIPTEN_RESULT emscripten_set_gamepaddisconnected_callback(void *userData, EM_BOOL useCapture, em_gamepad_callback_func callback) + + Registers a callback function for receiving the gamepad_ events: `gamepadconnected `_ and `gamepaddisconnected `_. - :param void* userData: |userData-parameter-doc| - :param EM_BOOL useCapture: |useCapture-parameter-doc| - :param em_gamepad_callback_func callback: |callback-function-parameter-doc| - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :param void* userData: |userData-parameter-doc| + :param EM_BOOL useCapture: |useCapture-parameter-doc| + :param em_gamepad_callback_func callback: |callback-function-parameter-doc| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: int emscripten_get_num_gamepads(void) - Returns the number of gamepads connected to the system or :c:type:`EMSCRIPTEN_RESULT_NOT_SUPPORTED` if the current browser does not support gamepads. - - .. note:: A gamepad does not show up as connected until a button on it is pressed. + Returns the number of gamepads connected to the system or + :c:type:`EMSCRIPTEN_RESULT_NOT_SUPPORTED` if the current browser does not + support gamepads. - .. note:: Gamepad API uses an array of gamepad state objects to return the state of each device. The devices are identified via the index they are present in in - this array. Because of that, if one first connects gamepad A, then gamepad B, and then disconnects gamepad A, the gamepad B shall not take the place of gamepad A, - so in this scenario, this function will still keep returning two for the count of connected gamepads, even though gamepad A is no longer present. To find the actual - number of connected gamepads, listen for the gamepadconnected and gamepaddisconnected events. - Consider the return value of this function as the largest value (-1) that can be passed to the function emscripten_get_gamepad_status(). + .. note:: A gamepad does not show up as connected until a button on it is pressed. - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: int + .. note:: + + Gamepad API uses an array of gamepad state objects to return the state of + each device. The devices are identified via the index they are present in in + this array. Because of that, if one first connects gamepad A, then gamepad + B, and then disconnects gamepad A, the gamepad B shall not take the place of + gamepad A, so in this scenario, this function will still keep returning two + for the count of connected gamepads, even though gamepad A is no longer + present. To find the actual number of connected gamepads, listen for the + gamepadconnected and gamepaddisconnected events. Consider the return value + of this function as the largest value (-1) that can be passed to the + function emscripten_get_gamepad_status(). + + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: int .. c:function:: EMSCRIPTEN_RESULT emscripten_get_gamepad_status(int index, EmscriptenGamepadEvent *gamepadState) - Returns a snapshot of the current gamepad state. + Returns a snapshot of the current gamepad state. - :param int index: The index of the gamepad to check (in the `array of connected gamepads `_). - :param EmscriptenGamepadEvent* gamepadState: The most recently received gamepad state. - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :param int index: The index of the gamepad to check (in the `array of connected gamepads `_). + :param EmscriptenGamepadEvent* gamepadState: The most recently received gamepad state. + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| @@ -1726,78 +1730,78 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_BATTERYCHARGINGCHANGE - EMSCRIPTEN_EVENT_BATTERYLEVELCHANGE - + EMSCRIPTEN_EVENT_BATTERYLEVELCHANGE + Emscripten `batterymanager `_ events. - + Struct ------ .. c:type:: EmscriptenBatteryEvent - The event structure passed in the `batterymanager `_ events: ``chargingchange`` and ``levelchange``. + The event structure passed in the `batterymanager `_ events: ``chargingchange`` and ``levelchange``. + + + .. c:member:: double chargingTime - - .. c:member:: double chargingTime - - Time remaining until the battery is fully charged (seconds). + Time remaining until the battery is fully charged (seconds). - .. c:member:: double dischargingTime - - Time remaining until the battery is empty and the system will be suspended (seconds). - - .. c:member:: double level - - Current battery level, on a scale of 0 to 1.0. + .. c:member:: double dischargingTime + + Time remaining until the battery is empty and the system will be suspended (seconds). + + .. c:member:: double level + + Current battery level, on a scale of 0 to 1.0. + + .. c:member:: EM_BOOL charging; + + ``true`` if the battery is charging, ``false`` otherwise. - .. c:member:: EM_BOOL charging; - - ``true`` if the battery is charging, ``false`` otherwise. - Callback functions ------------------ .. c:type:: em_battery_callback_func - Function pointer for the :c:func:`batterymanager event callback functions `, defined as: + Function pointer for the :c:func:`batterymanager event callback functions `, defined as: + + .. code-block:: cpp + + typedef EM_BOOL (*em_battery_callback_func)(int eventType, const EmscriptenBatteryEvent *batteryEvent, void *userData); + + :param int eventType: The type of ``batterymanager`` event (:c:data:`EMSCRIPTEN_EVENT_BATTERYCHARGINGCHANGE`). + :param batteryEvent: Information about the ``batterymanager`` event that occurred. + :type batteryEvent: const EmscriptenBatteryEvent* + :param void* userData: The ``userData`` originally passed to the registration function. + :returns: |callback-handler-return-value-doc| + :rtype: |EM_BOOL| - .. code-block:: cpp - typedef EM_BOOL (*em_battery_callback_func)(int eventType, const EmscriptenBatteryEvent *batteryEvent, void *userData); - - :param int eventType: The type of ``batterymanager`` event (:c:data:`EMSCRIPTEN_EVENT_BATTERYCHARGINGCHANGE`). - :param batteryEvent: Information about the ``batterymanager`` event that occurred. - :type batteryEvent: const EmscriptenBatteryEvent* - :param void* userData: The ``userData`` originally passed to the registration function. - :returns: |callback-handler-return-value-doc| - :rtype: |EM_BOOL| - - Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_batterychargingchange_callback(void *userData, em_battery_callback_func callback) - EMSCRIPTEN_RESULT emscripten_set_batterylevelchange_callback(void *userData, em_battery_callback_func callback) - - Registers a callback function for receiving the `batterymanager `_ events: ``chargingchange`` and ``levelchange``. + EMSCRIPTEN_RESULT emscripten_set_batterylevelchange_callback(void *userData, em_battery_callback_func callback) + + Registers a callback function for receiving the `batterymanager `_ events: ``chargingchange`` and ``levelchange``. - :param void* userData: |userData-parameter-doc| - :param em_battery_callback_func callback: |callback-function-parameter-doc| - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :param void* userData: |userData-parameter-doc| + :param em_battery_callback_func callback: |callback-function-parameter-doc| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: EMSCRIPTEN_RESULT emscripten_get_battery_status(EmscriptenBatteryEvent *batteryState) - Returns the current battery status. + Returns the current battery status. - :param batteryState: The most recently received battery state. - :type batteryState: EmscriptenBatteryEvent* - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :param batteryState: The most recently received battery state. + :type batteryState: EmscriptenBatteryEvent* + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| @@ -1805,26 +1809,26 @@ Vibration ========= Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_vibrate(int msecs) - Produces a `vibration `_ for the specified time, in milliseconds. + Produces a `vibration `_ for the specified time, in milliseconds. - :param int msecs: The amount of time for which the vibration is required (milliseconds). - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :param int msecs: The amount of time for which the vibration is required (milliseconds). + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: EMSCRIPTEN_RESULT emscripten_vibrate_pattern(int *msecsArray, int numEntries) - Produces a complex vibration feedback pattern. + Produces a complex vibration feedback pattern. - :param int* msecsArray: An array of timing entries [on, off, on, off, on, off, ...] where every second one specifies a duration of vibration, and every other one specifies a duration of silence. - :param int numEntries: The number of integers in the array ``msecsArray``. - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :param int* msecsArray: An array of timing entries [on, off, on, off, on, off, ...] where every second one specifies a duration of vibration, and every other one specifies a duration of silence. + :param int numEntries: The number of integers in the array ``msecsArray``. + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| Page unload @@ -1834,45 +1838,45 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_BEFOREUNLOAD - + Emscripten `beforeunload `_ event. - + Callback functions ------------------ .. c:type:: em_beforeunload_callback - Function pointer for the :c:func:`beforeunload event callback functions `, defined as: - - .. code-block:: cpp - - typedef const char *(*em_beforeunload_callback)(int eventType, const void *reserved, void *userData); - - :param int eventType: The type of ``beforeunload`` event (:c:data:`EMSCRIPTEN_EVENT_BEFOREUNLOAD`). - :param reserved: Reserved for future use; pass in 0. - :type reserved: const void* - :param void* userData: The ``userData`` originally passed to the registration function. - :returns: Return a string to be displayed to the user. - :rtype: char* - - - + Function pointer for the :c:func:`beforeunload event callback functions `, defined as: + + .. code-block:: cpp + + typedef const char *(*em_beforeunload_callback)(int eventType, const void *reserved, void *userData); + + :param int eventType: The type of ``beforeunload`` event (:c:data:`EMSCRIPTEN_EVENT_BEFOREUNLOAD`). + :param reserved: Reserved for future use; pass in 0. + :type reserved: const void* + :param void* userData: The ``userData`` originally passed to the registration function. + :returns: Return a string to be displayed to the user. + :rtype: char* + + + Functions --------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_beforeunload_callback(void *userData, em_beforeunload_callback callback) - - Registers a callback function for receiving the page `beforeunload `_ event. - - Hook into this event to perform actions immediately prior to page close (for example, to display a notification to ask if the user really wants to leave the page). - :param void* userData: |userData-parameter-doc| - :param em_beforeunload_callback callback: |callback-function-parameter-doc| - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| - + Registers a callback function for receiving the page `beforeunload `_ event. + + Hook into this event to perform actions immediately prior to page close (for example, to display a notification to ask if the user really wants to leave the page). + + :param void* userData: |userData-parameter-doc| + :param em_beforeunload_callback callback: |callback-function-parameter-doc| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| + WebGL context @@ -1882,221 +1886,221 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_WEBGLCONTEXTLOST - EMSCRIPTEN_EVENT_WEBGLCONTEXTRESTORED - - Emscripten `WebGL context `_ events. + EMSCRIPTEN_EVENT_WEBGLCONTEXTRESTORED + + Emscripten `WebGL context`_ events. .. c:type:: EMSCRIPTEN_WEBGL_CONTEXT_HANDLE - Represents a handle to an Emscripten WebGL context object. The value 0 denotes an invalid/no context (this is a typedef to an ``int``). - - + Represents a handle to an Emscripten WebGL context object. The value 0 denotes an invalid/no context (this is a typedef to an ``int``). + + Struct ------ .. c:type:: EmscriptenWebGLContextAttributes - Specifies `WebGL context creation parameters `_. - - .. c:member:: EM_BOOL alpha - - If ``true``, request an alpha channel for the context. If you create an alpha channel, you can blend the canvas rendering with the underlying web page contents. Default value: ``true``. - - .. c:member:: EM_BOOL depth - - If ``true``, request a depth buffer of at least 16 bits. If ``false``, no depth buffer will be initialized. Default value: ``true``. + Specifies `WebGL context creation parameters `_. + + .. c:member:: EM_BOOL alpha + + If ``true``, request an alpha channel for the context. If you create an alpha channel, you can blend the canvas rendering with the underlying web page contents. Default value: ``true``. + + .. c:member:: EM_BOOL depth + + If ``true``, request a depth buffer of at least 16 bits. If ``false``, no depth buffer will be initialized. Default value: ``true``. + + .. c:member:: EM_BOOL stencil + + If ``true``, request a stencil buffer of at least 8 bits. If ``false``, no stencil buffer will be initialized. Default value: ``false``. + + .. c:member:: EM_BOOL antialias - .. c:member:: EM_BOOL stencil + If ``true``, antialiasing will be initialized with a browser-specified algorithm and quality level. If ``false``, antialiasing is disabled. Default value: ``true``. - If ``true``, request a stencil buffer of at least 8 bits. If ``false``, no stencil buffer will be initialized. Default value: ``false``. - .. c:member:: EM_BOOL antialias + .. c:member:: EM_BOOL premultipliedAlpha - If ``true``, antialiasing will be initialized with a browser-specified algorithm and quality level. If ``false``, antialiasing is disabled. Default value: ``true``. + If ``true``, the alpha channel of the rendering context will be treated as representing premultiplied alpha values. If ``false``, the alpha channel represents non-premultiplied alpha. Default value: ``true``. - .. c:member:: EM_BOOL premultipliedAlpha + .. c:member:: EM_BOOL preserveDrawingBuffer - If ``true``, the alpha channel of the rendering context will be treated as representing premultiplied alpha values. If ``false``, the alpha channel represents non-premultiplied alpha. Default value: ``true``. + If ``true``, the contents of the drawing buffer are preserved between consecutive ``requestAnimationFrame()`` calls. If ``false``, color, depth and stencil are cleared at the beginning of each ``requestAnimationFrame()``. Generally setting this to ``false`` gives better performance. Default value: ``false``. - - .. c:member:: EM_BOOL preserveDrawingBuffer - If ``true``, the contents of the drawing buffer are preserved between consecutive ``requestAnimationFrame()`` calls. If ``false``, color, depth and stencil are cleared at the beginning of each ``requestAnimationFrame()``. Generally setting this to ``false`` gives better performance. Default value: ``false``. - - - .. c:member:: EM_BOOL preferLowPowerToHighPerformance + .. c:member:: EM_BOOL preferLowPowerToHighPerformance - If ``true``, hints the browser to initialize a low-power GPU rendering context. If ``false``, prefers to initialize a high-performance rendering context. Default value: ``false``. + If ``true``, hints the browser to initialize a low-power GPU rendering context. If ``false``, prefers to initialize a high-performance rendering context. Default value: ``false``. - .. c:member:: EM_BOOL failIfMajorPerformanceCaveat - - If ``true``, requests context creation to abort if the browser is only able to create a context that does not give good hardware-accelerated performance. Default value: ``false``. + .. c:member:: EM_BOOL failIfMajorPerformanceCaveat + If ``true``, requests context creation to abort if the browser is only able to create a context that does not give good hardware-accelerated performance. Default value: ``false``. - .. c:member:: int majorVersion - int minorVersion - - Emscripten-specific extensions which specify the WebGL context version to initialize. - For example, pass in ``majorVersion=1``, ``minorVersion=0`` to request a WebGL 1.0 context, and ``majorVersion=2``, ``minorVersion=0`` to request a WebGL 2.0 context. + .. c:member:: int majorVersion + int minorVersion - Default value: ``majorVersion=1``, ``minorVersion=0`` + Emscripten-specific extensions which specify the WebGL context version to initialize. - - .. c:member:: EM_BOOL enableExtensionsByDefault + For example, pass in ``majorVersion=1``, ``minorVersion=0`` to request a WebGL 1.0 context, and ``majorVersion=2``, ``minorVersion=0`` to request a WebGL 2.0 context. - If ``true``, all GLES2-compatible non-performance-impacting WebGL extensions will automatically be enabled for you after the context has been created. If ``false``, no extensions are enabled by default, and you need to manually call :c:func:`emscripten_webgl_enable_extension` to enable each extension that you want to use. Default value: ``true``. + Default value: ``majorVersion=1``, ``minorVersion=0`` - .. c:member:: EM_BOOL explicitSwapControl + .. c:member:: EM_BOOL enableExtensionsByDefault - By default, when ``explicitSwapControl`` is in its default state ``false``, rendered WebGL content is implicitly presented (displayed to the user) on the canvas when the event handler that renders with WebGL returns back to the browser event loop. If ``explicitSwapControl`` is set to ``true``, rendered content will not be displayed on screen automatically when event handler function finishes, but the control of swapping is given to the user to manage, via the ``emscripten_webgl_commit_frame()`` function. + If ``true``, all GLES2-compatible non-performance-impacting WebGL extensions will automatically be enabled for you after the context has been created. If ``false``, no extensions are enabled by default, and you need to manually call :c:func:`emscripten_webgl_enable_extension` to enable each extension that you want to use. Default value: ``true``. - In order to be able to set ``explicitSwapControl==true``, support for it must explicitly be enabled either 1) via adding the ``-s OFFSCREEN_FRAMEBUFFER=1`` Emscripten linker flag, and enabling ``renderViaOffscreenBackBuffer==1``, or 2) via adding the the linker flag ``-s OFFSCREENCANVAS_SUPPORT=1``, and running in a browser that supports OffscreenCanvas. + .. c:member:: EM_BOOL explicitSwapControl - .. c:member:: EM_BOOL renderViaOffscreenBackBuffer + By default, when ``explicitSwapControl`` is in its default state ``false``, rendered WebGL content is implicitly presented (displayed to the user) on the canvas when the event handler that renders with WebGL returns back to the browser event loop. If ``explicitSwapControl`` is set to ``true``, rendered content will not be displayed on screen automatically when event handler function finishes, but the control of swapping is given to the user to manage, via the ``emscripten_webgl_commit_frame()`` function. - If ``true``, an extra intermediate backbuffer (offscreen render target) is allocated to the created WebGL context, and rendering occurs to this backbuffer instead of directly onto the WebGL "default backbuffer". This is required to be enabled if 1) ``explicitSwapControl==true`` and the browser does not support OffscreenCanvas, 2) when performing WebGL rendering in a worker thread and the browser does not support OffscreenCanvas, and 3) when performing WebGL context accesses from multiple threads simultaneously (independent of whether OffscreenCanvas is supported or not). + In order to be able to set ``explicitSwapControl==true``, support for it must explicitly be enabled either 1) via adding the ``-s OFFSCREEN_FRAMEBUFFER=1`` Emscripten linker flag, and enabling ``renderViaOffscreenBackBuffer==1``, or 2) via adding the the linker flag ``-s OFFSCREENCANVAS_SUPPORT=1``, and running in a browser that supports OffscreenCanvas. + + + .. c:member:: EM_BOOL renderViaOffscreenBackBuffer + + If ``true``, an extra intermediate backbuffer (offscreen render target) is allocated to the created WebGL context, and rendering occurs to this backbuffer instead of directly onto the WebGL "default backbuffer". This is required to be enabled if 1) ``explicitSwapControl==true`` and the browser does not support OffscreenCanvas, 2) when performing WebGL rendering in a worker thread and the browser does not support OffscreenCanvas, and 3) when performing WebGL context accesses from multiple threads simultaneously (independent of whether OffscreenCanvas is supported or not). + + Because supporting offscreen framebuffer adds some amount of extra code to the compiled output, support for it must explicitly be enabled via the ``-s OFFSCREEN_FRAMEBUFFER=1`` Emscripten linker flag. When building simultaneously with both ``-s OFFSCREEN_FRAMEBUFFER=1`` and ``-s OFFSCREENCANVAS_SUPPORT=1`` linker flags enabled, offscreen backbuffer can be used as a polyfill-like compatibility fallback to enable rendering WebGL from a pthread when the browser does not support the OffscreenCanvas API. - Because supporting offscreen framebuffer adds some amount of extra code to the compiled output, support for it must explicitly be enabled via the ``-s OFFSCREEN_FRAMEBUFFER=1`` Emscripten linker flag. When building simultaneously with both ``-s OFFSCREEN_FRAMEBUFFER=1`` and ``-s OFFSCREENCANVAS_SUPPORT=1`` linker flags enabled, offscreen backbuffer can be used as a polyfill-like compatibility fallback to enable rendering WebGL from a pthread when the browser does not support the OffscreenCanvas API. - Callback functions ------------------ .. c:type:: em_webgl_context_callback - Function pointer for the :c:func:`WebGL Context event callback functions `, defined as: + Function pointer for the :c:func:`WebGL Context event callback functions `, defined as: + + .. code-block:: cpp + + typedef EM_BOOL (*em_webgl_context_callback)(int eventType, const void *reserved, void *userData); + + :param int eventType: The type of :c:data:`WebGL context event `. + :param reserved: Reserved for future use; pass in 0. + :type reserved: const void* + :param void* userData: The ``userData`` originally passed to the registration function. + :returns: |callback-handler-return-value-doc| + :rtype: |EM_BOOL| - .. code-block:: cpp - typedef EM_BOOL (*em_webgl_context_callback)(int eventType, const void *reserved, void *userData); - - :param int eventType: The type of :c:data:`WebGL context event `. - :param reserved: Reserved for future use; pass in 0. - :type reserved: const void* - :param void* userData: The ``userData`` originally passed to the registration function. - :returns: |callback-handler-return-value-doc| - :rtype: |EM_BOOL| - - Functions --------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_webglcontextlost_callback(const char *target, void *userData, EM_BOOL useCapture, em_webgl_context_callback callback) - EMSCRIPTEN_RESULT emscripten_set_webglcontextrestored_callback(const char *target, void *userData, EM_BOOL useCapture, em_webgl_context_callback callback) + EMSCRIPTEN_RESULT emscripten_set_webglcontextrestored_callback(const char *target, void *userData, EM_BOOL useCapture, em_webgl_context_callback callback) - Registers a callback function for the canvas `WebGL context `_ events: ``webglcontextlost`` and ``webglcontextrestored``. + Registers a callback function for the canvas `WebGL context`_ events: ``webglcontextlost`` and ``webglcontextrestored``. - :param target: |target-parameter-doc| - :type target: const char* - :param void* userData: |userData-parameter-doc| - :param EM_BOOL useCapture: |useCapture-parameter-doc| - :param em_webgl_context_callback callback: |callback-function-parameter-doc| - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :param target: |target-parameter-doc| + :type target: const char* + :param void* userData: |userData-parameter-doc| + :param EM_BOOL useCapture: |useCapture-parameter-doc| + :param em_webgl_context_callback callback: |callback-function-parameter-doc| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: EM_BOOL emscripten_is_webgl_context_lost(const char *target) - Queries the given canvas element for whether its WebGL context is in a lost state. + Queries the given canvas element for whether its WebGL context is in a lost state. + + :param target: Reserved for future use, pass in 0. + :type target: const char* + :returns: ``true`` if the WebGL context is in a lost state. + :rtype: |EM_BOOL| - :param target: Reserved for future use, pass in 0. - :type target: const char* - :returns: ``true`` if the WebGL context is in a lost state. - :rtype: |EM_BOOL| - .. c:function:: void emscripten_webgl_init_context_attributes(EmscriptenWebGLContextAttributes *attributes) - Populates all fields of the given :c:type:`EmscriptenWebGLContextAttributes` structure to their default values for use with WebGL 1.0. - - Call this function as a forward-compatible way to ensure that if there are new fields added to the ``EmscriptenWebGLContextAttributes`` structure in the future, that they also will get default-initialized without having to change any code. - - :param attributes: The structure to be populated. - :type attributes: EmscriptenWebGLContextAttributes* + Populates all fields of the given :c:type:`EmscriptenWebGLContextAttributes` structure to their default values for use with WebGL 1.0. + + Call this function as a forward-compatible way to ensure that if there are new fields added to the ``EmscriptenWebGLContextAttributes`` structure in the future, that they also will get default-initialized without having to change any code. + + :param attributes: The structure to be populated. + :type attributes: EmscriptenWebGLContextAttributes* .. c:function:: EMSCRIPTEN_WEBGL_CONTEXT_HANDLE emscripten_webgl_create_context(const char *target, const EmscriptenWebGLContextAttributes *attributes) - Creates and returns a new `WebGL context `_. - - .. note:: - - - A successful call to this function will not immediately make that rendering context active. Call :c:func:`emscripten_webgl_make_context_current` after creating a context to activate it. - - This function will try to initialize the context version that was *exactly* requested. It will not e.g. initialize a newer backwards-compatible version or similar. - - :param target: The DOM canvas element in which to initialize the WebGL context. If 0 is passed, the element specified by ``Module.canvas`` will be used. - :type target: const char* - :param attributes: The attributes of the requested context version. - :type attributes: const EmscriptenWebGLContextAttributes* - :returns: On success, a strictly positive value that represents a handle to the created context. On failure, a negative number that can be cast to an |EMSCRIPTEN_RESULT| field to get the reason why the context creation failed. - :rtype: |EMSCRIPTEN_WEBGL_CONTEXT_HANDLE| - - + Creates and returns a new `WebGL context `_. + + .. note:: + + - A successful call to this function will not immediately make that rendering context active. Call :c:func:`emscripten_webgl_make_context_current` after creating a context to activate it. + - This function will try to initialize the context version that was *exactly* requested. It will not e.g. initialize a newer backwards-compatible version or similar. + + :param target: The DOM canvas element in which to initialize the WebGL context. If 0 is passed, the element specified by ``Module.canvas`` will be used. + :type target: const char* + :param attributes: The attributes of the requested context version. + :type attributes: const EmscriptenWebGLContextAttributes* + :returns: On success, a strictly positive value that represents a handle to the created context. On failure, a negative number that can be cast to an |EMSCRIPTEN_RESULT| field to get the reason why the context creation failed. + :rtype: |EMSCRIPTEN_WEBGL_CONTEXT_HANDLE| + + .. c:function:: EMSCRIPTEN_RESULT emscripten_webgl_make_context_current(EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context) - Activates the given WebGL context for rendering. After calling this function, all OpenGL functions (``glBindBuffer()``, ``glDrawArrays()``, etc.) can be applied to the given GL context. + Activates the given WebGL context for rendering. After calling this function, all OpenGL functions (``glBindBuffer()``, ``glDrawArrays()``, etc.) can be applied to the given GL context. + + :param EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context: The WebGL context to activate. + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| - :param EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context: The WebGL context to activate. - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| - .. c:function:: EMSCRIPTEN_WEBGL_CONTEXT_HANDLE emscripten_webgl_get_current_context() - Returns the currently active WebGL rendering context, or 0 if no context is active. Calling any WebGL functions when there is no active rendering context is undefined and may throw a JavaScript exception. + Returns the currently active WebGL rendering context, or 0 if no context is active. Calling any WebGL functions when there is no active rendering context is undefined and may throw a JavaScript exception. + + :returns: The currently active WebGL rendering context, or 0 if no context is active. + :rtype: |EMSCRIPTEN_WEBGL_CONTEXT_HANDLE| + - :returns: The currently active WebGL rendering context, or 0 if no context is active. - :rtype: |EMSCRIPTEN_WEBGL_CONTEXT_HANDLE| - - .. c:function:: EMSCRIPTEN_RESULT emscripten_webgl_commit_frame() - Presents ("swaps") the content rendered on the currently active WebGL context to be visible on the canvas. This function is available on WebGL contexts that were created with the ``explicitSwapControl==true`` context creation attribute. If ``explicitSwapControl==false``, then the rendered content is displayed on the screen "implicitly" when yielding back to the browser from the calling event handler. + Presents ("swaps") the content rendered on the currently active WebGL context to be visible on the canvas. This function is available on WebGL contexts that were created with the ``explicitSwapControl==true`` context creation attribute. If ``explicitSwapControl==false``, then the rendered content is displayed on the screen "implicitly" when yielding back to the browser from the calling event handler. - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values, denoting a reason for failure. - :rtype: |EMSCRIPTEN_RESULT| + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values, denoting a reason for failure. + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: EMSCRIPTEN_RESULT emscripten_webgl_get_drawing_buffer_size(EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context, int *width, int *height) - Gets the ``drawingBufferWidth`` and ``drawingBufferHeight`` of the specified WebGL context. + Gets the ``drawingBufferWidth`` and ``drawingBufferHeight`` of the specified WebGL context. + + :param EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context: The WebGL context to get width/height of. + :param int \*width: The context's ``drawingBufferWidth``. + :param int \*height: The context's ``drawingBufferHeight``. + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| - :param EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context: The WebGL context to get width/height of. - :param int *width: The context's ``drawingBufferWidth``. - :param int *height: The context's ``drawingBufferHeight``. - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| - .. c:function:: EMSCRIPTEN_RESULT emscripten_webgl_destroy_context(EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context) - Deletes the given WebGL context. If that context was active, then the no context is set to active. + Deletes the given WebGL context. If that context was active, then the no context is set to active. - :param EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context: The WebGL context to delete. - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :param EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context: The WebGL context to delete. + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: EM_BOOL emscripten_webgl_enable_extension(EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context, const char *extension) - Enables the given extension on the given context. + Enables the given extension on the given context. - :param EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context: The WebGL context on which the extension is to be enabled. - :param extension: A string identifying the `WebGL extension `_. For example "OES_texture_float". - :type extension: const char* - :returns: EM_TRUE if the given extension is supported by the context, and EM_FALSE if the extension was not available. - :rtype: |EM_BOOL| - - .. comment : **HamishW** Are EM_TRUE, EM_FALSE defined? + :param EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context: The WebGL context on which the extension is to be enabled. + :param extension: A string identifying the `WebGL extension `_. For example "OES_texture_float". + :type extension: const char* + :returns: EM_TRUE if the given extension is supported by the context, and EM_FALSE if the extension was not available. + :rtype: |EM_BOOL| + + .. comment : **HamishW** Are EM_TRUE, EM_FALSE defined? CSS @@ -2108,33 +2112,33 @@ Functions .. c:function:: EMSCRIPTEN_RESULT emscripten_set_element_css_size(const char * target, double width, double height) - Resizes the CSS width and height of the element specified by ``target`` on the Emscripten web page. + Resizes the CSS width and height of the element specified by ``target`` on the Emscripten web page. - :param target: Element to resize. If 0 is passed, the element specified by ``Module.canvas`` will be used. - :type target: const char* - :param double width: New width of the element. - :param double height: New height of the element. - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :param target: Element to resize. If 0 is passed, the element specified by ``Module.canvas`` will be used. + :type target: const char* + :param double width: New width of the element. + :param double height: New height of the element. + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: EMSCRIPTEN_RESULT emscripten_get_element_css_size(const char * target, double * width, double * height) - Gets the current CSS width and height of the element specified by ``target``. + Gets the current CSS width and height of the element specified by ``target``. + + :param target: Element to get size of. If 0 is passed, the element specified by ``Module.canvas`` will be used. + :type target: const char* + :param double* width: Width of the element. + :param double* height: Height of the element. + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. + :rtype: |EMSCRIPTEN_RESULT| + - :param target: Element to get size of. If 0 is passed, the element specified by ``Module.canvas`` will be used. - :type target: const char* - :param double* width: Width of the element. - :param double* height: Height of the element. - :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| - - .. COMMENT (not rendered): Section below is automated copy and replace text. .. COMMENT (not rendered): The replace function return values with links (not created automatically) - + .. |EMSCRIPTEN_RESULT| replace:: :c:type:`EMSCRIPTEN_RESULT` .. |EM_BOOL| replace:: :c:type:`EM_BOOL` .. |EMSCRIPTEN_WEBGL_CONTEXT_HANDLE| replace:: :c:type:`EMSCRIPTEN_WEBGL_CONTEXT_HANDLE` @@ -2147,7 +2151,7 @@ Functions .. |userData-parameter-doc| replace:: :ref:`User-defined data ` to be passed to the callback (opaque to the API). .. |useCapture-parameter-doc| replace:: Set ``true`` to :ref:`use capture `. .. |callback-handler-return-value-doc| replace:: ``true`` (non zero) to indicate that the event was consumed by the :ref:`callback handler `. -.. |callback-function-parameter-doc| replace:: A callback function. The function is called with the type of event, information about the event, and user data passed from this registration function. The callback should return ``true`` if the event is consumed. - - +.. |callback-function-parameter-doc| replace:: A callback function. The function is called with the type of event, information about the event, and user data passed from this registration function. The callback should return ``true`` if the event is consumed. +.. _gamepad: http://www.w3.org/TR/gamepad/#gamepad-interface +.. _webgl_context: http://www.khronos.org/registry/webgl/specs/latest/1.0/#5.15.2 diff --git a/site/source/docs/api_reference/index.rst b/site/source/docs/api_reference/index.rst index e400d734c2e6d..3662020dd7955 100644 --- a/site/source/docs/api_reference/index.rst +++ b/site/source/docs/api_reference/index.rst @@ -18,7 +18,7 @@ This section lists Emscripten's public API, organised by header file. At a very - :ref:`Filesystem-API` (**library_fs.js**): APIs for managing file systems and synchronous file operations. -- :ref:`Fetch API`: +- :ref:`Fetch-API`: API for managing accesses to network XHR and IndexedDB. - :ref:`Module`: diff --git a/site/source/docs/api_reference/module.rst b/site/source/docs/api_reference/module.rst index 7b1a9660844ec..c28995d21befa 100644 --- a/site/source/docs/api_reference/module.rst +++ b/site/source/docs/api_reference/module.rst @@ -11,8 +11,8 @@ Developers can provide an implementation of ``Module`` to control the execution .. note:: ``Module`` is also used to provide access to Emscripten API functions (for example :js:func:`ccall`) in a safe way. Any function or runtime method exported (using ``EXPORTED_FUNCTIONS`` for compiled functions, or ``EXTRA_EXPORTED_RUNTIME_METHODS`` for runtime methods like ``ccall``) will be accessible on the ``Module`` object, without minification changing the name, and the optimizer will make sure to keep the function present (and not remove it as unused). See the :ref:`relevant FAQ entry`. .. contents:: Table of Contents - :local: - :depth: 1 + :local: + :depth: 1 .. _module-creating: @@ -24,20 +24,20 @@ Use emcc's :ref:`pre-js option` to add JavaScript code that defines When generating only JavaScript (as opposed to HTML), no ``Module`` object is created by default, and the behaviour is entirely defined by the developer. For example, creating a ``Module`` object with the following code will cause all notifications from the program to be calls to ``alert()``. - :: + .. code-block:: javascript - var Module = { - 'print': function(text) { alert('stdout: ' + text) }, - 'printErr': function(text) { alert('stderr: ' + text) } - }; + var Module = { + 'print': function(text) { alert('stdout: ' + text) }, + 'printErr': function(text) { alert('stderr: ' + text) } + }; .. important:: If you run the :term:`Closure Compiler` on your code (which is optional, and can be done by ``--closure 1``), you will need quotation marks around the properties of ``Module`` as in the example above. In addition, you need to run closure on the compiled code together with the declaration of ``Module`` — this is done automatically for a ``-pre-js`` file. -When generating HTML, Emscripten creates a ``Module`` object with default methods (see `src/shell.html `_). In this case you should again use ``--pre-js``, but this time you add properties to the *existing* ``Module`` object, for example +When generating HTML, Emscripten creates a ``Module`` object with default methods (see `src/shell.html `_). In this case you should again use ``--pre-js``, but this time you add properties to the *existing* ``Module`` object, for example: - :: + .. code-block:: javascript - Module['print'] = function(text) { alert('stdout: ' + text) }; + Module['print'] = function(text) { alert('stdout: ' + text) }; Note that once the Module object is received by the main JavaScript file, it will look for `Module['print']` and so forth at that time, and use them accordingly. Changing their values later may not be noticed. @@ -49,69 +49,66 @@ The following ``Module`` attributes affect code execution. Set them to customize .. js:attribute:: Module.arguments - The commandline arguments. The value of ``arguments`` contains the values returned if compiled code checks ``argc`` and ``argv``. + The commandline arguments. The value of ``arguments`` contains the values returned if compiled code checks ``argc`` and ``argv``. .. js:attribute:: Module.locateFile - If set, this method will be called when the runtime needs to load a file, such as a ``.wasm`` WebAssembly file, ``.mem`` memory init file, or a file generated by the file packager. The function receives the relative path to the file as configured in build process and a ``prefix`` (path to the main JavaScript file's directory), and should return the actual URL. This lets you host file packages or the ``.mem`` file etc. on a different location than the directory of the JavaScript file (which is the default expectation), for example if you want to host them on a CDN. + If set, this method will be called when the runtime needs to load a file, such as a ``.wasm`` WebAssembly file, ``.mem`` memory init file, or a file generated by the file packager. The function receives the relative path to the file as configured in build process and a ``prefix`` (path to the main JavaScript file's directory), and should return the actual URL. This lets you host file packages or the ``.mem`` file etc. on a different location than the directory of the JavaScript file (which is the default expectation), for example if you want to host them on a CDN. - .. note:: ``prefix`` might be an empty string, if ``locateFile`` is called before we load the main JavaScript. For example, that can happen if a file package or a mememory initializer file are loaded beforehand (perhaps from the HTML, before it loads the main JavaScript). + .. note:: ``prefix`` might be an empty string, if ``locateFile`` is called before we load the main JavaScript. For example, that can happen if a file package or a mememory initializer file are loaded beforehand (perhaps from the HTML, before it loads the main JavaScript). - .. note:: Several ``Module.*PrefixURL`` options have been deprecated in favor of ``locateFile``, which includes ``memoryInitializerPrefixURL``, ``pthreadMainPrefixURL``, ``cdInitializerPrefixURL``, ``filePackagePrefixURL``. To update your code, for example if you used ``Module.memoryInitializerPrefixURL`` equal to ``"https://mycdn.com/memory-init-dir/"``, then you can replace that with something like + .. note:: Several ``Module.*PrefixURL`` options have been deprecated in favor of ``locateFile``, which includes ``memoryInitializerPrefixURL``, ``pthreadMainPrefixURL``, ``cdInitializerPrefixURL``, ``filePackagePrefixURL``. To update your code, for example if you used ``Module.memoryInitializerPrefixURL`` equal to ``"https://mycdn.com/memory-init-dir/"``, then you can replace that with something like: - :: + .. code-block:: javascript - Module['locateFile'] = function(path, prefix) { - // if it's a mem init file, use a custom dir - if (path.endsWith(".mem")) return "https://mycdn.com/memory-init-dir/" + path; - // otherwise, use the default, the prefix (JS file's dir) + the path - return prefix + path; - } + Module['locateFile'] = function(path, prefix) { + // if it's a mem init file, use a custom dir + if (path.endsWith(".mem")) return "https://mycdn.com/memory-init-dir/" + path; + // otherwise, use the default, the prefix (JS file's dir) + the path + return prefix + path; + } .. js:attribute:: Module.logReadFiles - If set, stderr will log when any file is read. + If set, stderr will log when any file is read. .. js:attribute:: Module.onAbort - If set, this function is called when abnormal program termination occurs. That can happen due to the C method ``abort()`` being called directly, or called from JavaScript, or due to a fatal problem such as being unable to fetch a necessary file during startup (like the wasm binary when running wasm), etc. After calling this function, program termination occurs (i.e., you can't use this to try to do something else instead of stopping; there is no possibility of recovering here). + If set, this function is called when abnormal program termination occurs. That can happen due to the C method ``abort()`` being called directly, or called from JavaScript, or due to a fatal problem such as being unable to fetch a necessary file during startup (like the wasm binary when running wasm), etc. After calling this function, program termination occurs (i.e., you can't use this to try to do something else instead of stopping; there is no possibility of recovering here). .. js:attribute:: Module.onRuntimeInitialized - If set, this function is called when the runtime is fully initialized, that is, when compiled code is safe to run, which is after any asynchronous startup operations have completed (such as asynchronous WebAssembly compilation, file preloading, etc.). (An alternative to waiting for this to be called is to wait for ``main()`` to be called.) - + If set, this function is called when the runtime is fully initialized, that is, when compiled code is safe to run, which is after any asynchronous startup operations have completed (such as asynchronous WebAssembly compilation, file preloading, etc.). (An alternative to waiting for this to be called is to wait for ``main()`` to be called.) .. js:attribute:: Module.noExitRuntime - If ``noExitRuntime`` is set to ``true``, the runtime is not shut down after ``run`` completes. Shutting down the runtime calls shutdown callbacks, for example ``atexit`` calls. If you want to continue using the code after ``run()`` finishes, it is necessary to set this. This is automatically set for you if you use an API command that implies that you want the runtime to not be shut down, for example ``emscripten_set_main_loop``. + If ``noExitRuntime`` is set to ``true``, the runtime is not shut down after ``run`` completes. Shutting down the runtime calls shutdown callbacks, for example ``atexit`` calls. If you want to continue using the code after ``run()`` finishes, it is necessary to set this. This is automatically set for you if you use an API command that implies that you want the runtime to not be shut down, for example ``emscripten_set_main_loop``. .. js:attribute:: Module.noInitialRun - If ``noInitialRun`` is set to ``true``, ``main()`` will not be automatically called (you can do so yourself later). The program will still call global initializers, set up memory initialization, and so forth. - + If ``noInitialRun`` is set to ``true``, ``main()`` will not be automatically called (you can do so yourself later). The program will still call global initializers, set up memory initialization, and so forth. .. js:attribute:: Module.preInit - A function (or array of functions) that must be called before global initializers run, but after basic initialization of the JavaScript runtime. This is typically used for :ref:`File System operations `. + A function (or array of functions) that must be called before global initializers run, but after basic initialization of the JavaScript runtime. This is typically used for :ref:`File System operations `. .. js:attribute:: Module.preinitializedWebGLContext - If building with -s GL_PREINITIALIZED_CONTEXT=1 set, you can set ``Module.preinitializedWebGLContext`` to a precreated instance of a WebGL context, which will be used later when initializing WebGL in C/C++ side. Precreating the GL context is useful if doing GL side loading (shader compilation, texture loading etc.) parallel to other page startup actions, and/or for detecting WebGL feature support, such as GL version or compressed texture support up front on a page before or in parallel to loading up any compiled code. + If building with -s GL_PREINITIALIZED_CONTEXT=1 set, you can set ``Module.preinitializedWebGLContext`` to a precreated instance of a WebGL context, which will be used later when initializing WebGL in C/C++ side. Precreating the GL context is useful if doing GL side loading (shader compilation, texture loading etc.) parallel to other page startup actions, and/or for detecting WebGL feature support, such as GL version or compressed texture support up front on a page before or in parallel to loading up any compiled code. .. js:attribute:: Module.preRun - An array of functions to call right before calling ``run()``, but after defining and setting up the environment, including global initializers. This is useful, for example, to set up directories and files using the :ref:`Filesystem-API` — as this needs to happen after the FileSystem API has been loaded, but before the program starts to run. + An array of functions to call right before calling ``run()``, but after defining and setting up the environment, including global initializers. This is useful, for example, to set up directories and files using the :ref:`Filesystem-API` — as this needs to happen after the FileSystem API has been loaded, but before the program starts to run. - .. note:: If code needs to affect global initializers, it should instead be run using :js:attr:`preInit`. + .. note:: If code needs to affect global initializers, it should instead be run using :js:attr:`preInit`. .. js:attribute:: Module.print - Called when something is printed to standard output (stdout) + Called when something is printed to standard output (stdout) .. js:attribute:: Module.printErr - Called when something is printed to standard error (stderr) - + Called when something is printed to standard error (stderr) Other methods @@ -119,23 +116,23 @@ Other methods .. js:function:: Module.destroy(obj) - This method should be called to destroy C++ objects created in JavaScript using :ref:`WebIDL bindings `. If this method is not called, an object may be garbage collected, but its destructor will not be called. + This method should be called to destroy C++ objects created in JavaScript using :ref:`WebIDL bindings `. If this method is not called, an object may be garbage collected, but its destructor will not be called. - :param obj: The JavaScript-wrapped C++ object to be destroyed. + :param obj: The JavaScript-wrapped C++ object to be destroyed. .. js:function:: Module.getPreloadedPackage - If you want to manually manage the download of .data file packages for custom caching, progress reporting and error handling behavior, you can implement the ``Module.getPreloadedPackage = function(remotePackageName, remotePackageSize)`` callback to provide the contents of the data files back to the file loading scripts. The return value of this callback should be an Arraybuffer with the contents of the downloade file data. See file ``tests/manual_download_data.html`` and the test ``browser.test_preload_file_with_manual_data_download`` for an example. + If you want to manually manage the download of .data file packages for custom caching, progress reporting and error handling behavior, you can implement the ``Module.getPreloadedPackage = function(remotePackageName, remotePackageSize)`` callback to provide the contents of the data files back to the file loading scripts. The return value of this callback should be an Arraybuffer with the contents of the downloade file data. See file ``tests/manual_download_data.html`` and the test ``browser.test_preload_file_with_manual_data_download`` for an example. .. js:function:: Module.instantiateWasm - When targeting WebAssembly, Module.instantiateWasm is an optional user-implemented callback function that the Emscripten runtime calls to perform the WebAssembly instantiation action. The callback function will be called with two parameters, ``imports`` and ``successCallback``. ``imports`` is a JS object which contains all the function imports that need to be passed to the WebAssembly Module when instantiating, and once instantiated, this callback function should call ``successCallback()`` with the generated WebAssembly Instance object. + When targeting WebAssembly, Module.instantiateWasm is an optional user-implemented callback function that the Emscripten runtime calls to perform the WebAssembly instantiation action. The callback function will be called with two parameters, ``imports`` and ``successCallback``. ``imports`` is a JS object which contains all the function imports that need to be passed to the WebAssembly Module when instantiating, and once instantiated, this callback function should call ``successCallback()`` with the generated WebAssembly Instance object. - The instantiation can be performed either synchronously or asynchronously. The return value of this function should contain the ``exports`` object of the instantiated WebAssembly Module, or an empty dictionary object ``{}`` if the instantiation is performed asynchronously, or ``false`` if instantiation failed. + The instantiation can be performed either synchronously or asynchronously. The return value of this function should contain the ``exports`` object of the instantiated WebAssembly Module, or an empty dictionary object ``{}`` if the instantiation is performed asynchronously, or ``false`` if instantiation failed. - Overriding the WebAssembly instantiation procedure via this function is useful when you have other custom asynchronous startup actions or downloads that can be performed in parallel to WebAssembly compilation. Implementing this callback allows performing all of these in parallel. See the file ``tests/manual_wasm_instantiate.html`` and the test ``browser.test_manual_wasm_instantiate`` for an example of how this construct works in action. + Overriding the WebAssembly instantiation procedure via this function is useful when you have other custom asynchronous startup actions or downloads that can be performed in parallel to WebAssembly compilation. Implementing this callback allows performing all of these in parallel. See the file ``tests/manual_wasm_instantiate.html`` and the test ``browser.test_manual_wasm_instantiate`` for an example of how this construct works in action. .. js:function:: Module.onCustomMessage - When compiled with ``PROXY_TO_WORKER = 1`` (see `settings.js `_), this callback (which should be implemented on both the client and worker's ``Module`` object) allows sending custom messages and data between the web worker and the main thread (using the ``postCustomMessage`` function defined in `proxyClient.js `_ and `proxyWorker.js `_). + When compiled with ``PROXY_TO_WORKER = 1`` (see `settings.js `_), this callback (which should be implemented on both the client and worker's ``Module`` object) allows sending custom messages and data between the web worker and the main thread (using the ``postCustomMessage`` function defined in `proxyClient.js `_ and `proxyWorker.js `_). diff --git a/site/source/docs/api_reference/preamble.js.rst b/site/source/docs/api_reference/preamble.js.rst index eed70820702b0..e61a50c97b914 100644 --- a/site/source/docs/api_reference/preamble.js.rst +++ b/site/source/docs/api_reference/preamble.js.rst @@ -47,13 +47,15 @@ Calling compiled C functions from JavaScript .. note:: - ``ccall`` uses the C stack for temporary values. If you pass a string then it is only "alive" until the call is complete. If the code being called saves the pointer to be used later, it may point to invalid data. - If you need a string to live forever, you can create it, for example, using ``_malloc`` and :js:func:`stringToUTF8`. However, you must later delete it manually! - - LLVM optimizations can inline and remove functions, after which you will not be able to call them. Similarly, function names minified by the *Closure Compiler* are inaccessible. In either case, the solution is to add the functions to the ``EXPORTED_FUNCTIONS`` list when you invoke *emcc* : + - LLVM optimizations can inline and remove functions, after which you will not be able to call them. Similarly, function names minified by the *Closure Compiler* are inaccessible. In either case, the solution is to add the functions to the ``EXPORTED_FUNCTIONS`` list when you invoke *emcc*: - :: + .. code-block:: none -s EXPORTED_FUNCTIONS="['_main', '_myfunc']" - (Note that we also export ``main`` - if we didn't, the compiler would assume we don't need it.) Exported functions can then be called as normal: :: + (Note that we also export ``main`` - if we didn't, the compiler would assume we don't need it.) Exported functions can then be called as normal: + + .. code-block:: javascript a_result = Module.ccall('myfunc', 'number', ['number'], [10]) @@ -100,11 +102,13 @@ Calling compiled C functions from JavaScript - LLVM optimizations can inline and remove functions, after which you will not be able to "wrap" them. Similarly, function names minified by the *Closure Compiler* are inaccessible. In either case, the solution is to add the functions to the ``EXPORTED_FUNCTIONS`` list when you invoke *emcc* : - ``cwrap`` does not actually call compiled code (only calling the wrapper it returns does that). That means that it is safe to call ``cwrap`` early, before the runtime is fully initialized (but calling the returned wrapped function must wait for the runtime, of course, like calling compiled code in general). - :: + .. code-block:: none -s EXPORTED_FUNCTIONS="['_main', '_myfunc']" - Exported functions can be called as normal: :: + Exported functions can be called as normal: + + .. code-block:: javascript my_func = Module.cwrap('myfunc', 'number', ['number']) my_func(12) @@ -116,8 +120,6 @@ Calling compiled C functions from JavaScript :returns: A JavaScript function that can be used for running the C function. - - Accessing memory ================ @@ -137,7 +139,6 @@ Accessing memory :type noSafe: bool - .. js:function:: getValue(ptr, type[, noSafe]) Gets a value at a specific memory address at run-time. diff --git a/site/source/docs/api_reference/val.h.rst b/site/source/docs/api_reference/val.h.rst index 5857a75135577..525588b0582d1 100644 --- a/site/source/docs/api_reference/val.h.rst +++ b/site/source/docs/api_reference/val.h.rst @@ -109,13 +109,6 @@ Guide material for this class can be found in :ref:`embind-val-guide`. :returns: **HamishW**-Replace with description. - .. cpp:function:: static val module_property(const char* name) - - **HamishW**-Replace with description. - - :param const char* name: **HamishW**-Replace with description. - :returns: **HamishW**-Replace with description. - .. cpp:function:: explicit val(T&& value) Constructor. diff --git a/site/source/docs/building_from_source/building_fastcomp_manually_from_source.rst b/site/source/docs/building_from_source/building_fastcomp_manually_from_source.rst index 66b880ac2b7cd..9611e3cbfc9f5 100644 --- a/site/source/docs/building_from_source/building_fastcomp_manually_from_source.rst +++ b/site/source/docs/building_from_source/building_fastcomp_manually_from_source.rst @@ -4,7 +4,7 @@ Manually building Fastcomp from source ====================================== -:ref:`Fastcomp ` is the default compiler core for Emscripten. It is a new :term:`LLVM backend` that converts the LLVM Intermediate Representation (IR) created by *Clang* (from C/C++) into JavaScript. +:ref:`Fastcomp ` is the default compiler core for Emscripten. It is a new :term:`LLVM backend` that converts the LLVM Intermediate Representation (IR) created by *Clang* (from C/C++) into JavaScript. This article explains how you can build Fastcomp's sources using a fully manual process. @@ -26,46 +26,46 @@ Then follow the instructions for your platform showing how to :ref:`manually bui Building Fastcomp ================= -To build the Fastcomp code from source: +To build the Fastcomp code from source: - Create a directory to store the build. It doesn't matter where, because Emscripten gets the information from the :ref:`compiler configuration file (~/.emscripten) `. We show how to update this file later in these instructions: :: - + mkdir myfastcomp cd myfastcomp - -- Clone the fastcomp LLVM repository (https://github.com/kripken/emscripten-fastcomp): + +- Clone the fastcomp LLVM repository (https://github.com/kripken/emscripten-fastcomp): :: - + git clone https://github.com/kripken/emscripten-fastcomp - -- Clone the `kripken/emscripten-fastcomp-clang `_ repository into **emscripten-fastcomp/tools/clang**: + +- Clone the `kripken/emscripten-fastcomp-clang `_ repository into **emscripten-fastcomp/tools/clang**: :: - + cd emscripten-fastcomp git clone https://github.com/kripken/emscripten-fastcomp-clang tools/clang - .. warning:: You **must** clone it into a directory named **clang** as shown, so that :term:`Clang` is present in **tools/clang**! - + .. warning:: You **must** clone it into a directory named **clang** as shown, so that :term:`Clang` is present in **tools/clang**! + - Create a *build* directory (inside the **emscripten-fastcomp** directory) and then navigate into it: - + :: - + mkdir build cd build - + - Configure the build using *cmake*: :: - + cmake .. -DCMAKE_BUILD_TYPE=Release -DLLVM_TARGETS_TO_BUILD="host;JSBackend" -DLLVM_INCLUDE_EXAMPLES=OFF -DLLVM_INCLUDE_TESTS=OFF -DCLANG_INCLUDE_TESTS=OFF - + .. note:: On Windows you will need Visual Studio 2015 or newer to build. - Determine the number of available cores on your system (Emscripten can run many operations in parallel, so using more cores may have a significant impact on compilation time): @@ -77,25 +77,24 @@ To build the Fastcomp code from source: - Call *make* to build the sources, specifying the number of available cores: :: - + make -j4 - + .. note:: If the build completes successfully, *clang*, *clang++*, and a number of other files will be created in the release directory (**/build/Release/bin**). .. _llvm-update-compiler-configuration-file: - -- - - The final step is to update the :ref:`~/.emscripten ` file, specifying the location of *fastcomp* in the ``LLVM_ROOT`` variable. - +- + + The final step is to update the :ref:`~/.emscripten ` file, specifying the location of *fastcomp* in the ``LLVM_ROOT`` variable. + .. note:: If you're building the **whole** of Emscripten from source, following the platform-specific instructions in :ref:`installing-from-source`, you won't yet have Emscripten installed. In this case, skip this step and return to those instructions. - If you already have an Emscripten environment (for example if you're building Fastcomp using the SDK), then set ``LLVM_ROOT`` to the location of the *clang* binary under the **build** directory. This will be something like **/build/Release/bin** or **/build/bin**: + If you already have an Emscripten environment (for example if you're building Fastcomp using the SDK), then set ``LLVM_ROOT`` to the location of the *clang* binary under the **build** directory. This will be something like **/build/Release/bin** or **/build/bin**: + + .. code-block:: none - :: - LLVM_ROOT='/home/ubuntu/yourpath/emscripten-fastcomp/build/bin' .. _building-fastcomp-from-source-branches: @@ -107,11 +106,11 @@ You should use the **same** branch (*incoming*, or *master*) for building all th - Emscripten: `emscripten `_. - Emscripten's LLVM fork: `emscripten-fastcomp `_. -- Emscripten's *Clang* fork `emscripten-fastcomp-clang `_. +- Emscripten's *Clang* fork `emscripten-fastcomp-clang `_. Mixing *incoming* and *master* branches may result in errors when building the three repositories. -Run ``emcc -v`` to check if the branches are synchronized. +Run ``emcc -v`` to check if the branches are synchronized. .. note:: ``emcc -v`` checks the code in the repositories, not the builds. Before building make sure that you fetch the latest changes to LLVM and Clang. @@ -120,9 +119,9 @@ Version numbers Bisecting across multiple git trees can be hard. We use version numbers to help synchronize points between them: -- `emscripten-version.txt `_ in Emscripten -- `emscripten-version.txt `_ in fastcomp (llvm) -- `emscripten-version.txt `_ in fastcomp-clang (clang) +- `emscripten-version.txt `__ in Emscripten +- `emscripten-version.txt `__ in fastcomp (llvm) +- `emscripten-version.txt `__ in fastcomp-clang (clang) Version numbers are typically ``X.Y.Z`` where: diff --git a/site/source/docs/building_from_source/verify_emscripten_environment.rst b/site/source/docs/building_from_source/verify_emscripten_environment.rst index a5560d069b5d3..1fce923fc016d 100644 --- a/site/source/docs/building_from_source/verify_emscripten_environment.rst +++ b/site/source/docs/building_from_source/verify_emscripten_environment.rst @@ -13,43 +13,39 @@ Testing the environment Sanity tests ------------ -The first step in verifying the environment is to run Emscripten with the version command (``-v``). The command prints out information about the toolchain and runs some basic sanity tests to check that the required tools are available. +The first step in verifying the environment is to run Emscripten with the version command (``-v``). The command prints out information about the toolchain and runs some basic sanity tests to check that the required tools are available. -Open a terminal in the directory in which you installed Emscripten (on Windows open the :ref:`Emscripten Command Prompt `). Then call the :ref:`Emscripten Compiler Frontend (emcc) ` as shown: +Open a terminal in the directory in which you installed Emscripten (on Windows open the :ref:`Emscripten Command Prompt `). Then call the :ref:`Emscripten Compiler Frontend (emcc) ` as shown:: -:: - - ./emcc -v + ./emcc -v .. note:: On Windows, invoke the tool with **emsdk** instead of **./emsdk**. - -For example, the following output reports an installation where Java is missing: -.. code-block:: javascript - :emphasize-lines: 6 +For example, the following output reports an installation where Java is missing:: + :emphasize-lines: 6 - emcc (Emscripten GCC-like replacement + linker emulating GNU ld ) 1.21.0 - clang version 3.3 - Target: x86_64-pc-win32 - Thread model: posix - INFO root: (Emscripten: Running sanity checks) - WARNING root: java does not seem to exist, required for closure compiler. -O2 and above will fail. You need to define JAVA in ~/.emscripten + emcc (Emscripten GCC-like replacement + linker emulating GNU ld ) 1.21.0 + clang version 3.3 + Target: x86_64-pc-win32 + Thread model: posix + INFO root: (Emscripten: Running sanity checks) + WARNING root: java does not seem to exist, required for closure compiler. -O2 and above will fail. You need to define JAVA in ~/.emscripten At this point you need to :ref:`Install and activate ` any missing components. When everything is set up properly, ``./emcc -v`` should give no warnings, and if you just enter ``./emcc`` (without any input files), it should only give the following warning: :: - WARNING root: no input files + WARNING root: no input files + - Build a basic example --------------------- -The next test is to actually build some code! On the command prompt navigate to the Emscripten directory for the current SDK and try to build the **hello_world.cpp** test code: +The next test is to actually build some code! On the command prompt navigate to the Emscripten directory for the current SDK and try to build the **hello_world.cpp** test code: :: - cd emscripten/ - ./emcc tests/hello_world.cpp - + cd emscripten/ + ./emcc tests/hello_world.cpp + This command should complete without warnings and you should find the newly-compiled JavaScript file (**a.out.js**) in the current directory. If compiling succeeds, you're ready for the :ref:`Tutorial`. If not, check out the troubleshooting instructions below. @@ -60,29 +56,30 @@ Run the full test suite Emscripten has a comprehensive test suite which may be used to further validate all or parts of the toolchain. For more information, see :ref:`emscripten-test-suite`. - + .. _troubleshooting-emscripten-environment: Troubleshooting =============== -First run ``./emcc -v`` and examine the output to find missing components. You can also try ``./emcc --clear-cache`` to empty the :ref:`compiler's internal cache ` and reset it to a known good state. +First run ``./emcc -v`` and examine the output to find missing components. You can also try ``./emcc --clear-cache`` to empty the :ref:`compiler's internal cache ` and reset it to a known good state. + .. _fixing-missing-components-emcc: -Installing missing components +Installing missing components ----------------------------- -Missing tools can often be added using the :ref:`emsdk`. For example, to fix a warning that Java is missing, locate it in the repository, install it, and then set it as active: :: - - #List all the components. Look for the missing component (in this case "java-7.45-64bit") - ./emsdk list - - #Install the missing component - ./emsdk install java-7.45-64bit - - #Set the component as active - ./emsdk activate java-7.45-64bit +Missing tools can often be added using the :ref:`emsdk`. For example, to fix a warning that Java is missing, locate it in the repository, install it, and then set it as active:: + + #List all the components. Look for the missing component (in this case "java-7.45-64bit") + ./emsdk list + + #Install the missing component + ./emsdk install java-7.45-64bit + + #Set the component as active + ./emsdk activate java-7.45-64bit If you're :ref:`building Emscripten manually from source `, see that link for information on how to obtain all dependencies. @@ -92,8 +89,8 @@ Other common problems Other common problems to check for are: - - Errors in the paths in :ref:`.emscripten `. These are less likely if you update the file using :ref:`emsdk `. - - Using older versions of Node or JavaScript engines. Use the default versions for the SDK as listed with :ref:`emsdk list `. - - Using older versions of LLVM. The correct versions come with the SDK, but if you're building the environment from source see :ref:`LLVM-Backend` for the proper repos for LLVM and Clang. + - Errors in the paths in :ref:`.emscripten `. These are less likely if you update the file using :ref:`emsdk `. + - Using older versions of Node or JavaScript engines. Use the default versions for the SDK as listed with :ref:`emsdk list `. + - Using older versions of LLVM. The correct versions come with the SDK, but if you're building the environment from source see :ref:`LLVM-Backend` for the proper repos for LLVM and Clang. If none of the above is helpful, then please :ref:`contact us ` for help. diff --git a/site/source/docs/compiling/Building-Projects.rst b/site/source/docs/compiling/Building-Projects.rst index ea04f3e1b0919..b7e9bb3818053 100644 --- a/site/source/docs/compiling/Building-Projects.rst +++ b/site/source/docs/compiling/Building-Projects.rst @@ -308,4 +308,4 @@ Troubleshooting .. note:: You can use ``llvm-nm`` to see which symbols are defined in each bitcode file. - One solution is to use the :ref:`building-projects-dynamic-linking-workaround` approach described above. This ensures that libraries are linked only once, in the final build stage. + One solution is to use the _`dynamic-linking` approach described above. This ensures that libraries are linked only once, in the final build stage. diff --git a/site/source/docs/compiling/WebAssembly.rst b/site/source/docs/compiling/WebAssembly.rst index f2c7676ce9dc9..9b7968da78d83 100644 --- a/site/source/docs/compiling/WebAssembly.rst +++ b/site/source/docs/compiling/WebAssembly.rst @@ -38,7 +38,7 @@ By default, it will try native support. The full list of methods is - ``interpret-asm2wasm``: Load ``.asm.js``, compile to wasm on the fly, and interpret that. - ``asmjs``: Load ``.asm.js`` and just run it, no wasm. Useful for comparisons, or as a fallback for browsers without WebAssembly support. -For more details, see the function ``integrateWasmJS`` in :ref:`preamble.js `, which is where all the integration between JavaScript and WebAssembly happens. +For more details, see the function ``integrateWasmJS`` in :ref:`preamble-js`, which is where all the integration between JavaScript and WebAssembly happens. Codegen effects --------------- diff --git a/site/source/docs/getting_started/test-suite.rst b/site/source/docs/getting_started/test-suite.rst index c5cf4b062d2cc..f4aed73509c20 100644 --- a/site/source/docs/getting_started/test-suite.rst +++ b/site/source/docs/getting_started/test-suite.rst @@ -112,6 +112,8 @@ When you want to run the entire test suite locally, these are the important comm # Optionally, also run benchmarks to check for regressions python tests/runner.py benchmark +.. _benchmarking: + Benchmarking ============ diff --git a/site/source/docs/index.rst b/site/source/docs/index.rst index cf043d91e116a..d8656e4377648 100644 --- a/site/source/docs/index.rst +++ b/site/source/docs/index.rst @@ -1,9 +1,12 @@ +:orphan: + .. _documentation-home: ======================== Emscripten Documentation ======================== + This comprehensive documentation set contains everything you need to know to use Emscripten. **Getting started:** @@ -33,21 +36,18 @@ This comprehensive documentation set contains everything you need to know to use The full hierarchy of articles, opened to the second level, is shown below. .. toctree:: - :maxdepth: 2 - - introducing_emscripten/index - getting_started/index - porting/index - optimizing/Optimizing-Code - optimizing/Optimizing-WebGL - optimizing/Profiling-Toolchain - compiling/index - building_from_source/index - contributing/index - api_reference/index - tools_reference/index - debugging/CyberDWARF - site/index - - - + :maxdepth: 2 + + introducing_emscripten/index + getting_started/index + porting/index + optimizing/Optimizing-Code + optimizing/Optimizing-WebGL + optimizing/Profiling-Toolchain + compiling/index + building_from_source/index + contributing/index + api_reference/index + tools_reference/index + debugging/CyberDWARF + site/index diff --git a/site/source/docs/introducing_emscripten/Talks-and-Publications.rst b/site/source/docs/introducing_emscripten/Talks-and-Publications.rst index 21c4344b4f4ad..df1061d732fd7 100644 --- a/site/source/docs/introducing_emscripten/Talks-and-Publications.rst +++ b/site/source/docs/introducing_emscripten/Talks-and-Publications.rst @@ -13,11 +13,11 @@ Presentations - `Emscripten & asm.js: C++'s role in the modern web `_ (`kripken `_) - - `Video of talk `_ + - `Video of talk `__ - `Connecting C++ and JavaScript on the Web with Embind `_ (`chadaustin `_) - - `Video of talk `_ + - `Video of talk `__ - Slides from GDC 2014: `Getting started with asm.js and Emscripten `_ (`kripken `_, `lwagner `_) - Slides from Strange Loop 2013: `Native speed on the web, JavaScript and asm.js `_ (`kripken `_) diff --git a/site/source/docs/introducing_emscripten/about_emscripten.rst b/site/source/docs/introducing_emscripten/about_emscripten.rst index 275da7361d1e3..b1eb0029bf323 100644 --- a/site/source/docs/introducing_emscripten/about_emscripten.rst +++ b/site/source/docs/introducing_emscripten/about_emscripten.rst @@ -32,7 +32,7 @@ Practically any **portable** C or C++ codebase can be compiled into JavaScript u For more demos, see the `list on the wiki `_. -Emscripten generates fast code! Its default output format is `asm.js `_ , a highly optimizable subset of JavaScript that can execute at close to native speed in many cases (check out the `current benchmark results `_ or run the :ref:`benchmark tests ` yourself). Optimized Emscripten code has also been `shown to have `_ a similar *effective size* to native code, when both are gzipped. +Emscripten generates fast code! Its default output format is `asm.js `_ , a highly optimizable subset of JavaScript that can execute at close to native speed in many cases (check out the `current benchmark results `_ or run the :ref:`benchmark tests ` yourself). Optimized Emscripten code has also been `shown to have `_ a similar *effective size* to native code, when both are gzipped. For a better understanding of just how fast and fluid Emscripten-ported code can be, check out the `Dead Trigger 2 `_ and `Angrybots `_ demos above. diff --git a/site/source/docs/optimizing/Optimizing-Code.rst b/site/source/docs/optimizing/Optimizing-Code.rst index 11d59f2e24b34..ba0e1a7087c88 100644 --- a/site/source/docs/optimizing/Optimizing-Code.rst +++ b/site/source/docs/optimizing/Optimizing-Code.rst @@ -95,19 +95,18 @@ A workaround is to separate out the asm.js into another file, and to make sure t You can also do this manually, as follows: * Run ``tools/separate_asm.py``. This receives as inputs the filename of the full project, and two filenames to emit: the asm.js file and a file for everything else. - * Load the asm.js script first, then after a turn of the event loop, the other one, for example using code like this in your HTML file: - :: - var script = document.createElement('script'); - script.src = "the_asm.js"; - script.onload = function() { - setTimeout(function() { - var script = document.createElement('script'); - script.src = "the_rest.js"; - document.body.appendChild(script); - }, 1); // delaying even 1ms is enough - }; - document.body.appendChild(script); - + * Load the asm.js script first, then after a turn of the event loop, the other one, for example using code like this in your HTML file: :: + + var script = document.createElement('script'); + script.src = "the_asm.js"; + script.onload = function() { + setTimeout(function() { + var script = document.createElement('script'); + script.src = "the_rest.js"; + document.body.appendChild(script); + }, 1); // delaying even 1ms is enough + }; + document.body.appendChild(script); .. _optimizing-code-outlining: diff --git a/site/source/docs/porting/Debugging.rst b/site/source/docs/porting/Debugging.rst index 82e51fd255f8f..a9383b1b883ad 100644 --- a/site/source/docs/porting/Debugging.rst +++ b/site/source/docs/porting/Debugging.rst @@ -112,9 +112,7 @@ You can also manually instrument the source code with ``printf()`` statements, t If you have a good idea of the problem line you can add ``print(new Error().stack)`` to the JavaScript to get a stack trace at that point. Also available is :js:func:`stackTrace`, which emits a stack trace and tries to demangle C++ function names (if you don't want or need C++ demangling, you can call :js:func:`jsStackTrace`). -Debug printouts can even execute arbitrary JavaScript. For example: - -.. code-block:: cpp +Debug printouts can even execute arbitrary JavaScript. For example:: function _addAndPrint($left, $right) { $left = $left | 0; diff --git a/site/source/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.rst b/site/source/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.rst index 2b1573eef0b2d..fcd1174210c2a 100644 --- a/site/source/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.rst +++ b/site/source/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.rst @@ -215,17 +215,17 @@ appears in the generated code. This will be the same as the original C function, but with a leading ``_``. .. note:: If you use :js:func:`ccall` or :js:func:`cwrap`, you do not need - to prefix function calls with ``_`` — just use the C name. + to prefix function calls with ``_`` -- just use the C name. The types of the parameters you pass to functions need to make sense. Integers and floating point values can be passed as is. Pointers are simply integers in the generated code. Strings in JavaScript must be converted to pointers for compiled -code — the relevant function is :js:func:`Pointer_stringify`, which +code -- the relevant function is :js:func:`Pointer_stringify`, which given a pointer returns a JavaScript string. Converting a JavaScript string ``someString`` to a pointer can be accomplished using ``ptr = `` -:js:func:`allocate(intArrayFromString(someString), 'i8', ALLOC_NORMAL) `. +allocate(intArrayFromString(someString), 'i8', ALLOC_NORMAL) ``. .. note:: The conversion to a pointer allocates memory, which needs to be freed up via a call to ``free(ptr)`` afterwards (``_free`` in JavaScript side) @@ -261,9 +261,7 @@ A faster way to call JavaScript from C is to write "inline JavaScript", using :c:func:`EM_JS` or :c:func:`EM_ASM` (and related macros). EM_JS is used to declare JavaScript functions from inside a C file. The "alert" -example might be written using EM_JS like: - -.. code-block:: c++ +example might be written using EM_JS like:: #include @@ -281,9 +279,7 @@ EM_JS's implementation is essentially a shorthand for :ref:`implementing a JavaScript library`. EM_ASM is used in a similar manner to inline assembly code. The "alert" example -might be written with inline JavaScript as: - -.. code-block:: c++ +might be written with inline JavaScript as:: #include @@ -302,26 +298,22 @@ Emscripten still does a function call even in this case, which has some amount of overhead.) You can also send values from C into JavaScript inside :c:macro:`EM_ASM_` -(note the extra "_" at the end), for example +(note the extra "_" at the end), for example:: -.. code-block:: cpp - - EM_ASM_({ - console.log('I received: ' + $0); - }, 100); + EM_ASM_({ + console.log('I received: ' + $0); + }, 100); This will show ``I received: 100``. You can also receive values back, for example the following will print out ``I received: 100`` -and then ``101``. - -.. code-block:: cpp +and then ``101``:: - int x = EM_ASM_INT({ - console.log('I received: ' + $0); - return $0 + 1; - }, 100); - printf("%d\n", x); + int x = EM_ASM_INT({ + console.log('I received: ' + $0); + return $0 + 1; + }, 100); + printf("%d\n", x); See the :c:macro:`emscripten.h docs ` for more details. diff --git a/site/source/docs/porting/files/packaging_files.rst b/site/source/docs/porting/files/packaging_files.rst index 3b419e8398179..8ab5fbd58bc2d 100644 --- a/site/source/docs/porting/files/packaging_files.rst +++ b/site/source/docs/porting/files/packaging_files.rst @@ -11,7 +11,7 @@ There are two alternatives for how files are packaged: *preloading* and *embeddi *Emcc* uses the *file packager* to package the files and generate the :ref:`File System API ` calls that create and load the file system at run time. While *Emcc* is the recommended tool for packaging, there are cases where it can make sense to run the *file packager* manually. With ``--use-preload-plugins``, files can be automatically decoded based on -their extension. See :ref:`preload-files` for more information. +their extension. See :ref:`preloading-files` for more information. Packaging using emcc ==================== diff --git a/site/source/docs/site/about.rst b/site/source/docs/site/about.rst index ed03991dbfdbd..db7585d2051da 100644 --- a/site/source/docs/site/about.rst +++ b/site/source/docs/site/about.rst @@ -4,7 +4,7 @@ About this site =============== -The site is built using `Sphinx `_ (1.2.2), the open source tool used to create the official Python documentation and many other sites. This is a very mature and stable tool, and was selected for, among other reasons, its support for defining API items and linking to them from code. +The site is built using `Sphinx `_ (1.2.2), the open source tool used to create the official Python documentation and many other sites. This is a very mature and stable tool, and was selected for, among other reasons, its support for defining API items and linking to them from code. The site uses a custom theme, which is based on the :ref:`read-the-docs-theme`. @@ -13,9 +13,9 @@ The site uses a custom theme, which is based on the :ref:`read-the-docs-theme`. Searching the site ================== -Searching returns topics that contain **all** the specified keywords. +Searching returns topics that contain **all** the specified keywords. -.. tip:: Always start by searching for *single* words like "interacting" or "compiling". Generally this will be enough to find the relevant document. If not, you can refine the search by adding additional terms. +.. tip:: Always start by searching for *single* words like "interacting" or "compiling". Generally this will be enough to find the relevant document. If not, you can refine the search by adding additional terms. .. note:: Searches that include characters like "-" and "+" will not work. There is no support for logical operators. @@ -29,7 +29,7 @@ Please :ref:`report documentation bugs ` as Contributing to the site ======================== -:ref:`Contributions ` to this site (and indeed any part of Emscripten) are welcome! +:ref:`Contributions ` to this site (and indeed any part of Emscripten) are welcome! Check out the rest of this article for instructions on how to :ref:`build the site ` and :ref:`write and update articles `. @@ -39,7 +39,7 @@ Check out the rest of this article for instructions on how to :ref:`build the si Building the site ================= -The site sources are stored on Github `here `_. Edits and additions should be submitted to this branch in the same way as any other change to the tool. +The site sources are stored on `Github `_. Edits and additions should be submitted to this branch in the same way as any other change to the tool. The site is published to the **kripken/emscripten-site** *gh-pages* branch (Github pages). @@ -48,18 +48,18 @@ The site is published to the **kripken/emscripten-site** *gh-pages* branch (Gith Installing Sphinx ----------------- -Notes for installing Sphinx are provided `here `_. +Notes for installing Sphinx are provided `here `_. Ubuntu ++++++ -The version of Sphinx on Ubuntu package repository (apt-get) fails when building the site. This is an early version (1.1.3), which appears to be dependent on an old version of the Jinja templating library. -The workaround is to use the *Python package installer* (pip) to get version 1.2.2, and then run an upgrade (note, you may have to uninstall Sphinx first): :: +The version of Sphinx on Ubuntu package repository (apt-get) fails when building the site. This is an early version (1.1.3), which appears to be dependent on an old version of the Jinja templating library. + +The workaround is to use the *Python package installer* (pip) to get version 1.7.8, and then run an upgrade (note, you may have to uninstall Sphinx first): :: + + pip install sphinx==1.7.9 - pip install sphinx - pip install sphinx --upgrade - .. _about-site-builds: @@ -68,9 +68,9 @@ Site builds The site can be built from source on Ubuntu and Windows by navigating to the */emscripten/site* directory and using the command: :: - make clean - make html - + make clean + make html + .. _about-sdk-builds: @@ -81,13 +81,13 @@ SDK builds are virtually identical to :ref:`about-site-builds`. The main differe SDK builds are enabled by enabling the ``sdkbuild`` tag. This is done through the ``SPHINXOPTS`` environment variable: :: - # Set the sdkbuild tag. - set SPHINXOPTS=-t sdkbuild - make html - - # Unset SPHINXOPTS - set SPHINXOPTS= - + # Set the sdkbuild tag. + set SPHINXOPTS=-t sdkbuild + make html + + # Unset SPHINXOPTS + set SPHINXOPTS= + .. _about-build-versions: Build version @@ -99,13 +99,13 @@ The version and release information is used in a few places in the documentation The version information is defined in **conf.py** — see variables ``version`` and ``release``. These variables can be overridden by setting new values in the ``SPHINXOPTS`` environment variable. For example, to update the ``release`` variable through the command line on Windows: :: - # Set SPHINXOPTS - set SPHINXOPTS=-D release=6.40 - make html - - # Unset SPHINXOPTS - set SPHINXOPTS= - + # Set SPHINXOPTS + set SPHINXOPTS=-D release=6.40 + make html + + # Unset SPHINXOPTS + set SPHINXOPTS= + .. _writing-and-updating-articles: @@ -114,9 +114,9 @@ Writing and updating articles .. note:: Sphinx is `well documented `_. This section only attempts to highlight specific styles and features used on this site. - The :ref:`building-the-site` section explains how to find the sources for articles and build the site. + The :ref:`building-the-site` section explains how to find the sources for articles and build the site. + - Site content is written using :term:`reStructured text`. We recommend you read the following articles to understand the syntax: * `reStructured text primer `_. @@ -128,7 +128,7 @@ Site content is written using :term:`reStructured text`. We recommend you read t Style guide ----------- -This section has a few very brief recommendations to help authors use common style. +This section has a few very brief recommendations to help authors use common style. .. tip:: In terms of contributions, we value your coding and content writing far more than perfect prose! Just do your best, and then :ref:`ask for editorial review `. @@ -138,33 +138,33 @@ This section has a few very brief recommendations to help authors use common sty **Emphasis:** - - **Bold** : use for file names, and UI/menu instructions (for example: "Press **OK** to do something"). - - *Italic* : use for tool names - e.g. *Clang*, *emcc*, *Closure Compiler*. - - ``monotype`` : use for inline code (where you can't link to the API reference) and for demonstrating tool command line options. - - .. note:: Other than the above rules, emphasis should be used sparingly. + - **Bold** : use for file names, and UI/menu instructions (for example: "Press **OK** to do something"). + - *Italic* : use for tool names - e.g. *Clang*, *emcc*, *Closure Compiler*. + - ``monotype`` : use for inline code (where you can't link to the API reference) and for demonstrating tool command line options. + + .. note:: Other than the above rules, emphasis should be used sparingly. **Lists**: Use a colon on the lead-in to the list where appropriate. Capitalize the first letter and use a full-stop for each item. - + How to link to a document or heading ------------------------------------ To link to a page, first define a globally unique reference before the page title (e.g. ``_my-page-reference``) then link to it using the `ref `_ role as shown: :: - .. _my-page-reference: + .. _my-page-reference: - My Page Title - ============= + My Page Title + ============= - This is the text of the section. - - To link to page use either of the options below: - ref:`my-reference-label` - the link text is the heading name after the reference - ref:`some text ` - the link text is "some text" + This is the text of the section. -This is a better approach than linking to documents using the *:doc:* role, because the links do not get broken if the articles are moved. + To link to page use either of the options below: + ref:`my-reference-label` - the link text is the heading name after the reference + ref:`some text ` - the link text is "some text" + +This is a better approach than linking to documents using the *:doc:* role, because the links do not get broken if the articles are moved. This approach is also recommended for linking to arbitrary headings in the site. @@ -177,66 +177,66 @@ Recommended section/heading markup reStructured text `defines `_ section headings using a separate line of punctuation characters after (and optionally before) the heading text. The line of characters must be at least as long as the heading. For example: :: - A heading - ========= + A heading + ========= Different punctuation characters are used to specify nested sections. Although the system does not mandate which punctuation character is used for each nested level, it is important to be consistent. The recommended heading levels are: :: - ======================================= - Page title (top and bottom bars of "=") - ======================================= - - Level 1 heading (single bar of "=" below) - ========================================= - - Level 2 heading (single bar of "-" below) - ----------------------------------------- - - Level 3 heading (single bar of "+" below) - +++++++++++++++++++++++++++++++++++++++++ - - Level 4 heading (single bar of "~" below) - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + ======================================= + Page title (top and bottom bars of "=") + ======================================= + + Level 1 heading (single bar of "=" below) + ========================================= + + Level 2 heading (single bar of "-" below) + ----------------------------------------- + + Level 3 heading (single bar of "+" below) + +++++++++++++++++++++++++++++++++++++++++ + + Level 4 heading (single bar of "~" below) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Working in markdown ------------------- - -New articles may be authored and discussed on the `wiki `_ using Markdown syntax before being included in the documentation set. The easiest way to convert these to restructured text is to use a tool like `Pandoc `_. -.. note:: The *get_wiki.py* tool (**/site/source/get_wiki.py**) can be used to automate getting a snapshot of the wiki. It clones the wiki and calls *pandoc* on each file. The output is copied to a folder **wiki_static**. The tool also adds a heading, a note stating that the file is a "wiki snapshot", and fixes up links marked as "inline code" to matching links in the API Reference. - - +New articles may be authored and discussed on the `wiki `_ using Markdown syntax before being included in the documentation set. The easiest way to convert these to restructured text is to use a tool like `Pandoc `_. + +.. note:: The *get_wiki.py* tool (**/site/source/get_wiki.py**) can be used to automate getting a snapshot of the wiki. It clones the wiki and calls *pandoc* on each file. The output is copied to a folder **wiki_static**. The tool also adds a heading, a note stating that the file is a "wiki snapshot", and fixes up links marked as "inline code" to matching links in the API Reference. + + .. _read-the-docs-theme: - -Read the docs theme + +Read the docs theme =================== The site uses a modification of the `Read the docs theme `_ (this can be found in the source at */emscripten/site/source/_themes/emscripten_sphinx_rtd_theme*). -The main changes to the original theme are listed below. +The main changes to the original theme are listed below. + +- **Footer.html** -- **Footer.html** + - Copyright changed to link to Emscripten authors (some code was broken by translation markup) + - Added footer menu bar - - Copyright changed to link to Emscripten authors (some code was broken by translation markup) - - Added footer menu bar - - **Layout.html** - - Added header menu bar with items - + - Added header menu bar with items + - **Breadcrumb.html** - - - Changed the text of the first link from "docs" to "Home" - - Moved the "View Page Source" code into the bottom footer + + - Changed the text of the first link from "docs" to "Home" + - Moved the "View Page Source" code into the bottom footer - **theme.css** - - - Changed to support 4 levels of depth in sidebar toc. - - Centred theme. Made sidebar reach bottom of page using absolute positioning. + + - Changed to support 4 levels of depth in sidebar toc. + - Centred theme. Made sidebar reach bottom of page using absolute positioning. -Site license +Site license ============ -The site is licensed under the same :ref:`emscripten-license` as the rest of Emscripten. Contributors to the site should add themselves to :ref:`emscripten-authors`. \ No newline at end of file +The site is licensed under the same :ref:`emscripten-license` as the rest of Emscripten. Contributors to the site should add themselves to :ref:`emscripten-authors`. diff --git a/site/source/docs/site/glossary.rst b/site/source/docs/site/glossary.rst index 92528b168eaa6..97b168cde802a 100644 --- a/site/source/docs/site/glossary.rst +++ b/site/source/docs/site/glossary.rst @@ -6,98 +6,98 @@ General ======= .. glossary:: - :sorted: - - XHR - Contraction of ``XMLHttpRequest``. Emscripten uses XHRs for asynchronously downloading binary data. - - LLVM backend - A (*Clang*) compiler backend that converts the :term:`LLVM` Intermediate Representation (IR) to code for a specified machine or other languages. In the case of Emscripten, the specified target is JavaScript. - - Minifying - `Minification `_ in JavaScript is the process of removing all unnecessary characters from source code without changing its functionality. At higher optimisation levels Emscripten uses the :term:`Closure Compiler` to minify Emscripten code. - - Relooping - Recreate high-level loop and ``if`` structures from the low-level labels and branches that appear in LLVM assembly (definition taken from `this paper `_). - - SDL - `Simple DirectMedia Layer `_ (SDL) is a cross-platform development library designed to provide low level access to audio, keyboard, mouse, joystick, and graphics hardware via OpenGL and Direct3D. - - Typed Arrays Mode 2 - *Typed Arrays Mode 2* is the name of the approach used for the current :ref:`emscripten-memory-model`. This is the only memory model supported by the (current) :ref:`Fastcomp ` compiler and is the default memory model for the :ref:`old compiler `. - - The original compiler supported a number of other memory models and compilation modes (see `Code Generation Modes `_) but *Typed Arrays Mode 2* proved to have, among other benefits, the greatest support for arbitrary code. - - - Load-store consistency - Load-Store Consistency (LSC), is the requirement that after a value with a specific type is written to a memory location, loads from that memory location will be of the same type. So if a variable contains a 32-bit floating point number, then both loads and stores to that variable will be of 32-bit floating point values, and not 16-bit unsigned integers or anything else. - - .. note:: This definition is taken from `Emscripten: An LLVM-to-JavaScript Compiler `_ (section 2.1.1). There is additional detail in that paper. + :sorted: + + XHR + Contraction of ``XMLHttpRequest``. Emscripten uses XHRs for asynchronously downloading binary data. + + LLVM backend + A (*Clang*) compiler backend that converts the :term:`LLVM` Intermediate Representation (IR) to code for a specified machine or other languages. In the case of Emscripten, the specified target is JavaScript. + + Minifying + `Minification `_ in JavaScript is the process of removing all unnecessary characters from source code without changing its functionality. At higher optimisation levels Emscripten uses the :term:`Closure Compiler` to minify Emscripten code. + + Relooping + Recreate high-level loop and ``if`` structures from the low-level labels and branches that appear in LLVM assembly (definition taken from `this paper `_). + + SDL + `Simple DirectMedia Layer `_ (SDL) is a cross-platform development library designed to provide low level access to audio, keyboard, mouse, joystick, and graphics hardware via OpenGL and Direct3D. + + Typed Arrays Mode 2 + *Typed Arrays Mode 2* is the name of the approach used for the current :ref:`emscripten-memory-model`. This is the only memory model supported by the (current) :ref:`Fastcomp ` compiler and is the default memory model for the :ref:`old compiler `. + + The original compiler supported a number of other memory models and compilation modes (see `Code Generation Modes `_) but *Typed Arrays Mode 2* proved to have, among other benefits, the greatest support for arbitrary code. + + + Load-store consistency + Load-Store Consistency (LSC), is the requirement that after a value with a specific type is written to a memory location, loads from that memory location will be of the same type. So if a variable contains a 32-bit floating point number, then both loads and stores to that variable will be of 32-bit floating point values, and not 16-bit unsigned integers or anything else. + + .. note:: This definition is taken from `Emscripten: An LLVM-to-JavaScript Compiler `_ (section 2.1.1). There is additional detail in that paper. Emscripten tools and dependencies ================================= .. glossary:: - :sorted: - - Clang - Clang is a compiler front end for C, C++, and other programming languages that uses :term:`LLVM` as its back end. - - emcc - The :ref:`emccdoc`. Emscripten's drop-in replacement for a compiler like *gcc*. - - Emscripten Command Prompt - The :ref:`emcmdprompt` is used to call Emscripten tools from the command line on Windows. - - Compiler Configuration File - The :ref:`Compiler Configuration File ` stores the :term:`active ` tools and SDKs as defined using :term:`emsdk activate `. - - LLVM - `LLVM `_ is a compiler infrastructure designed to allow optimization of programs written in arbitrary programming languages. - - Fastcomp - :ref:`Fastcomp ` is Emscripten's current compiler core. - - node.js - **Node.js** is a cross-platform runtime environment for server-side and networking applications written in JavaScript. Essentially it allows you to run JavaScript applications outside of a browser context. - - Python - Python is a scripting language used to write many of Emscripten's tools. The required version is listed in the :ref:`toolchain requirements `. - - Java - `Java `_ is a programming language and computing platform. It is used by Emscripten for the code that performs some advanced optimisations. The required version is listed in the :ref:`toolchain requirements `. - - JavaScript - `JavaScript `_ (`ECMAScript `_) is a programming language that is primarily used as part of a web browser, providing programmatic access to objects within a host environment. With :term:`node.js`, it is also being used in server-side network programming. - - The `asm.js `_ subset of JavaScript is Emscripten's target output language. - - Closure Compiler - The closure compiler is used to minify Emscripten-generated code at higher optimisations. - - Git - `Git `_ is a distributed revision control system. Emscripten is hosted on :term:`Github` and can be updated and modified using a git client. - - Github - `GitHub `_ is a :term:`Git` repository web-based hosting service that also offers project-based collaboration features including wikis, task management, and bug tracking. - - The Emscripten project is hosted on Github. - - lli - LLVM Interpreter - The `LLVM interpreter (LLI) `_ executes programs from :term:`LLVM` bitcode. This tool is not maintained and has odd errors and crashes. - - Emscripten provides an alternative tool, the :term:`LLVM Nativizer`. - - LLVM Nativizer - The LLVM Nativizer (`tools/nativize_llvm.py `_) compiles LLVM bitcode to a native executable. This links to the host libraries, so comparisons of output with Emscripten builds will not necessarily be identical. - - It performs a similar role to the :term:`LLVM Interpreter`. - - .. note:: Sometimes the output of the this tool will crash or fail. This tool is intended for developers fixing bugs in Emscripten. - - + :sorted: + + Clang + Clang is a compiler front end for C, C++, and other programming languages that uses :term:`LLVM` as its back end. + + emcc + The :ref:`emccdoc`. Emscripten's drop-in replacement for a compiler like *gcc*. + + Emscripten Command Prompt + The :ref:`emcmdprompt` is used to call Emscripten tools from the command line on Windows. + + Compiler Configuration File + The :ref:`Compiler Configuration File ` stores the :term:`active ` tools and SDKs as defined using :term:`emsdk activate `. + + LLVM + `LLVM `_ is a compiler infrastructure designed to allow optimization of programs written in arbitrary programming languages. + + Fastcomp + :ref:`Fastcomp ` is Emscripten's current compiler core. + + node.js + **Node.js** is a cross-platform runtime environment for server-side and networking applications written in JavaScript. Essentially it allows you to run JavaScript applications outside of a browser context. + + Python + Python is a scripting language used to write many of Emscripten's tools. The required version is listed in the :ref:`toolchain requirements `. + + Java + `Java `_ is a programming language and computing platform. It is used by Emscripten for the code that performs some advanced optimisations. The required version is listed in the :ref:`toolchain requirements `. + + JavaScript + `JavaScript `_ (`ECMAScript `_) is a programming language that is primarily used as part of a web browser, providing programmatic access to objects within a host environment. With :term:`node.js`, it is also being used in server-side network programming. + + The `asm.js `_ subset of JavaScript is Emscripten's target output language. + + Closure Compiler + The closure compiler is used to minify Emscripten-generated code at higher optimisations. + + Git + `Git `_ is a distributed revision control system. Emscripten is hosted on :term:`Github` and can be updated and modified using a git client. + + Github + `GitHub `_ is a :term:`Git` repository web-based hosting service that also offers project-based collaboration features including wikis, task management, and bug tracking. + + The Emscripten project is hosted on Github. + + lli + LLVM Interpreter + The `LLVM interpreter (LLI) `_ executes programs from :term:`LLVM` bitcode. This tool is not maintained and has odd errors and crashes. + + Emscripten provides an alternative tool, the :term:`LLVM Nativizer`. + + LLVM Nativizer + The LLVM Nativizer (`tools/nativize_llvm.py `_) compiles LLVM bitcode to a native executable. This links to the host libraries, so comparisons of output with Emscripten builds will not necessarily be identical. + + It performs a similar role to the :term:`LLVM Interpreter`. + + .. note:: Sometimes the output of the this tool will crash or fail. This tool is intended for developers fixing bugs in Emscripten. + + SDK Terms ========= @@ -105,33 +105,32 @@ The following terms are used when referring to the SDK and :ref:`emsdk`: .. glossary:: - emsdk - The :ref:`emsdk` is used to perform all SDK maintenance and can install, update, add, remove and :term:`activate ` :term:`SDKs ` and :term:`tools `. Most operations are of the form ``./emsdk command``. To access the *emsdk* script, launch the :term:`Emscripten Command Prompt`. - - Tool - The basic unit of software bundled in the :term:`SDK`. A Tool has a name and a version. For example, **clang-3.2-32bit** is a tool that contains the 32-bit version of the *Clang* v3.2 compiler. Other tools used by *Emscripten* include :term:`Java`, :term:`Git`, :term:`node.js`, etc. - - SDK - A set of :term:`tools `. For example, **sdk-1.5.6-32bit** is an SDK consisting of the tools: clang-3.2-32bit, node-0.10.17-32bit, python-2.7.5.1-32bit and emscripten-1.5.6. - - There are a number of different Emscripten SDK packages, which are provided as :term:`Portable Emscripten SDK` installations. These can be downloaded from :ref:`here `. - - Active Tool/SDK - The :term:`emsdk` can store multiple versions of :term:`tools ` and :term:`SDKs `. The active tools/SDK is the set of tools that are used by default on the *Emscripten Command Prompt*. This compiler configuration is stored in a user-specific persistent file (**~/.emscripten**) and can be changed using *emsdk*. - - emsdk root directory - The :term:`emsdk` can manage any number of :term:`tools ` and :term:`SDKs `, and these are stored in :term:`subdirectories ` of the *emsdk root directory*. The **emsdk root** is the directory specified when you first installed an SDK. - - SDK root directory - The :term:`emsdk` can store any number of tools and SDKs. The *SDK root directory* is the directory used to store a particular :term:`SDK`. It is located as follows, with respect to the :term:`emsdk root directory`: **\\emscripten\\\\** - - - + emsdk + The :ref:`emsdk` is used to perform all SDK maintenance and can install, update, add, remove and :term:`activate ` :term:`SDKs ` and :term:`tools `. Most operations are of the form ``./emsdk command``. To access the *emsdk* script, launch the :term:`Emscripten Command Prompt`. + + Tool + The basic unit of software bundled in the :term:`SDK`. A Tool has a name and a version. For example, **clang-3.2-32bit** is a tool that contains the 32-bit version of the *Clang* v3.2 compiler. Other tools used by *Emscripten* include :term:`Java`, :term:`Git`, :term:`node.js`, etc. + + SDK + A set of :term:`tools `. For example, **sdk-1.5.6-32bit** is an SDK consisting of the tools: clang-3.2-32bit, node-0.10.17-32bit, python-2.7.5.1-32bit and emscripten-1.5.6. + + There are a number of different Emscripten SDK packages. These can be downloaded from :ref:`here `. + + Active Tool/SDK + The :term:`emsdk` can store multiple versions of :term:`tools ` and :term:`SDKs `. The active tools/SDK is the set of tools that are used by default on the *Emscripten Command Prompt*. This compiler configuration is stored in a user-specific persistent file (**~/.emscripten**) and can be changed using *emsdk*. + + emsdk root directory + The :term:`emsdk` can manage any number of :term:`tools ` and :term:`SDKs `, and these are stored in :term:`subdirectories ` of the *emsdk root directory*. The **emsdk root** is the directory specified when you first installed an SDK. + + SDK root directory + The :term:`emsdk` can store any number of tools and SDKs. The *SDK root directory* is the directory used to store a particular :term:`SDK`. It is located as follows, with respect to the :term:`emsdk root directory`: **\\emscripten\\\\** + + Site / Sphinx -============== +============== .. glossary:: - :sorted: + :sorted: - reStructured text - Markup language used to define content on this site. See the `reStructured text primer `_. \ No newline at end of file + reStructured text + Markup language used to define content on this site. See the `reStructured text primer `_. diff --git a/site/source/index.rst b/site/source/index.rst index cc06d39e55c23..1bd467060bdc9 100644 --- a/site/source/index.rst +++ b/site/source/index.rst @@ -4,32 +4,29 @@ .. only:: sdkbuild - .. admonition:: Welcome to Emscripten SDK |release| + .. admonition:: Welcome to Emscripten SDK |release| - This documentation contains everything you need to :ref:`start developing ` with the Emscripten SDK. + This documentation contains everything you need to :ref:`start developing ` with the Emscripten SDK. .. raw:: html :file: home_page_layout.html ----- - - - .. toctree:: - :hidden: - - docs/introducing_emscripten/index - docs/getting_started/index - docs/compiling/index - docs/porting/index - docs/api_reference/index - docs/tools_reference/index - docs/optimizing/Optimizing-Code - docs/optimizing/Optimizing-WebGL - docs/debugging/CyberDWARF - docs/building_from_source/index - docs/contributing/index - docs/optimizing/Profiling-Toolchain - docs/site/about + :hidden: + + docs/introducing_emscripten/index + docs/getting_started/index + docs/compiling/index + docs/porting/index + docs/api_reference/index + docs/tools_reference/index + docs/optimizing/Optimizing-Code + docs/optimizing/Optimizing-WebGL + docs/debugging/CyberDWARF + docs/building_from_source/index + docs/contributing/index + docs/optimizing/Profiling-Toolchain + docs/site/about