repo_id
stringlengths
21
96
file_path
stringlengths
31
155
content
stringlengths
1
92.9M
__index_level_0__
int64
0
0
rapidsai_public_repos/node/modules/cugraph/test
rapidsai_public_repos/node/modules/cugraph/test/community/spectral-clustering-tests.ts
// Copyright (c) 2022, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {setDefaultAllocator} from '@rapidsai/cuda'; import {DataFrame, Series} from '@rapidsai/cudf'; import {DedupedEdgesGraph} from '@rapidsai/cugraph'; import {CudaMemoryResource, DeviceBuffer} from '@rapidsai/rmm'; const mr = new CudaMemoryResource(); setDefaultAllocator((byteLength: number) => new DeviceBuffer(byteLength, mr)); test.each([ {type: 'balanced_cut', num_clusters: 2, expected: [1, 0, 0]}, {type: 'modularity_maximization', num_clusters: 2, expected: [0, 1, 0]}, ])(`DedupedEdgesGraph.computeClusters (%j)`, ({type, num_clusters, expected}: any) => { const src = Series.new(new Int32Array([0, 0, 0, 1])); const dst = Series.new(new Int32Array([1, 1, 1, 2])); const graph = DedupedEdgesGraph.fromEdgeList(src, dst); expect(graph.computeClusters({type, num_clusters}).toString()) .toEqual(new DataFrame({ vertex: Series.new(new Int32Array([0, 1, 2])), cluster: Series.new(new Int32Array(expected)), }).toString()); }); test.each([ {type: 'edge_cut', clusterType: 'balanced_cut', num_clusters: 2, expected: 1.5}, {type: 'ratio_cut', clusterType: 'balanced_cut', num_clusters: 2, expected: 3}, {type: 'modularity', clusterType: 'balanced_cut', num_clusters: 2, expected: -.375}, {type: 'edge_cut', clusterType: 'modularity_maximization', num_clusters: 2, expected: 2}, {type: 'ratio_cut', clusterType: 'modularity_maximization', num_clusters: 2, expected: 2.5}, {type: 'modularity', clusterType: 'modularity_maximization', num_clusters: 2, expected: -.625}, ])(`DedupedEdgesGraph.analyzeClustering (%j)`, ({type, clusterType, num_clusters, expected}: any) => { const src = Series.new(new Int32Array([0, 0, 0, 1])); const dst = Series.new(new Int32Array([1, 1, 1, 2])); const graph = DedupedEdgesGraph.fromEdgeList(src, dst); const cluster = graph.computeClusters({type: clusterType, num_clusters}).get('cluster'); expect(graph.analyzeClustering({type, num_clusters, cluster})).toEqual(expected); });
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/glfw/package.json
{ "name": "@rapidsai/glfw", "version": "22.12.2", "description": "Platform-native (and headless) GPU-accelerated OpenGL windows", "license": "Apache-2.0", "main": "index.js", "types": "build/js", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "homepage": "https://github.com/rapidsai/node/tree/main/modules/glfw#readme", "bugs": { "url": "https://github.com/rapidsai/node/issues" }, "repository": { "type": "git", "url": "git+https://github.com/rapidsai/node.git" }, "scripts": { "clean": "rimraf build doc compile_commands.json", "doc": "rimraf doc && typedoc --options typedoc.js", "test": "node -r dotenv/config node_modules/.bin/jest -c jest.config.js", "build": "yarn tsc:build && yarn cpp:build", "build:debug": "yarn tsc:build && yarn cpp:build:debug", "compile": "yarn tsc:build && yarn cpp:compile", "compile:debug": "yarn tsc:build && yarn cpp:compile:debug", "rebuild": "yarn tsc:build && yarn cpp:rebuild", "rebuild:debug": "yarn tsc:build && yarn cpp:rebuild:debug", "cpp:clean": "npx cmake-js clean -O build/Release", "cpp:clean:debug": "npx cmake-js clean -O build/Debug", "cpp:build": "npx cmake-js build -g -O build/Release", "cpp:build:debug": "npx cmake-js build -g -D -O build/Debug", "cpp:compile": "npx cmake-js compile -g -O build/Release", "postcpp:compile": "npx rapidsai-merge-compile-commands", "cpp:compile:debug": "npx cmake-js compile -g -D -O build/Debug", "postcpp:compile:debug": "npx rapidsai-merge-compile-commands", "cpp:configure": "npx cmake-js configure -g -O build/Release", "postcpp:configure": "npx rapidsai-merge-compile-commands", "cpp:configure:debug": "npx cmake-js configure -g -D -O build/Debug", "postcpp:configure:debug": "npx rapidsai-merge-compile-commands", "cpp:rebuild": "npx cmake-js rebuild -g -O build/Release", "postcpp:rebuild": "npx rapidsai-merge-compile-commands", "cpp:rebuild:debug": "npx cmake-js rebuild -g -D -O build/Debug", "postcpp:rebuild:debug": "npx rapidsai-merge-compile-commands", "cpp:reconfigure": "npx cmake-js reconfigure -g -O build/Release", "postcpp:reconfigure": "npx rapidsai-merge-compile-commands", "cpp:reconfigure:debug": "npx cmake-js reconfigure -g -D -O build/Debug", "postcpp:reconfigure:debug": "npx rapidsai-merge-compile-commands", "tsc:clean": "rimraf build/js", "tsc:build": "yarn tsc:clean && tsc -p ./tsconfig.json", "tsc:watch": "yarn tsc:clean && tsc -p ./tsconfig.json -w" }, "dependencies": { "@rapidsai/core": "~22.12.2", "@rapidsai/webgl": "~22.12.2" }, "files": [ "LICENSE", "README.md", "index.js", "package.json", "CMakeLists.txt", "build/js", "build/Release/*.so*", "build/Release/*.node" ] }
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/glfw/index.js
// Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = require('./build/js/index');
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/glfw/jest.config.js
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. try { require('dotenv').config(); } catch (e) {} module.exports = { 'verbose': true, 'testEnvironment': 'node', 'maxWorkers': process.env.PARALLEL_LEVEL || 1, 'globals': {'ts-jest': {'diagnostics': false, 'tsconfig': 'test/tsconfig.json'}}, 'rootDir': './', 'roots': ['<rootDir>/test/'], 'moduleFileExtensions': ['js', 'ts', 'tsx'], 'coverageReporters': ['lcov'], 'coveragePathIgnorePatterns': ['test\\/.*\\.(ts|tsx|js)$', '/node_modules/'], 'transform': {'^.+\\.jsx?$': 'ts-jest', '^.+\\.tsx?$': 'ts-jest'}, 'transformIgnorePatterns': [ '/build/(js|Debug|Release)/*$', '/node_modules/(?!@tensorflow)/*$', '/node_modules/(?!web-stream-tools).+\\.js$' ], 'testRegex': '(.*(-|\\.)(test|spec)s?)\\.(ts|tsx|js)$', 'preset': 'ts-jest', 'testMatch': null, 'moduleNameMapper': { '^@rapidsai\/glfw(.*)': '<rootDir>/src/$1', '^\.\.\/(Debug|Release)\/(rapidsai_glfw.node)$': '<rootDir>/build/$1/$2', } };
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/glfw/CMakeLists.txt
#============================================================================= # Copyright (c) 2020-2021, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #============================================================================= cmake_minimum_required(VERSION 3.24.1 FATAL_ERROR) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) unset(CMAKE_LIBRARY_OUTPUT_DIRECTORY) unset(CMAKE_LIBRARY_OUTPUT_DIRECTORY CACHE) option(NODE_RAPIDS_USE_SCCACHE "Enable caching compilation results with sccache" ON) ################################################################################################### # - cmake modules --------------------------------------------------------------------------------- execute_process(COMMAND node -p "require('@rapidsai/core').cmake_modules_path" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" OUTPUT_VARIABLE NODE_RAPIDS_CMAKE_MODULES_PATH OUTPUT_STRIP_TRAILING_WHITESPACE) include("${NODE_RAPIDS_CMAKE_MODULES_PATH}/cmake_policies.cmake") project(rapidsai_glfw VERSION $ENV{npm_package_version} LANGUAGES C CXX) execute_process(COMMAND node -p "require('path').dirname(require.resolve('@rapidsai/core'))" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" OUTPUT_VARIABLE NODE_RAPIDS_CORE_MODULE_PATH OUTPUT_STRIP_TRAILING_WHITESPACE) include("${NODE_RAPIDS_CMAKE_MODULES_PATH}/ConfigureCXX.cmake") include("${NODE_RAPIDS_CMAKE_MODULES_PATH}/ConfigureNapi.cmake") include("${NODE_RAPIDS_CMAKE_MODULES_PATH}/ConfigureOpenGL.cmake") include("${NODE_RAPIDS_CMAKE_MODULES_PATH}/ConfigureOpenGLFW.cmake") include("${NODE_RAPIDS_CMAKE_MODULES_PATH}/install_utils.cmake") function(_find_glfw VARIANT USE_WAYLAND USE_EGLHEADLESS) find_and_configure_glfw( VARIANT ${VARIANT} VERSION 3.3.2 # version GIT_REPO https://github.com/trxcllnt/glfw.git # git repo GIT_TAG fea/headless-egl-with-fallback # git tag USE_SHARED_LIBS OFF # build + dynamically link libglfw.so USE_WAYLAND ${USE_WAYLAND} USE_EGLHEADLESS ${USE_EGLHEADLESS} EXPORT_SET rapidsai_glfw-exports ) endfunction() _find_glfw(x11 OFF OFF) # _find_glfw(wayland ON OFF) _find_glfw(eglheadless OFF ON) ################################################################################################### # - rapidsai_glfw target -------------------------------------------------------------------------- file(GLOB_RECURSE NODE_GLFW_SRC_FILES "src/*.cpp") function(make_rapidsai_glfw_target VARIANT DEFINES) add_library(${PROJECT_NAME}_${VARIANT} SHARED ${NODE_GLFW_SRC_FILES} ${CMAKE_JS_SRC}) set_target_properties(${PROJECT_NAME}_${VARIANT} PROPERTIES PREFIX "" SUFFIX ".node" BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN" CXX_STANDARD 17 CXX_STANDARD_REQUIRED ON CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON NO_SYSTEM_FROM_IMPORTED ON POSITION_INDEPENDENT_CODE ON INTERFACE_POSITION_INDEPENDENT_CODE ON ) set(${PROJECT_NAME}_${VARIANT}_C_FLAGS "") set(${PROJECT_NAME}_${VARIANT}_CXX_FLAGS "") list(APPEND ${PROJECT_NAME}_${VARIANT}_C_FLAGS ${DEFINES}) list(APPEND ${PROJECT_NAME}_${VARIANT}_CXX_FLAGS ${DEFINES}) list(APPEND ${PROJECT_NAME}_${VARIANT}_C_FLAGS ${NODE_RAPIDS_CMAKE_C_FLAGS}) list(APPEND ${PROJECT_NAME}_${VARIANT}_CXX_FLAGS ${NODE_RAPIDS_CMAKE_CXX_FLAGS}) target_compile_options(${PROJECT_NAME}_${VARIANT} PRIVATE "$<BUILD_INTERFACE:$<$<COMPILE_LANGUAGE:C>:${${PROJECT_NAME}_${VARIANT}_C_FLAGS}>>" "$<BUILD_INTERFACE:$<$<COMPILE_LANGUAGE:CXX>:${${PROJECT_NAME}_${VARIANT}_CXX_FLAGS}>>" ) target_include_directories(${PROJECT_NAME}_${VARIANT} PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src>" "$<BUILD_INTERFACE:${RAPIDS_CORE_INCLUDE_DIR}>" "$<BUILD_INTERFACE:${NAPI_INCLUDE_DIRS}>" ) target_link_libraries(${PROJECT_NAME}_${VARIANT} PUBLIC glfw::${VARIANT} OpenGL::EGL OpenGL::OpenGL "${NODE_RAPIDS_CORE_MODULE_PATH}/build/${CMAKE_BUILD_TYPE}/rapidsai_core.node") endfunction() make_rapidsai_glfw_target(x11 "-DGLFW_EXPOSE_NATIVE_X11") # make_rapidsai_glfw_target(wayland "-DGLFW_EXPOSE_NATIVE_WAYLAND") make_rapidsai_glfw_target(eglheadless "-DGLFW_EXPOSE_NATIVE_EGL_EXT -D_GLFW_EGL_LIBRARY=libEGL_nvidia.so.0") generate_install_rules( NAME ${PROJECT_NAME} GLOBAL_TARGETS ${PROJECT_NAME}_x11 ${PROJECT_NAME}_eglheadless ) # Create a symlink to compile_commands.json for the llvm-vs-code-extensions.vscode-clangd plugin execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink ${CMAKE_CURRENT_BINARY_DIR}/compile_commands.json ${CMAKE_CURRENT_SOURCE_DIR}/compile_commands.json)
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/glfw/README.md
### node-glfw (`npm install @rapidsai/glfw`) A node native addon that provides bindings to the platform window manager via GLFW (https://www.glfw.org/). GLFW provides cross-platform multi-display support for creating native windows that host an OpenGL or Vulkan rendering context. These bindings provide a stripped-down version of the DOM's "Window", "Document", and "Canvas" APIs. #### dependencies: - `@rapidsai/webgl` #### Window management: - [Window](https://www.glfw.org/docs/latest/group__window.html) wraps and manages a GLFW `Window`. - [Document](https://developer.mozilla.org/en-US/docs/Web/API/Document) implements a few DOM `Document` APIs that frameworks expect. - [Canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) implements a DOM `Canvas` APIs that provides a 3D rendering context. #### GLFW APIs: createWindow, showWindow, hideWindow, focusWindow, iconifyWindow, restoreWindow, maximizeWindow, requestWindowAttention, reparentWindow, destroyWindow, getWindowFrameSize, getWindowContentScale, setWindowSizeLimits, getPlatformWindowPointer, getPlatformContextPointer, get/setWindowIcon, get/setWindowSize, get/setWindowTitle, get/setWindowMonitor, get/setWindowOpacity, get/setWindowPosition, get/setWindowAttribute, get/setWindowAspectRatio, get/setWindowShouldClose
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/glfw/tsconfig.json
{ "include": ["src"], "exclude": ["node_modules"], "compilerOptions": { "baseUrl": "./", "paths": { "@rapidsai/glfw": ["src/index"], "@rapidsai/glfw/*": ["src/*"] }, "target": "ESNEXT", "module": "commonjs", "outDir": "./build/js", /* Decorators */ "experimentalDecorators": true, /* Basic stuff */ "moduleResolution": "node", "skipLibCheck": true, "skipDefaultLibCheck": true, "lib": ["dom", "esnext", "esnext.asynciterable"], /* Control what is emitted */ "declaration": true, "declarationMap": true, "noEmitOnError": true, "removeComments": false, "downlevelIteration": true, /* Create inline sourcemaps with sources */ "sourceMap": false, "inlineSources": true, "inlineSourceMap": true, /* The most restrictive settings possible */ "strict": true, "importHelpers": true, "noEmitHelpers": true, "noImplicitAny": true, "noUnusedLocals": true, "noImplicitReturns": true, "allowUnusedLabels": false, "noUnusedParameters": true, "allowUnreachableCode": false, "noFallthroughCasesInSwitch": true, "forceConsistentCasingInFileNames": true } }
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/glfw/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2019 NVIDIA Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/glfw/typedoc.js
module.exports = { entryPoints: ['src/index.ts'], out: 'doc', name: '@rapidsai/glfw', tsconfig: 'tsconfig.json', excludePrivate: true, excludeProtected: true, excludeExternals: true, };
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/.vscode/launch.json
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "compounds": [ { "name": "Debug Tests (TS and C++)", "configurations": [ "Debug Tests (launch gdb)", // "Debug Tests (launch lldb)", "Debug Tests (attach node)", ] } ], "configurations": [ { "name": "Debug Tests (TS only)", "type": "node", "request": "launch", "cwd": "${workspaceFolder}", "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", "program": "${workspaceFolder}/node_modules/.bin/jest", "skipFiles": [ "<node_internals>/**", "${workspaceFolder}/node_modules/**" ], "env": { "NODE_NO_WARNINGS": "1", "NODE_ENV": "production", "READABLE_STREAM": "disable", }, "args": [ "--verbose", "--runInBand", "-c", "jest.config.js", "${input:TEST_FILE}" ] }, // { // "name": "Debug Tests (launch lldb)", // // hide the individual configurations from the debug dropdown list // "presentation": { "hidden": true }, // "type": "lldb", // "request": "launch", // "stdio": null, // "cwd": "${workspaceFolder}", // "preLaunchTask": "cpp:ensure:debug:build", // "env": { // "NODE_DEBUG": "1", // "NODE_NO_WARNINGS": "1", // "NODE_ENV": "production", // "READABLE_STREAM": "disable", // }, // "stopOnEntry": false, // "terminal": "console", // "program": "${input:NODE_BINARY}", // "initCommands": [ // "settings set target.disable-aslr false", // ], // "sourceLanguages": ["cpp", "cuda", "javascript"], // "args": [ // "--inspect=9229", // "--expose-internals", // "${workspaceFolder}/node_modules/.bin/jest", // "--verbose", // "--runInBand", // "-c", // "jest.config.js", // "${input:TEST_FILE}" // ], // }, { "name": "Debug Tests (launch gdb)", // hide the individual configurations from the debug dropdown list "presentation": { "hidden": true }, "type": "cppdbg", "request": "launch", "stopAtEntry": false, "externalConsole": false, "cwd": "${workspaceFolder}", "envFile": "${workspaceFolder}/.env", "MIMode": "gdb", "miDebuggerPath": "/usr/bin/gdb", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true } ], "program": "${input:NODE_BINARY}", "environment": [ { "name": "NODE_DEBUG", "value": "1" }, { "name": "NODE_NO_WARNINGS", "value": "1" }, { "name": "NODE_ENV", "value": "production" }, { "name": "READABLE_STREAM", "value": "disable" }, ], "args": [ "--inspect=9229", "--expose-internals", "${workspaceFolder}/node_modules/.bin/jest", "--verbose", "--runInBand", "-c", "jest.config.js", "${input:TEST_FILE}" ], }, { "name": "Debug Tests (attach node)", "type": "node", "request": "attach", // hide the individual configurations from the debug dropdown list "presentation": { "hidden": true }, "port": 9229, "timeout": 60000, "cwd": "${workspaceFolder}", "skipFiles": [ "<node_internals>/**", "${workspaceFolder}/node_modules/**" ], }, ], "inputs": [ { "type": "command", "id": "NODE_BINARY", "command": "shellCommand.execute", "args": { "description": "path to node", "command": "which node", "useFirstResult": true, } }, { "type": "command", "id": "TEST_FILE", "command": "shellCommand.execute", "args": { "cwd": "${workspaceFolder}/modules/glfw", "description": "Select a file to debug", "command": "./node_modules/.bin/jest --listTests | sed -r \"s@$PWD/test/@@g\"", } }, ], }
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/.vscode/tasks.json
{ "version": "2.0.0", "tasks": [ { "type": "shell", "label": "Rebuild node_glfw TS and C++ (slow)", "group": { "kind": "build", "isDefault": true, }, "command": "if [[ \"${input:CMAKE_BUILD_TYPE}\" == \"Release\" ]]; then yarn rebuild; else yarn rebuild:debug; fi", "problemMatcher": [ "$tsc", { "owner": "cuda", "fileLocation": ["relative", "${workspaceFolder}/build/${input:CMAKE_BUILD_TYPE}"], "pattern": { "file": 1, "line": 2, "severity": 3, "message": 4, "regexp": "^(.*)\\((\\d+)\\):\\s+(error|warning|note|info):\\s+(.*)$" } }, { "owner": "cpp", "fileLocation": ["relative", "${workspaceFolder}/build/${input:CMAKE_BUILD_TYPE}"], "pattern": { "file": 1, "line": 2, "severity": 4, "message": 5, "regexp": "^(.*):(\\d+):(\\d+):\\s+(error|warning|note|info):\\s+(.*)$" } }, ], }, { "type": "npm", "group": "build", "label": "Recompile node_glfw TS (fast)", "script": "tsc:build", "detail": "yarn tsc:build", "problemMatcher": ["$tsc"], }, { "type": "shell", "group": "build", "label": "Recompile node_glfw C++ (fast)", "command": "ninja -C ${workspaceFolder}/build/${input:CMAKE_BUILD_TYPE}", "problemMatcher": [ { "owner": "cuda", "fileLocation": ["relative", "${workspaceFolder}/build/${input:CMAKE_BUILD_TYPE}"], "pattern": { "file": 1, "line": 2, "severity": 3, "message": 4, "regexp": "^(.*)\\((\\d+)\\):\\s+(error|warning|note|info):\\s+(.*)$" } }, { "owner": "cpp", "fileLocation": ["relative", "${workspaceFolder}/build/${input:CMAKE_BUILD_TYPE}"], "pattern": { "file": 1, "line": 2, "severity": 4, "message": 5, "regexp": "^(.*):(\\d+):(\\d+):\\s+(error|warning|note|info):\\s+(.*)$" } }, ], }, ], "inputs": [ { "type": "pickString", "default": "Release", "id": "CMAKE_BUILD_TYPE", "options": ["Release", "Debug"], "description": "C++ Build Type", } ] }
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/src/index.ts
// Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. export { GLFW, glfw, GLFWClientAPI, GLFWContextCreationAPI, GLFWInputMode, GLFWKey, GLFWModifierKey, GLFWmonitor, GLFWMouseButton, GLFWOpenGLProfile, GLFWStandardCursor, GLFWWindowAttribute, isHeadless } from './glfw'; export {Monitor} from './monitor';
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/src/monitor.ts
// Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {EventEmitter} from 'events'; import {glfw, GLFWmonitor} from './glfw'; export class Monitor extends EventEmitter { constructor(id: GLFWmonitor, connected = true) { super(); this._id = id; this._connected = connected; this._name = glfw.getMonitorName(id); if (connected) { ({x: this._x, y: this._y, width: this._width, height: this._height} = glfw.getMonitorWorkarea(id)); ({xscale: this._xscale, yscale: this._yscale} = glfw.getMonitorContentScale(id)); ({width: this._widthMM, height: this._heightMM} = glfw.getMonitorPhysicalSize(id)); } } private _x = 0; public get x() { return this._x; } private _y = 0; public get y() { return this._y; } private _id: GLFWmonitor = 0; public get id() { return this._id; } private _name = ''; public get name() { return this._name; } private _xscale = 0; public get xscale() { return this._xscale; } private _yscale = 0; public get yscale() { return this._yscale; } private _width = 800; public get width() { return this._width; } private _height = 600; public get height() { return this._height; } private _widthMM = 800; public get widthMM() { return this._widthMM; } private _heightMM = 600; public get heightMM() { return this._heightMM; } private _connected = true; public get connected() { return this._connected; } public[Symbol.toStringTag]: string; public inspect() { return this.toString(); } public[Symbol.for('nodejs.util.inspect.custom')]() { return this.toString(); } public toString() { return `${this[Symbol.toStringTag]} ${JSON.stringify({ id: this.id, x: this.x, y: this.y, width: this.width, height: this.height, xscale: this.xscale, yscale: this.yscale, widthMM: this.widthMM, heightMM: this.heightMM, })}`; } } Monitor.prototype[Symbol.toStringTag] = 'Monitor';
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/src/callbacks.cpp
// Copyright (c) 2020-2023, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "glfw.hpp" #include "macros.hpp" #include <nv_node/objectwrap.hpp> #include <napi.h> #include <map> #include <vector> namespace Napi { template <> inline Value Value::From(napi_env env, GLFWmonitor* const& monitor) { return Napi::Number::New(env, reinterpret_cast<uintptr_t>(monitor)); } template <> inline Value Value::From(napi_env env, GLFWwindow* const& window) { return Napi::Number::New(env, reinterpret_cast<uintptr_t>(window)); } template <> inline Value Value::From(napi_env env, std::vector<std::string> const& vec) { uint32_t idx = 0; auto arr = Napi::Array::New(env, vec.size()); for (auto const& val : vec) { arr[idx++] = val; } return arr; } } // namespace Napi namespace nv { namespace { Napi::FunctionReference error_cb; Napi::FunctionReference joystick_cb; Napi::FunctionReference monitor_cb; std::map<GLFWwindow*, Napi::FunctionReference> pos_cbs; std::map<GLFWwindow*, Napi::FunctionReference> size_cbs; std::map<GLFWwindow*, Napi::FunctionReference> close_cbs; std::map<GLFWwindow*, Napi::FunctionReference> refresh_cbs; std::map<GLFWwindow*, Napi::FunctionReference> focus_cbs; std::map<GLFWwindow*, Napi::FunctionReference> iconify_cbs; std::map<GLFWwindow*, Napi::FunctionReference> maximize_cbs; std::map<GLFWwindow*, Napi::FunctionReference> scale_cbs; std::map<GLFWwindow*, Napi::FunctionReference> fb_resize_cbs; std::map<GLFWwindow*, Napi::FunctionReference> key_cbs; std::map<GLFWwindow*, Napi::FunctionReference> char_cbs; std::map<GLFWwindow*, Napi::FunctionReference> charmods_cbs; std::map<GLFWwindow*, Napi::FunctionReference> mousebutton_cbs; std::map<GLFWwindow*, Napi::FunctionReference> cursorpos_cbs; std::map<GLFWwindow*, Napi::FunctionReference> cursorenter_cbs; std::map<GLFWwindow*, Napi::FunctionReference> scroll_cbs; std::map<GLFWwindow*, Napi::FunctionReference> drop_cbs; template <typename... Args> std::vector<napi_value> to_napi(Napi::Env env, Args&&... args) { std::vector<napi_value> napi_values; napi_values.reserve(sizeof...(Args)); detail::tuple::for_each( std::make_tuple<Args...>(std::forward<Args>(args)...), [&](auto const& x) mutable { napi_values.push_back(Napi::Value::From(env, x)); }); return napi_values; } void GLFWerror_cb(int32_t err, const char* msg) { auto& cb = error_cb; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), err, std::string{msg == nullptr ? msg : ""}); cb.MakeCallback(cb.Env().Global(), args); } } void GLFWmonitor_cb(GLFWmonitor* monitor, int32_t event) { auto& cb = monitor_cb; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), monitor, event); cb.MakeCallback(cb.Env().Global(), args); } } void GLFWjoystick_cb(int32_t joystick, int32_t event) { auto& cb = joystick_cb; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), joystick, event); cb.MakeCallback(cb.Env().Global(), args); } } void GLFWwindowpos_cb(GLFWwindow* window, int32_t x, int32_t y) { if (pos_cbs.find(window) != pos_cbs.end()) { auto& cb = pos_cbs[window]; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), window, x, y); cb.MakeCallback(cb.Env().Global(), args); } } } void GLFWwindowsize_cb(GLFWwindow* window, int32_t width, int32_t height) { if (size_cbs.find(window) != size_cbs.end()) { auto& cb = size_cbs[window]; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), window, width, height); cb.MakeCallback(cb.Env().Global(), args); } } } void GLFWwindowclose_cb(GLFWwindow* window) { if (close_cbs.find(window) != close_cbs.end()) { auto& cb = close_cbs[window]; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), window); cb.MakeCallback(cb.Env().Global(), args); } } } void GLFWwindowrefresh_cb(GLFWwindow* window) { if (refresh_cbs.find(window) != refresh_cbs.end()) { auto& cb = refresh_cbs[window]; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), window); cb.MakeCallback(cb.Env().Global(), args); } } } void GLFWwindowfocus_cb(GLFWwindow* window, int32_t focused) { if (focus_cbs.find(window) != focus_cbs.end()) { auto& cb = focus_cbs[window]; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), window, focused); cb.MakeCallback(cb.Env().Global(), args); } } } void GLFWwindowiconify_cb(GLFWwindow* window, int32_t iconified) { if (iconify_cbs.find(window) != iconify_cbs.end()) { auto& cb = iconify_cbs[window]; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), window, iconified); cb.MakeCallback(cb.Env().Global(), args); } } } void GLFWwindowmaximize_cb(GLFWwindow* window, int32_t maximized) { if (maximize_cbs.find(window) != maximize_cbs.end()) { auto& cb = maximize_cbs[window]; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), window, maximized); cb.MakeCallback(cb.Env().Global(), args); } } } void GLFWframebuffersize_cb(GLFWwindow* window, int32_t width, int32_t height) { if (fb_resize_cbs.find(window) != fb_resize_cbs.end()) { auto& cb = fb_resize_cbs[window]; auto args = to_napi(cb.Env(), window, width, height); cb.MakeCallback(cb.Env().Global(), args); } } void GLFWwindowcontentscale_cb(GLFWwindow* window, float xscale, float yscale) { if (scale_cbs.find(window) != scale_cbs.end()) { auto& cb = scale_cbs[window]; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), window, xscale, yscale); cb.MakeCallback(cb.Env().Global(), args); } } } void GLFWkey_cb(GLFWwindow* window, int32_t key, int32_t scancode, int32_t action, int32_t mods) { if (key_cbs.find(window) != key_cbs.end()) { auto& cb = key_cbs[window]; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), window, key, scancode, action, mods); cb.MakeCallback(cb.Env().Global(), args); } } } void GLFWchar_cb(GLFWwindow* window, uint32_t codepoint) { if (char_cbs.find(window) != char_cbs.end()) { auto& cb = char_cbs[window]; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), window, codepoint); cb.MakeCallback(cb.Env().Global(), args); } } } void GLFWcharmods_cb(GLFWwindow* window, uint32_t codepoint, int32_t mods) { if (charmods_cbs.find(window) != charmods_cbs.end()) { auto& cb = charmods_cbs[window]; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), window, codepoint, mods); cb.MakeCallback(cb.Env().Global(), args); } } } void GLFWmousebutton_cb(GLFWwindow* window, int32_t button, int32_t action, int32_t mods) { if (mousebutton_cbs.find(window) != mousebutton_cbs.end()) { auto& cb = mousebutton_cbs[window]; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), window, button, action, mods); cb.MakeCallback(cb.Env().Global(), args); } } } void GLFWcursorpos_cb(GLFWwindow* window, double x, double y) { if (cursorpos_cbs.find(window) != cursorpos_cbs.end()) { auto& cb = cursorpos_cbs[window]; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), window, x, y); cb.MakeCallback(cb.Env().Global(), args); } } } void GLFWcursorenter_cb(GLFWwindow* window, int32_t entered) { if (cursorenter_cbs.find(window) != cursorenter_cbs.end()) { auto& cb = cursorenter_cbs[window]; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), window, entered); cb.MakeCallback(cb.Env().Global(), args); } } } void GLFWscroll_cb(GLFWwindow* window, double x, double y) { if (scroll_cbs.find(window) != scroll_cbs.end()) { auto& cb = scroll_cbs[window]; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), window, x, y); cb.MakeCallback(cb.Env().Global(), args); } } } void GLFWdrop_cb(GLFWwindow* window, int count, const char** paths) { if (drop_cbs.find(window) != drop_cbs.end()) { auto& cb = drop_cbs[window]; if (!cb.IsEmpty()) { // auto args = to_napi(cb.Env(), window, std::vector<std::string>{paths, paths + count}); cb.MakeCallback(cb.Env().Global(), args); } } } }; // namespace // GLFWAPI GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun callback); void glfwSetErrorCallback(Napi::CallbackInfo const& info) { auto env = info.Env(); if (info[0].IsFunction()) { error_cb = Napi::Persistent(info[0].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetErrorCallback(GLFWerror_cb)); } else { error_cb.Reset(); GLFW_TRY(env, GLFWAPI::glfwSetErrorCallback(NULL)); } } // GLFWAPI GLFWmonitorfun glfwSetMonitorCallback(GLFWmonitorfun callback); void glfwSetMonitorCallback(Napi::CallbackInfo const& info) { auto env = info.Env(); if (info[0].IsFunction()) { monitor_cb = Napi::Persistent(info[0].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetMonitorCallback(GLFWmonitor_cb)); } else { monitor_cb.Reset(); GLFW_TRY(env, GLFWAPI::glfwSetMonitorCallback(NULL)); } } // GLFWAPI GLFWjoystickfun glfwSetJoystickCallback(GLFWjoystickfun callback); void glfwSetJoystickCallback(Napi::CallbackInfo const& info) { auto env = info.Env(); if (info[0].IsFunction()) { joystick_cb = Napi::Persistent(info[0].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetJoystickCallback(GLFWjoystick_cb)); } else { joystick_cb.Reset(); GLFW_TRY(env, GLFWAPI::glfwSetJoystickCallback(NULL)); } } // GLFWAPI GLFWwindowposfun glfwSetWindowPosCallback(GLFWwindow* window, GLFWwindowposfun callback); void glfwSetWindowPosCallback(Napi::CallbackInfo const& info) { auto window = reinterpret_cast<GLFWwindow*>(info[0].ToNumber().Int64Value()); if (window != nullptr) { // auto env = info.Env(); if (info[1].IsFunction()) { pos_cbs[window] = Napi::Persistent(info[1].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetWindowPosCallback(window, GLFWwindowpos_cb)); } else { if (pos_cbs.find(window) != pos_cbs.end()) { pos_cbs.erase(window); } GLFW_TRY(env, GLFWAPI::glfwSetWindowPosCallback(window, NULL)); } } } // GLFWAPI GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun // callback); void glfwSetWindowSizeCallback(Napi::CallbackInfo const& info) { auto window = reinterpret_cast<GLFWwindow*>(info[0].ToNumber().Int64Value()); if (window != nullptr) { // auto env = info.Env(); if (info[1].IsFunction()) { size_cbs[window] = Napi::Persistent(info[1].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetWindowSizeCallback(window, GLFWwindowsize_cb)); } else { if (size_cbs.find(window) != size_cbs.end()) { size_cbs.erase(window); } GLFW_TRY(env, GLFWAPI::glfwSetWindowSizeCallback(window, NULL)); } } } // GLFWAPI GLFWwindowclosefun glfwSetWindowCloseCallback(GLFWwindow* window, GLFWwindowclosefun // callback); void glfwSetWindowCloseCallback(Napi::CallbackInfo const& info) { auto window = reinterpret_cast<GLFWwindow*>(info[0].ToNumber().Int64Value()); if (window != nullptr) { // auto env = info.Env(); if (info[1].IsFunction()) { close_cbs[window] = Napi::Persistent(info[1].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetWindowCloseCallback(window, GLFWwindowclose_cb)); } else { if (close_cbs.find(window) != close_cbs.end()) { close_cbs.erase(window); } GLFW_TRY(env, GLFWAPI::glfwSetWindowCloseCallback(window, NULL)); } } } // GLFWAPI GLFWwindowrefreshfun glfwSetWindowRefreshCallback(GLFWwindow* window, // GLFWwindowrefreshfun callback); void glfwSetWindowRefreshCallback(Napi::CallbackInfo const& info) { auto window = reinterpret_cast<GLFWwindow*>(info[0].ToNumber().Int64Value()); if (window != nullptr) { // auto env = info.Env(); if (info[1].IsFunction()) { refresh_cbs[window] = Napi::Persistent(info[1].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetWindowRefreshCallback(window, GLFWwindowrefresh_cb)); } else { if (refresh_cbs.find(window) != refresh_cbs.end()) { refresh_cbs.erase(window); } GLFW_TRY(env, GLFWAPI::glfwSetWindowRefreshCallback(window, NULL)); } } } // GLFWAPI GLFWwindowfocusfun glfwSetWindowFocusCallback(GLFWwindow* window, GLFWwindowfocusfun // callback); void glfwSetWindowFocusCallback(Napi::CallbackInfo const& info) { auto window = reinterpret_cast<GLFWwindow*>(info[0].ToNumber().Int64Value()); if (window != nullptr) { // auto env = info.Env(); if (info[1].IsFunction()) { focus_cbs[window] = Napi::Persistent(info[1].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetWindowFocusCallback(window, GLFWwindowfocus_cb)); } else { if (focus_cbs.find(window) != focus_cbs.end()) { focus_cbs.erase(window); } GLFW_TRY(env, GLFWAPI::glfwSetWindowFocusCallback(window, NULL)); } } } // GLFWAPI GLFWwindowiconifyfun glfwSetWindowIconifyCallback(GLFWwindow* window, // GLFWwindowiconifyfun callback); void glfwSetWindowIconifyCallback(Napi::CallbackInfo const& info) { auto window = reinterpret_cast<GLFWwindow*>(info[0].ToNumber().Int64Value()); if (window != nullptr) { // auto env = info.Env(); if (info[1].IsFunction()) { iconify_cbs[window] = Napi::Persistent(info[1].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetWindowIconifyCallback(window, GLFWwindowiconify_cb)); } else { if (iconify_cbs.find(window) != iconify_cbs.end()) { iconify_cbs.erase(window); } GLFW_TRY(env, GLFWAPI::glfwSetWindowIconifyCallback(window, NULL)); } } } // GLFWAPI GLFWwindowmaximizefun glfwSetWindowMaximizeCallback(GLFWwindow* window, // GLFWwindowmaximizefun callback); void glfwSetWindowMaximizeCallback(Napi::CallbackInfo const& info) { auto window = reinterpret_cast<GLFWwindow*>(info[0].ToNumber().Int64Value()); if (window != nullptr) { // auto env = info.Env(); if (info[1].IsFunction()) { maximize_cbs[window] = Napi::Persistent(info[1].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetWindowMaximizeCallback(window, GLFWwindowmaximize_cb)); } else { if (maximize_cbs.find(window) != maximize_cbs.end()) { maximize_cbs.erase(window); } GLFW_TRY(env, GLFWAPI::glfwSetWindowMaximizeCallback(window, NULL)); } } } // GLFWAPI GLFWframebuffersizefun glfwSetFramebufferSizeCallback(GLFWwindow* window, // GLFWframebuffersizefun callback); void glfwSetFramebufferSizeCallback(Napi::CallbackInfo const& info) { auto window = reinterpret_cast<GLFWwindow*>(info[0].ToNumber().Int64Value()); if (window != nullptr) { // auto env = info.Env(); if (info[1].IsFunction()) { fb_resize_cbs[window] = Napi::Persistent(info[1].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetFramebufferSizeCallback(window, GLFWframebuffersize_cb)); } else { if (fb_resize_cbs.find(window) != fb_resize_cbs.end()) { fb_resize_cbs.erase(window); } GLFW_TRY(env, GLFWAPI::glfwSetFramebufferSizeCallback(window, NULL)); } } } // GLFWAPI GLFWwindowcontentscalefun glfwSetWindowContentScaleCallback(GLFWwindow* window, // GLFWwindowcontentscalefun callback); void glfwSetWindowContentScaleCallback(Napi::CallbackInfo const& info) { auto window = reinterpret_cast<GLFWwindow*>(info[0].ToNumber().Int64Value()); if (window != nullptr) { // auto env = info.Env(); if (info[1].IsNull() || info[1].IsEmpty() || info[1].IsUndefined()) { if (info[1].IsFunction()) { scale_cbs[window] = Napi::Persistent(info[1].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetWindowContentScaleCallback(window, GLFWwindowcontentscale_cb)); } else { if (scale_cbs.find(window) != scale_cbs.end()) { scale_cbs.erase(window); } GLFW_TRY(env, GLFWAPI::glfwSetWindowContentScaleCallback(window, NULL)); } } } } // GLFWAPI GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun callback); void glfwSetKeyCallback(Napi::CallbackInfo const& info) { auto window = reinterpret_cast<GLFWwindow*>(info[0].ToNumber().Int64Value()); if (window != nullptr) { // auto env = info.Env(); if (info[1].IsFunction()) { key_cbs[window] = Napi::Persistent(info[1].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetKeyCallback(window, GLFWkey_cb)); } else { if (key_cbs.find(window) != key_cbs.end()) { key_cbs.erase(window); } GLFW_TRY(env, GLFWAPI::glfwSetKeyCallback(window, NULL)); } } } // GLFWAPI GLFWcharfun glfwSetCharCallback(GLFWwindow* window, GLFWcharfun callback); void glfwSetCharCallback(Napi::CallbackInfo const& info) { auto window = reinterpret_cast<GLFWwindow*>(info[0].ToNumber().Int64Value()); if (window != nullptr) { // auto env = info.Env(); if (info[1].IsFunction()) { char_cbs[window] = Napi::Persistent(info[1].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetCharCallback(window, GLFWchar_cb)); } else { if (char_cbs.find(window) != char_cbs.end()) { char_cbs.erase(window); } GLFW_TRY(env, GLFWAPI::glfwSetCharCallback(window, NULL)); } } } // GLFWAPI GLFWcharmodsfun glfwSetCharModsCallback(GLFWwindow* window, GLFWcharmodsfun callback); void glfwSetCharModsCallback(Napi::CallbackInfo const& info) { auto window = reinterpret_cast<GLFWwindow*>(info[0].ToNumber().Int64Value()); if (window != nullptr) { // auto env = info.Env(); if (info[1].IsFunction()) { charmods_cbs[window] = Napi::Persistent(info[1].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetCharModsCallback(window, GLFWcharmods_cb)); } else { if (charmods_cbs.find(window) != charmods_cbs.end()) { charmods_cbs.erase(window); } GLFW_TRY(env, GLFWAPI::glfwSetCharModsCallback(window, NULL)); } } } // GLFWAPI GLFWmousebuttonfun glfwSetMouseButtonCallback(GLFWwindow* window, GLFWmousebuttonfun // callback); void glfwSetMouseButtonCallback(Napi::CallbackInfo const& info) { auto window = reinterpret_cast<GLFWwindow*>(info[0].ToNumber().Int64Value()); if (window != nullptr) { // auto env = info.Env(); if (info[1].IsFunction()) { mousebutton_cbs[window] = Napi::Persistent(info[1].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetMouseButtonCallback(window, GLFWmousebutton_cb)); } else { if (mousebutton_cbs.find(window) != mousebutton_cbs.end()) { mousebutton_cbs.erase(window); } GLFW_TRY(env, GLFWAPI::glfwSetMouseButtonCallback(window, NULL)); } } } void glfwSetCursorPosCallback(Napi::CallbackInfo const& info) { auto window = reinterpret_cast<GLFWwindow*>(info[0].ToNumber().Int64Value()); if (window != nullptr) { // auto env = info.Env(); if (info[1].IsFunction()) { cursorpos_cbs[window] = Napi::Persistent(info[1].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetCursorPosCallback(window, GLFWcursorpos_cb)); } else { if (cursorpos_cbs.find(window) != cursorpos_cbs.end()) { cursorpos_cbs.erase(window); } GLFW_TRY(env, GLFWAPI::glfwSetCursorPosCallback(window, NULL)); } } } // GLFWAPI GLFWcursorenterfun glfwSetCursorEnterCallback(GLFWwindow* window, GLFWcursorenterfun // callback); void glfwSetCursorEnterCallback(Napi::CallbackInfo const& info) { auto window = reinterpret_cast<GLFWwindow*>(info[0].ToNumber().Int64Value()); if (window != nullptr) { // auto env = info.Env(); if (info[1].IsFunction()) { cursorenter_cbs[window] = Napi::Persistent(info[1].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetCursorEnterCallback(window, GLFWcursorenter_cb)); } else { if (cursorenter_cbs.find(window) != cursorenter_cbs.end()) { cursorenter_cbs.erase(window); } GLFW_TRY(env, GLFWAPI::glfwSetCursorEnterCallback(window, NULL)); } } } // GLFWAPI GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun callback); void glfwSetScrollCallback(Napi::CallbackInfo const& info) { auto window = reinterpret_cast<GLFWwindow*>(info[0].ToNumber().Int64Value()); if (window != nullptr) { // auto env = info.Env(); if (info[1].IsFunction()) { scroll_cbs[window] = Napi::Persistent(info[1].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetScrollCallback(window, GLFWscroll_cb)); } else { if (scroll_cbs.find(window) != scroll_cbs.end()) { scroll_cbs.erase(window); } GLFW_TRY(env, GLFWAPI::glfwSetScrollCallback(window, NULL)); } } } // GLFWAPI GLFWdropfun glfwSetDropCallback(GLFWwindow* window, GLFWdropfun callback); void glfwSetDropCallback(Napi::CallbackInfo const& info) { auto window = reinterpret_cast<GLFWwindow*>(info[0].ToNumber().Int64Value()); if (window != nullptr) { // auto env = info.Env(); if (info[1].IsFunction()) { drop_cbs[window] = Napi::Persistent(info[1].As<Napi::Function>()); GLFW_TRY(env, GLFWAPI::glfwSetDropCallback(window, GLFWdrop_cb)); } else { if (drop_cbs.find(window) != drop_cbs.end()) { drop_cbs.erase(window); } GLFW_TRY(env, GLFWAPI::glfwSetDropCallback(window, NULL)); } } } } // namespace nv
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/src/window.cpp
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "glfw.hpp" #include "macros.hpp" #include <nv_node/utilities/args.hpp> #include <nv_node/utilities/cpp_to_napi.hpp> #include <algorithm> namespace nv { // GLFWAPI void glfwDefaultWindowHints(void); void glfwDefaultWindowHints(Napi::CallbackInfo const& info) { auto env = info.Env(); GLFW_TRY(env, GLFWAPI::glfwDefaultWindowHints()); } // GLFWAPI void glfwWindowHint(int hint, int value); void glfwWindowHint(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; int32_t hint = args[0]; int32_t value = args[1]; GLFW_TRY(env, GLFWAPI::glfwWindowHint(hint, value)); } // GLFWAPI void glfwWindowHintString(int hint, const char* value); void glfwWindowHintString(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; int32_t hint = args[0]; std::string value = args[1]; GLFW_TRY(env, GLFWAPI::glfwWindowHintString(hint, value.data())); } // GLFWAPI GLFWwindow* glfwCreateWindow(int width, int height, const char* title, GLFWmonitor* // monitor, GLFWwindow* share); Napi::Value glfwCreateWindow(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; int32_t width = args[0]; int32_t height = args[1]; std::string title = args[2]; GLFWmonitor* monitor = nullptr; GLFWwindow* root_win = nullptr; if (info.Length() > 3) { monitor = args[3]; } if (info.Length() > 4) { root_win = args[4]; } GLFWwindow* window = nullptr; GLFW_TRY(env, window = GLFWAPI::glfwCreateWindow(width, height, title.c_str(), monitor, root_win)); return CPPToNapi(info)(window); } // #ifdef __linux__ // // void glfwReparentWindow(GLFWwindow* window); // void glfwReparentWindow(Napi::CallbackInfo const& info) { // CallbackArgs args{info}; // int32_t targetX = args[2]; // int32_t targetY = args[3]; // auto display = glfwGetX11Display(); // auto child = glfwGetX11Window(args[0]); // Window parent = args[1]; // XWindowAttributes attrs; // XGetWindowAttributes(display, parent, &attrs); // XReparentWindow(display, child, parent, targetX, targetY); // XResizeWindow(display, child, attrs.width - targetX, attrs.height - targetY); // } // #endif // GLFWAPI void glfwDestroyWindow(GLFWwindow* window); void glfwDestroyWindow(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwDestroyWindow(args[0])); } // GLFWAPI int glfwWindowShouldClose(GLFWwindow* window); Napi::Value glfwWindowShouldClose(Napi::CallbackInfo const& info) { CallbackArgs args{info}; auto should_close = GLFWAPI::glfwWindowShouldClose(args[0]); return CPPToNapi(info)(static_cast<bool>(should_close)); } // GLFWAPI void glfwSetWindowShouldClose(GLFWwindow* window, int value); void glfwSetWindowShouldClose(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwSetWindowShouldClose(args[0], args[1])); } // GLFWAPI void glfwSetWindowTitle(GLFWwindow* window, const char* title); void glfwSetWindowTitle(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; std::string title = args[1]; GLFW_TRY(env, GLFWAPI::glfwSetWindowTitle(args[0], title.data())); } // GLFWAPI void glfwSetWindowIcon(GLFWwindow* window, int count, const GLFWimage* images); void glfwSetWindowIcon(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFWwindow* window = args[0]; Napi::Array js_images = args[1]; std::vector<GLFWimage> images(js_images.Length()); size_t i{0}; std::generate_n(images.begin(), images.size(), [&]() mutable { Napi::Object image = js_images.Get(i++).As<Napi::Object>(); return GLFWimage{ NapiToCPP(image.Get("width")), NapiToCPP(image.Get("height")), NapiToCPP(image.Get("pixels")), }; }); GLFW_TRY(env, GLFWAPI::glfwSetWindowIcon(window, images.size(), images.data())); } // GLFWAPI void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos); Napi::Value glfwGetWindowPos(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; int32_t x{}, y{}; GLFWwindow* window = args[0]; GLFW_TRY(env, GLFWAPI::glfwGetWindowPos(window, &x, &y)); return CPPToNapi(info)(std::map<std::string, int32_t>{{"x", x}, {"y", y}}); } // GLFWAPI void glfwSetWindowPos(GLFWwindow* window, int xpos, int ypos); void glfwSetWindowPos(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFWwindow* window = args[0]; std::map<std::string, int32_t> pos = args[1]; GLFW_TRY(env, GLFWAPI::glfwSetWindowPos(window, pos["x"], pos["y"])); } // GLFWAPI void glfwGetWindowSize(GLFWwindow* window, int* width, int* height); Napi::Value glfwGetWindowSize(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; int32_t width{}, height{}; GLFWwindow* window = args[0]; GLFW_TRY(env, GLFWAPI::glfwGetWindowSize(window, &width, &height)); return CPPToNapi(info)(std::map<std::string, int32_t>{{"width", width}, {"height", height}}); } // GLFWAPI void glfwSetWindowSizeLimits(GLFWwindow* window, int minwidth, int minheight, int // maxwidth, int maxheight); void glfwSetWindowSizeLimits(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFWwindow* window = args[0]; std::map<std::string, int32_t> pos = args[1]; GLFW_TRY(env, GLFWAPI::glfwSetWindowSizeLimits( // window, pos["minWidth"], pos["minHeight"], pos["maxWidth"], pos["maxHeight"])); } // GLFWAPI void glfwSetWindowAspectRatio(GLFWwindow* window, int numer, int denom); void glfwSetWindowAspectRatio(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwSetWindowAspectRatio(args[0], args[1], args[2])); } // GLFWAPI void glfwSetWindowSize(GLFWwindow* window, int width, int height); void glfwSetWindowSize(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFWwindow* window = args[0]; std::map<std::string, int32_t> pos = args[1]; GLFW_TRY(env, GLFWAPI::glfwSetWindowSize(window, pos["width"], pos["height"])); } // GLFWAPI void glfwGetFramebufferSize(GLFWwindow* window, int* width, int* height); Napi::Value glfwGetFramebufferSize(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; int32_t width{}, height{}; GLFWwindow* window = args[0]; GLFW_TRY(env, GLFWAPI::glfwGetFramebufferSize(window, &width, &height)); return CPPToNapi(info)(std::map<std::string, int32_t>{{"width", width}, {"height", height}}); } // GLFWAPI void glfwGetWindowFrameSize(GLFWwindow* window, int* left, int* top, int* right, int* // bottom); Napi::Value glfwGetWindowFrameSize(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; int32_t left{}, top{}, right{}, bottom{}; GLFWwindow* window = args[0]; GLFW_TRY(env, GLFWAPI::glfwGetWindowFrameSize(window, &left, &top, &right, &bottom)); return CPPToNapi(info)(std::map<std::string, int32_t>{// {"left", left}, {"top", top}, {"right", right}, {"bottom", bottom}}); } // GLFWAPI void glfwGetWindowContentScale(GLFWwindow* window, float* xscale, float* yscale); Napi::Value glfwGetWindowContentScale(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; float xscale{}, yscale{}; GLFWwindow* window = args[0]; GLFW_TRY(env, GLFWAPI::glfwGetWindowContentScale(window, &xscale, &yscale)); return CPPToNapi(info)(std::map<std::string, int32_t>{// {"xscale", xscale}, {"yscale", yscale}}); } // GLFWAPI float glfwGetWindowOpacity(GLFWwindow* window); Napi::Value glfwGetWindowOpacity(Napi::CallbackInfo const& info) { CallbackArgs args{info}; return CPPToNapi(info)(GLFWAPI::glfwGetWindowOpacity(args[0])); } // GLFWAPI void glfwSetWindowOpacity(GLFWwindow* window, float opacity); void glfwSetWindowOpacity(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwSetWindowOpacity(args[0], args[1])); } // GLFWAPI void glfwIconifyWindow(GLFWwindow* window); void glfwIconifyWindow(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwIconifyWindow(args[0])); } // GLFWAPI void glfwRestoreWindow(GLFWwindow* window); void glfwRestoreWindow(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwRestoreWindow(args[0])); } // GLFWAPI void glfwMaximizeWindow(GLFWwindow* window); void glfwMaximizeWindow(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwMaximizeWindow(args[0])); } // GLFWAPI void glfwShowWindow(GLFWwindow* window); void glfwShowWindow(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwShowWindow(args[0])); } // GLFWAPI void glfwHideWindow(GLFWwindow* window); void glfwHideWindow(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwHideWindow(args[0])); } // GLFWAPI void glfwFocusWindow(GLFWwindow* window); void glfwFocusWindow(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwFocusWindow(args[0])); } // GLFWAPI void glfwRequestWindowAttention(GLFWwindow* window); void glfwRequestWindowAttention(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwRequestWindowAttention(args[0])); } // GLFWAPI GLFWmonitor* glfwGetWindowMonitor(GLFWwindow* window); Napi::Value glfwGetWindowMonitor(Napi::CallbackInfo const& info) { CallbackArgs args{info}; return CPPToNapi(info)(GLFWAPI::glfwGetWindowMonitor(args[0])); } // GLFWAPI void glfwSetWindowMonitor(GLFWwindow* window, GLFWmonitor* monitor, int xpos, int ypos, // int width, int height, int refreshRate); void glfwSetWindowMonitor(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFWwindow* window = args[0]; GLFWmonitor* monitor = args[1]; std::map<std::string, int32_t> map = args[2]; GLFW_TRY(env, GLFWAPI::glfwSetWindowMonitor( // window, monitor, map["x"], map["y"], map["width"], map["height"], map["refreshRate"])); } // GLFWAPI int glfwGetWindowAttrib(GLFWwindow* window, int attrib); Napi::Value glfwGetWindowAttrib(Napi::CallbackInfo const& info) { CallbackArgs args{info}; return CPPToNapi(info)(GLFWAPI::glfwGetWindowAttrib(args[0], args[1])); } // GLFWAPI void glfwSetWindowAttrib(GLFWwindow* window, int attrib, int value); void glfwSetWindowAttrib(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFWwindow* window = args[0]; int32_t attrib = args[1]; int32_t value = args[2]; GLFW_TRY(env, GLFWAPI::glfwSetWindowAttrib(window, attrib, value)); } // GLFWAPI void glfwSetWindowUserPointer(GLFWwindow* window, void* pointer); // Napi::Value glfwSetWindowUserPointer(Napi::CallbackInfo const& info); // GLFWAPI void* glfwGetWindowUserPointer(GLFWwindow* window); // Napi::Value glfwGetWindowUserPointer(Napi::CallbackInfo const& info); // GLFWAPI int glfwGetInputMode(GLFWwindow* window, int mode); Napi::Value glfwGetInputMode(Napi::CallbackInfo const& info) { CallbackArgs args{info}; return CPPToNapi(info)(GLFWAPI::glfwGetInputMode(args[0], args[1])); } // GLFWAPI void glfwSetInputMode(GLFWwindow* window, int mode, int value); void glfwSetInputMode(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwSetInputMode(args[0], args[1], args[2])); } // GLFWAPI int glfwGetKey(GLFWwindow* window, int key); Napi::Value glfwGetKey(Napi::CallbackInfo const& info) { CallbackArgs args{info}; return CPPToNapi(info)(GLFWAPI::glfwGetKey(args[0], args[1])); } // GLFWAPI int glfwGetMouseButton(GLFWwindow* window, int button); Napi::Value glfwGetMouseButton(Napi::CallbackInfo const& info) { CallbackArgs args{info}; return CPPToNapi(info)(GLFWAPI::glfwGetMouseButton(args[0], args[1])); } // GLFWAPI void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos); Napi::Value glfwGetCursorPos(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; double x{}, y{}; GLFWwindow* window = args[0]; GLFW_TRY(env, GLFWAPI::glfwGetCursorPos(window, &x, &y)); return CPPToNapi(info)(std::map<std::string, int32_t>{// {"x", x}, {"y", y}}); } // GLFWAPI void glfwSetCursorPos(GLFWwindow* window, double xpos, double ypos); void glfwSetCursorPos(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFWwindow* window = args[0]; std::map<std::string, int32_t> pos = args[1]; GLFW_TRY(env, GLFWAPI::glfwSetCursorPos(window, pos["x"], pos["y"])); } // GLFWAPI void glfwSetCursor(GLFWwindow* window, GLFWcursor* cursor); void glfwSetCursor(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwSetCursor(args[0], args[1])); } // GLFWAPI void glfwSetClipboardString(GLFWwindow* window, const char* string); void glfwSetClipboardString(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; std::string str = args[1]; GLFW_TRY(env, GLFWAPI::glfwSetClipboardString(args[0], str.data())); } // GLFWAPI const char* glfwGetClipboardString(GLFWwindow* window); Napi::Value glfwGetClipboardString(Napi::CallbackInfo const& info) { CallbackArgs args{info}; auto str = GLFWAPI::glfwGetClipboardString(args[0]); return CPPToNapi(info)(std::string{str == nullptr ? str : ""}); } // GLFWAPI void glfwMakeContextCurrent(GLFWwindow* window); void glfwMakeContextCurrent(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwMakeContextCurrent(args[0])); } // GLFWAPI GLFWwindow* glfwGetCurrentContext(void); Napi::Value glfwGetCurrentContext(Napi::CallbackInfo const& info) { return CPPToNapi(info)(GLFWAPI::glfwGetCurrentContext()); } // GLFWAPI void glfwSwapBuffers(GLFWwindow* window); void glfwSwapBuffers(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwSwapBuffers(args[0])); } } // namespace nv
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/src/vulkan.cpp
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "glfw.hpp" #include "macros.hpp" #include <nv_node/utilities/cpp_to_napi.hpp> namespace nv { // GLFWAPI int glfwVulkanSupported(void); Napi::Value glfwVulkanSupported(Napi::CallbackInfo const& info) { return Napi::Value::From(info.Env(), static_cast<bool>(GLFWAPI::glfwVulkanSupported())); } // TODO: // #if defined(VK_VERSION_1_0) // // GLFWAPI GLFWvkproc glfwGetInstanceProcAddress(VkInstance instance, const char* procname); // Napi::Value glfwGetInstanceProcAddress(Napi::CallbackInfo const& info); // // GLFWAPI int glfwGetPhysicalDevicePresentationSupport(VkInstance instance, VkPhysicalDevice // device, uint32_t // // queuefamily); // Napi::Value glfwGetPhysicalDevicePresentationSupport(Napi::CallbackInfo const& info); // // GLFWAPI VkResult glfwCreateWindowSurface(VkInstance instance, GLFWwindow* window, const // VkAllocationCallbacks* // // allocator, VkSurfaceKHR* surface); // Napi::Value glfwCreateWindowSurface(Napi::CallbackInfo const& info); // #endif /*VK_VERSION_1_0*/ } // namespace nv
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/src/glfw.hpp
// Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <napi.h> #define GLFW_NO_GLU #define GLFW_DLL #include <GLFW/glfw3.h> #ifdef _WIN32 #define GLFW_EXPOSE_NATIVE_WIN32 #define GLFW_EXPOSE_NATIVE_WGL #elif __APPLE__ #define GLFW_EXPOSE_NATIVE_COCOA #define GLFW_EXPOSE_NATIVE_NSGL #elif __linux__ #define GLFW_EXPOSE_NATIVE_EGL #endif #include <GLFW/glfw3native.h> // Fix bad defines #ifdef True #undef True #endif #ifdef False #undef False #endif
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/src/glfw.ts
// Copyright (c) 2020-2023, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {addon as CORE} from '@rapidsai/core'; export const isHeadless = typeof process.env.DISPLAY === 'undefined' ? true : false; export const GLFW: any = require('bindings')(isHeadless ? 'rapidsai_glfw_eglheadless.node' : 'rapidsai_glfw_x11.node') .init(CORE); process?.on && process?.on('exit', () => GLFW.terminate()); process?.on && process?.on('beforeExit', () => GLFW.terminate()); export default GLFW; export type GLFWmonitor = number; export type GLFWwindow = number; export type GLFWcursor = number; export type GLFWglproc = number; export type GLFWParentWindow = number|bigint|Buffer|ArrayBufferView|ArrayBufferView; export interface GLFWVersion { major: number; minor: number; rev: number; } export interface GLFWScale { xscale: number; yscale: number; } export interface GLFWPosition { x: number; y: number; } export interface GLFWSize { width: number; height: number; } export interface GLFWRect { left: number; top: number; right: number; bottom: number; } export interface GLFWSizeLimits { minWidth: number; minHeight: number; maxWidth: number; maxHeight: number; } export interface GLFWPositionAndSize extends GLFWPosition, GLFWSize {} export interface GLFWvidmode { /** The width, in screen coordinates, of the video mode. */ width: number; /** The height, in screen coordinates, of the video mode. */ height: number; /** The bit depth of the red channel of the video mode. */ redBits: number; /** The bit depth of the green channel of the video mode. */ greenBits: number; /** The bit depth of the blue channel of the video mode. */ blueBits: number; /** The refresh rate, in Hz, of the video mode. */ refreshRate: number; } export interface GLFWgammaramp { /** An array of value describing the response of the red channel. */ red: number[]; /** An array of value describing the response of the green channel. */ green: number[]; /** An array of value describing the response of the blue channel. */ blue: number[]; } export interface GLFWimage { /** The width, in pixels, of this image. */ width: number; /** The height, in pixels, of this image. */ height: number; /** The pixel data of this image, arranged left-to-right, top-to-bottom. */ pixels: ArrayBufferLike|ArrayBufferView; } export interface GLFWgamepadstate { /** The states of each gamepad button], `GLFW_PRESS` or `GLFW_RELEASE`. */ buttons: number[]; /** The states of each gamepad axis], in the range -1.0 to 1.0 inclusive. */ axes: number[]; } // eslint-disable-next-line @typescript-eslint/no-namespace export namespace glfw { export const TRUE = GLFW.TRUE; export const FALSE = GLFW.FALSE; export const PRESS = GLFW.PRESS; export const REPEAT = GLFW.REPEAT; export const RELEASE = GLFW.RELEASE; // export const init: () => void = GLFW.init; export const terminate: () => void = GLFW.terminate; export const initHint: (hint: number, value: number|boolean) => void = GLFW.initHint; export const getVersion: () => GLFWVersion = GLFW.getVersion; export const getVersionString: () => string = GLFW.getVersionString; export const getError: () => Error | undefined = GLFW.getError; export const getMonitors: () => GLFWmonitor[] = GLFW.getMonitors; export const getPrimaryMonitor: () => GLFWmonitor = GLFW.getPrimaryMonitor; export const getMonitorPos: (monitor: GLFWmonitor) => GLFWPosition = GLFW.getMonitorPos; export const getMonitorWorkarea: (monitor: GLFWmonitor) => GLFWPositionAndSize = GLFW.getMonitorWorkarea; export const getMonitorPhysicalSize: (monitor: GLFWmonitor) => GLFWSize = GLFW.getMonitorPhysicalSize; export const getMonitorContentScale: (monitor: GLFWmonitor) => GLFWScale = GLFW.getMonitorContentScale; export const getMonitorName: (monitor: GLFWmonitor) => string = GLFW.getMonitorName; export const getVideoModes: (monitor: GLFWmonitor) => GLFWvidmode[] = GLFW.getVideoModes; export const getVideoMode: (monitor: GLFWmonitor) => GLFWvidmode = GLFW.getVideoMode; export const setGamma: (monitor: GLFWmonitor, gamma: number) => void = GLFW.setGamma; export const getGammaRamp: (monitor: GLFWmonitor) => GLFWgammaramp = GLFW.getGammaRamp; export const setGammaRamp: (monitor: GLFWmonitor, rapi: GLFWgammaramp) => void = GLFW.setGammaRamp; export const defaultWindowHints: () => void = GLFW.defaultWindowHints; export const windowHint: (hint: GLFWWindowAttribute, value: number|boolean) => void = GLFW.windowHint; export const windowHintString: (hint: string, value: number|boolean) => void = GLFW.windowHintString; export const createWindow: (width: number, height: number, title: string, monitor?: GLFWmonitor|null, root?: GLFWwindow|null) => GLFWwindow = GLFW.createWindow; export const reparentWindow: (child: GLFWwindow, parent: GLFWParentWindow, targetX: number, targetY: number) => void = GLFW.reparentWindow; export const destroyWindow: (window: GLFWwindow) => void = GLFW.destroyWindow; export const windowShouldClose: (window: GLFWwindow) => boolean = GLFW.windowShouldClose; export const setWindowShouldClose: (window: GLFWwindow, shouldClose: boolean) => void = GLFW.setWindowShouldClose; export const setWindowTitle: (window: GLFWwindow, title: string) => void = GLFW.setWindowTitle; export const setWindowIcon: (window: GLFWwindow, icon: GLFWimage) => void = GLFW.setWindowIcon; export const getWindowPos: (window: GLFWwindow) => GLFWPosition = GLFW.getWindowPos; export const setWindowPos: (window: GLFWwindow, position: GLFWPosition) => void = GLFW.setWindowPos; export const getWindowSize: (window: GLFWwindow) => GLFWSize = GLFW.getWindowSize; export const setWindowSizeLimits: (window: GLFWwindow, limits: GLFWSizeLimits) => void = GLFW.setWindowSizeLimits; export const setWindowAspectRatio: (window: GLFWwindow, num: number, denom: number) => void = GLFW.setWindowAspectRatio; export const setWindowSize: (window: GLFWwindow, size: GLFWSize) => void = GLFW.setWindowSize; export const getFramebufferSize: (window: GLFWwindow) => GLFWSize = GLFW.getFramebufferSize; export const getWindowFrameSize: (window: GLFWwindow) => GLFWRect = GLFW.getWindowFrameSize; export const getWindowContentScale: (window: GLFWwindow) => GLFWScale = GLFW.getWindowContentScale; export const getWindowOpacity: (window: GLFWwindow) => number = GLFW.getWindowOpacity; export const setWindowOpacity: (window: GLFWwindow, opacity: number) => void = GLFW.setWindowOpacity; export const iconifyWindow: (window: GLFWwindow) => void = GLFW.iconifyWindow; export const restoreWindow: (window: GLFWwindow) => void = GLFW.restoreWindow; export const maximizeWindow: (window: GLFWwindow) => void = GLFW.maximizeWindow; export const showWindow: (window: GLFWwindow) => void = GLFW.showWindow; export const hideWindow: (window: GLFWwindow) => void = GLFW.hideWindow; export const focusWindow: (window: GLFWwindow) => void = GLFW.focusWindow; export const requestWindowAttention: (window: GLFWwindow) => void = GLFW.requestWindowAttention; export const getWindowMonitor: (window: GLFWwindow) => GLFWmonitor = GLFW.getWindowMonitor; export const setWindowMonitor: (window: GLFWwindow, monitor: GLFWmonitor) => void = GLFW.setWindowMonitor; export const getWindowAttrib: (window: GLFWwindow, attribute: GLFWWindowAttribute) => void = GLFW.getWindowAttrib; export const setWindowAttrib: (window: GLFWwindow, attribute: GLFWWindowAttribute, value: number|boolean) => void = GLFW.setWindowAttrib; export const pollEvents: () => void = GLFW.pollEvents; export const waitEvents: () => void = GLFW.waitEvents; export const waitEventsTimeout: (timeout: number) => void = GLFW.waitEventsTimeout; export const postEmptyEvent: () => void = GLFW.postEmptyEvent; export const getInputMode: (window: GLFWwindow, mode: number) => number = GLFW.getInputMode; export const setInputMode: (window: GLFWwindow, mode: number, value: number|boolean) => void = GLFW.setInputMode; export const rawMouseMotionSupported: () => boolean = GLFW.rawMouseMotionSupported; export const getKeyName: (key: number, scancode: number) => string = GLFW.getKeyName; export const getKeyScancode: (key: number) => number = GLFW.getKeyScancode; export const getKey: (window: GLFWwindow, key: number) => void = GLFW.getKey; export const getMouseButton: (window: GLFWwindow, button: number) => number = GLFW.getMouseButton; export const getCursorPos: (window: GLFWwindow) => GLFWPosition = GLFW.getCursorPos; export const setCursorPos: (window: GLFWwindow, position: GLFWPosition) => void = GLFW.setCursorPos; export const createCursor: (image: GLFWimage, x: number, y: number) => GLFWcursor = GLFW.createCursor; export const createStandardCursor: (shape: number) => GLFWcursor = GLFW.createStandardCursor; export const destroyCursor: (cursor: GLFWcursor) => void = GLFW.destroyCursor; export const setCursor: (window: GLFWwindow, cursor: GLFWcursor) => void = GLFW.setCursor; export const joystickPresent: (joystickId: number) => boolean = GLFW.joystickPresent; export const getJoystickAxes: (joystickId: number) => number[] = GLFW.getJoystickAxes; export const getJoystickButtons: (joystickId: number) => number[] = GLFW.getJoystickButtons; export const getJoystickHats: (joystickId: number) => number[] = GLFW.getJoystickHats; export const getJoystickName: (joystickId: number) => string = GLFW.getJoystickName; export const getJoystickGUID: (joystickId: number) => string = GLFW.getJoystickGUID; export const joystickIsGamepad: (joystickId: number) => boolean = GLFW.joystickIsGamepad; export const updateGamepadMappings: (mappings: string) => void = GLFW.updateGamepadMappings; export const getGamepadName: (joystickId: number) => string = GLFW.getGamepadName; export const getGamepadState: (joystickId: number) => GLFWgamepadstate = GLFW.getGamepadState; export const setClipboardString: (window: GLFWwindow, value: string) => void = GLFW.setClipboardString; export const getClipboardString: (window: GLFWwindow) => string = GLFW.getClipboardString; export const getTime: () => number = GLFW.getTime; export const setTime: (time: number) => void = GLFW.setTime; export const getTimerValue: () => number = GLFW.getTimerValue; export const getTimerFrequency: () => number = GLFW.getTimerFrequency; export const makeContextCurrent: (window: GLFWwindow) => void = GLFW.makeContextCurrent; export const getCurrentContext: () => GLFWwindow = GLFW.getCurrentContext; export const swapBuffers: (window: GLFWwindow) => void = GLFW.swapBuffers; export const swapInterval: (interval: number) => void = GLFW.swapInterval; export const extensionSupported: (extension: string) => boolean = GLFW.extensionSupported; export const getProcAddress: (procname: string) => GLFWglproc = GLFW.getProcAddress; export const vulkanSupported: () => boolean = GLFW.vulkanSupported; export const getRequiredInstanceExtensions: () => string[] = GLFW.getRequiredInstanceExtensions; export const setErrorCallback: (callback: null| ((error_code: number, description: string) => void)) => void = GLFW.setErrorCallback; export const setMonitorCallback: (callback: null| ((monitor: GLFWmonitor, event: number) => void)) => void = GLFW.setMonitorCallback; export const setJoystickCallback: (callback: null|((joystick: number, event: number) => void)) => void = GLFW.setJoystickCallback; export const setWindowPosCallback: (window: GLFWwindow, callback: null| ((window: GLFWwindow, x: number, y: number) => void)) => void = GLFW.setWindowPosCallback; export const setWindowSizeCallback: (window: GLFWwindow, callback: null|((window: GLFWwindow, width: number, height: number) => void)) => void = GLFW.setWindowSizeCallback; export const setWindowCloseCallback: (window: GLFWwindow, callback: null|((window: GLFWwindow) => void)) => void = GLFW.setWindowCloseCallback; export const setWindowRefreshCallback: (window: GLFWwindow, callback: null|((window: GLFWwindow) => void)) => void = GLFW.setWindowRefreshCallback; export const setWindowFocusCallback: (window: GLFWwindow, callback: null| ((window: GLFWwindow, focused: boolean) => void)) => void = GLFW.setWindowFocusCallback; export const setWindowIconifyCallback: (window: GLFWwindow, callback: null| ((window: GLFWwindow, iconified: boolean) => void)) => void = GLFW.setWindowIconifyCallback; export const setWindowMaximizeCallback: (window: GLFWwindow, callback: null| ((window: GLFWwindow, maximized: boolean) => void)) => void = GLFW.setWindowMaximizeCallback; export const setFramebufferSizeCallback: (window: GLFWwindow, callback: null|((window: GLFWwindow, width: number, height: number) => void)) => void = GLFW.setFramebufferSizeCallback; export const setWindowContentScaleCallback: (window: GLFWwindow, callback: null|((window: GLFWwindow, xscale: number, yscale: number) => void)) => void = GLFW.setWindowContentScaleCallback; export const setKeyCallback: (window: GLFWwindow, callback: null| ((window: GLFWwindow, key: number, scancode: number, action: number, mods: number) => void)) => void = GLFW.setKeyCallback; export const setCharCallback: (window: GLFWwindow, callback: null|((window: GLFWwindow, code: number) => void)) => void = GLFW.setCharCallback; export const setCharModsCallback: (window: GLFWwindow, callback: null| ((window: GLFWwindow, code: number, mods: number) => void)) => void = GLFW.setCharModsCallback; export const setMouseButtonCallback: (window: GLFWwindow, callback: null|((window: GLFWwindow, button: number, action: number, mods: number) => void)) => void = GLFW.setMouseButtonCallback; export const setCursorPosCallback: (window: GLFWwindow, callback: null| ((window: GLFWwindow, x: number, y: number) => void)) => void = GLFW.setCursorPosCallback; export const setCursorEnterCallback: (window: GLFWwindow, callback: null| ((window: GLFWwindow, entered: number) => void)) => void = GLFW.setCursorEnterCallback; export const setScrollCallback: (window: GLFWwindow, callback: null|((window: GLFWwindow, xoffset: number, yoffset: number) => void)) => void = GLFW.setScrollCallback; export const setDropCallback: (window: GLFWwindow, callback: null|((window: GLFWwindow, items: string[]) => void)) => void = GLFW.setDropCallback; // export const getInstanceProcAddress: () => void = GLFW.getInstanceProcAddress; // export const getPhysicalDevicePresentationSupport: () => void = // GLFW.getPhysicalDevicePresentationSupport; export const createWindowSurface: () => void = // GLFW.createWindowSurface; } export const GLFWStandardCursor = { ARROW: glfw.createStandardCursor(GLFW.ARROW_CURSOR), IBEAM: glfw.createStandardCursor(GLFW.IBEAM_CURSOR), CROSSHAIR: glfw.createStandardCursor(GLFW.CROSSHAIR_CURSOR), HAND: glfw.createStandardCursor(GLFW.HAND_CURSOR), HRESIZE: glfw.createStandardCursor(GLFW.HRESIZE_CURSOR), VRESIZE: glfw.createStandardCursor(GLFW.VRESIZE_CURSOR), }; export enum GLFWClientAPI { NONE = GLFW.NO_API, OPENGL = GLFW.OPENGL_API, OPENGL_ES = GLFW.OPENGL_ES_API, } export enum GLFWOpenGLProfile { ANY = GLFW.OPENGL_ANY_PROFILE, CORE = GLFW.OPENGL_CORE_PROFILE, COMPAT = GLFW.OPENGL_COMPAT_PROFILE, } export enum GLFWContextCreationAPI { EGL = GLFW.EGL_CONTEXT_API, NATIVE = GLFW.NATIVE_CONTEXT_API, OSMESA = GLFW.OSMESA_CONTEXT_API, } export enum GLFWWindowAttribute { FOCUSED = GLFW.FOCUSED, ICONIFIED = GLFW.ICONIFIED, RESIZABLE = GLFW.RESIZABLE, VISIBLE = GLFW.VISIBLE, DECORATED = GLFW.DECORATED, AUTO_ICONIFY = GLFW.AUTO_ICONIFY, FLOATING = GLFW.FLOATING, MAXIMIZED = GLFW.MAXIMIZED, CENTER_CURSOR = GLFW.CENTER_CURSOR, TRANSPARENT_FRAMEBUFFER = GLFW.TRANSPARENT_FRAMEBUFFER, HOVERED = GLFW.HOVERED, FOCUS_ON_SHOW = GLFW.FOCUS_ON_SHOW, RED_BITS = GLFW.RED_BITS, GREEN_BITS = GLFW.GREEN_BITS, BLUE_BITS = GLFW.BLUE_BITS, ALPHA_BITS = GLFW.ALPHA_BITS, DEPTH_BITS = GLFW.DEPTH_BITS, STENCIL_BITS = GLFW.STENCIL_BITS, ACCUM_RED_BITS = GLFW.ACCUM_RED_BITS, ACCUM_GREEN_BITS = GLFW.ACCUM_GREEN_BITS, ACCUM_BLUE_BITS = GLFW.ACCUM_BLUE_BITS, ACCUM_ALPHA_BITS = GLFW.ACCUM_ALPHA_BITS, AUX_BUFFERS = GLFW.AUX_BUFFERS, STEREO = GLFW.STEREO, SAMPLES = GLFW.SAMPLES, SRGB_CAPABLE = GLFW.SRGB_CAPABLE, REFRESH_RATE = GLFW.REFRESH_RATE, DOUBLEBUFFER = GLFW.DOUBLEBUFFER, CLIENT_API = GLFW.CLIENT_API, CONTEXT_VERSION_MAJOR = GLFW.CONTEXT_VERSION_MAJOR, CONTEXT_VERSION_MINOR = GLFW.CONTEXT_VERSION_MINOR, CONTEXT_REVISION = GLFW.CONTEXT_REVISION, CONTEXT_ROBUSTNESS = GLFW.CONTEXT_ROBUSTNESS, OPENGL_FORWARD_COMPAT = GLFW.OPENGL_FORWARD_COMPAT, OPENGL_DEBUG_CONTEXT = GLFW.OPENGL_DEBUG_CONTEXT, OPENGL_PROFILE = GLFW.OPENGL_PROFILE, CONTEXT_RELEASE_BEHAVIOR = GLFW.CONTEXT_RELEASE_BEHAVIOR, CONTEXT_NO_ERROR = GLFW.CONTEXT_NO_ERROR, CONTEXT_CREATION_API = GLFW.CONTEXT_CREATION_API, SCALE_TO_MONITOR = GLFW.SCALE_TO_MONITOR, COCOA_RETINA_FRAMEBUFFER = GLFW.COCOA_RETINA_FRAMEBUFFER, COCOA_FRAME_NAME = GLFW.COCOA_FRAME_NAME, COCOA_GRAPHICS_SWITCHING = GLFW.COCOA_GRAPHICS_SWITCHING, X11_CLASS_NAME = GLFW.X11_CLASS_NAME, X11_INSTANCE_NAME = GLFW.X11_INSTANCE_NAME, } export enum GLFWModifierKey { MOD_ALT = GLFW.MOD_ALT, MOD_SHIFT = GLFW.MOD_SHIFT, MOD_SUPER = GLFW.MOD_SUPER, MOD_CONTROL = GLFW.MOD_CONTROL, MOD_NUM_LOCK = GLFW.MOD_NUM_LOCK, MOD_CAPS_LOCK = GLFW.MOD_CAPS_LOCK, } export enum GLFWMouseButton { MOUSE_BUTTON_1 = GLFW.MOUSE_BUTTON_1, MOUSE_BUTTON_2 = GLFW.MOUSE_BUTTON_2, MOUSE_BUTTON_3 = GLFW.MOUSE_BUTTON_3, MOUSE_BUTTON_4 = GLFW.MOUSE_BUTTON_4, MOUSE_BUTTON_5 = GLFW.MOUSE_BUTTON_5, MOUSE_BUTTON_6 = GLFW.MOUSE_BUTTON_6, MOUSE_BUTTON_7 = GLFW.MOUSE_BUTTON_7, MOUSE_BUTTON_8 = GLFW.MOUSE_BUTTON_8, MOUSE_BUTTON_LAST = GLFW.MOUSE_BUTTON_LAST, MOUSE_BUTTON_LEFT = GLFW.MOUSE_BUTTON_LEFT, MOUSE_BUTTON_RIGHT = GLFW.MOUSE_BUTTON_RIGHT, MOUSE_BUTTON_MIDDLE = GLFW.MOUSE_BUTTON_MIDDLE, } export enum GLFWInputMode { CURSOR = GLFW.CURSOR, STICKY_KEYS = GLFW.STICKY_KEYS, STICKY_MOUSE_BUTTONS = GLFW.STICKY_MOUSE_BUTTONS, LOCK_KEY_MODS = GLFW.LOCK_KEY_MODS, RAW_MOUSE_MOTION = GLFW.RAW_MOUSE_MOTION, } export enum GLFWKey { KEY_UNKNOWN = GLFW.KEY_UNKNOWN, KEY_SPACE = GLFW.KEY_SPACE, KEY_APOSTROPHE = GLFW.KEY_APOSTROPHE, KEY_COMMA = GLFW.KEY_COMMA, KEY_MINUS = GLFW.KEY_MINUS, KEY_PERIOD = GLFW.KEY_PERIOD, KEY_SLASH = GLFW.KEY_SLASH, KEY_0 = GLFW.KEY_0, KEY_1 = GLFW.KEY_1, KEY_2 = GLFW.KEY_2, KEY_3 = GLFW.KEY_3, KEY_4 = GLFW.KEY_4, KEY_5 = GLFW.KEY_5, KEY_6 = GLFW.KEY_6, KEY_7 = GLFW.KEY_7, KEY_8 = GLFW.KEY_8, KEY_9 = GLFW.KEY_9, KEY_SEMICOLON = GLFW.KEY_SEMICOLON, KEY_EQUAL = GLFW.KEY_EQUAL, KEY_A = GLFW.KEY_A, KEY_B = GLFW.KEY_B, KEY_C = GLFW.KEY_C, KEY_D = GLFW.KEY_D, KEY_E = GLFW.KEY_E, KEY_F = GLFW.KEY_F, KEY_G = GLFW.KEY_G, KEY_H = GLFW.KEY_H, KEY_I = GLFW.KEY_I, KEY_J = GLFW.KEY_J, KEY_K = GLFW.KEY_K, KEY_L = GLFW.KEY_L, KEY_M = GLFW.KEY_M, KEY_N = GLFW.KEY_N, KEY_O = GLFW.KEY_O, KEY_P = GLFW.KEY_P, KEY_Q = GLFW.KEY_Q, KEY_R = GLFW.KEY_R, KEY_S = GLFW.KEY_S, KEY_T = GLFW.KEY_T, KEY_U = GLFW.KEY_U, KEY_V = GLFW.KEY_V, KEY_W = GLFW.KEY_W, KEY_X = GLFW.KEY_X, KEY_Y = GLFW.KEY_Y, KEY_Z = GLFW.KEY_Z, KEY_LEFT_BRACKET = GLFW.KEY_LEFT_BRACKET, KEY_BACKSLASH = GLFW.KEY_BACKSLASH, KEY_RIGHT_BRACKET = GLFW.KEY_RIGHT_BRACKET, KEY_GRAVE_ACCENT = GLFW.KEY_GRAVE_ACCENT, KEY_WORLD_1 = GLFW.KEY_WORLD_1, KEY_WORLD_2 = GLFW.KEY_WORLD_2, KEY_ESCAPE = GLFW.KEY_ESCAPE, KEY_ENTER = GLFW.KEY_ENTER, KEY_TAB = GLFW.KEY_TAB, KEY_BACKSPACE = GLFW.KEY_BACKSPACE, KEY_INSERT = GLFW.KEY_INSERT, KEY_DELETE = GLFW.KEY_DELETE, KEY_RIGHT = GLFW.KEY_RIGHT, KEY_LEFT = GLFW.KEY_LEFT, KEY_DOWN = GLFW.KEY_DOWN, KEY_UP = GLFW.KEY_UP, KEY_PAGE_UP = GLFW.KEY_PAGE_UP, KEY_PAGE_DOWN = GLFW.KEY_PAGE_DOWN, KEY_HOME = GLFW.KEY_HOME, KEY_END = GLFW.KEY_END, KEY_CAPS_LOCK = GLFW.KEY_CAPS_LOCK, KEY_SCROLL_LOCK = GLFW.KEY_SCROLL_LOCK, KEY_NUM_LOCK = GLFW.KEY_NUM_LOCK, KEY_PRINT_SCREEN = GLFW.KEY_PRINT_SCREEN, KEY_PAUSE = GLFW.KEY_PAUSE, KEY_F1 = GLFW.KEY_F1, KEY_F2 = GLFW.KEY_F2, KEY_F3 = GLFW.KEY_F3, KEY_F4 = GLFW.KEY_F4, KEY_F5 = GLFW.KEY_F5, KEY_F6 = GLFW.KEY_F6, KEY_F7 = GLFW.KEY_F7, KEY_F8 = GLFW.KEY_F8, KEY_F9 = GLFW.KEY_F9, KEY_F10 = GLFW.KEY_F10, KEY_F11 = GLFW.KEY_F11, KEY_F12 = GLFW.KEY_F12, KEY_F13 = GLFW.KEY_F13, KEY_F14 = GLFW.KEY_F14, KEY_F15 = GLFW.KEY_F15, KEY_F16 = GLFW.KEY_F16, KEY_F17 = GLFW.KEY_F17, KEY_F18 = GLFW.KEY_F18, KEY_F19 = GLFW.KEY_F19, KEY_F20 = GLFW.KEY_F20, KEY_F21 = GLFW.KEY_F21, KEY_F22 = GLFW.KEY_F22, KEY_F23 = GLFW.KEY_F23, KEY_F24 = GLFW.KEY_F24, KEY_F25 = GLFW.KEY_F25, KEY_KP_0 = GLFW.KEY_KP_0, KEY_KP_1 = GLFW.KEY_KP_1, KEY_KP_2 = GLFW.KEY_KP_2, KEY_KP_3 = GLFW.KEY_KP_3, KEY_KP_4 = GLFW.KEY_KP_4, KEY_KP_5 = GLFW.KEY_KP_5, KEY_KP_6 = GLFW.KEY_KP_6, KEY_KP_7 = GLFW.KEY_KP_7, KEY_KP_8 = GLFW.KEY_KP_8, KEY_KP_9 = GLFW.KEY_KP_9, KEY_KP_DECIMAL = GLFW.KEY_KP_DECIMAL, KEY_KP_DIVIDE = GLFW.KEY_KP_DIVIDE, KEY_KP_MULTIPLY = GLFW.KEY_KP_MULTIPLY, KEY_KP_SUBTRACT = GLFW.KEY_KP_SUBTRACT, KEY_KP_ADD = GLFW.KEY_KP_ADD, KEY_KP_ENTER = GLFW.KEY_KP_ENTER, KEY_KP_EQUAL = GLFW.KEY_KP_EQUAL, KEY_LEFT_SHIFT = GLFW.KEY_LEFT_SHIFT, KEY_LEFT_CONTROL = GLFW.KEY_LEFT_CONTROL, KEY_LEFT_ALT = GLFW.KEY_LEFT_ALT, KEY_LEFT_SUPER = GLFW.KEY_LEFT_SUPER, KEY_RIGHT_SHIFT = GLFW.KEY_RIGHT_SHIFT, KEY_RIGHT_CONTROL = GLFW.KEY_RIGHT_CONTROL, KEY_RIGHT_ALT = GLFW.KEY_RIGHT_ALT, KEY_RIGHT_SUPER = GLFW.KEY_RIGHT_SUPER, KEY_MENU = GLFW.KEY_MENU, KEY_LAST = GLFW.KEY_LAST, }
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/src/monitor.cpp
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "glfw.hpp" #include "macros.hpp" #include "napi.h" #include <algorithm> #include <map> #include <nv_node/utilities/args.hpp> #include <nv_node/utilities/cpp_to_napi.hpp> namespace nv { // GLFWAPI GLFWmonitor** glfwGetMonitors(int* count); Napi::Value glfwGetMonitors(Napi::CallbackInfo const& info) { int32_t count{}; GLFWAPI::GLFWmonitor** mons = GLFWAPI::glfwGetMonitors(&count); return CPPToNapi(info)(std::vector<GLFWAPI::GLFWmonitor*>{mons, mons + count}); } // GLFWAPI GLFWmonitor* glfwGetPrimaryMonitor(void); Napi::Value glfwGetPrimaryMonitor(Napi::CallbackInfo const& info) { return CPPToNapi(info)(GLFWAPI::glfwGetPrimaryMonitor()); } // GLFWAPI void glfwGetMonitorPos(GLFWmonitor* monitor, int* xpos, int* ypos); Napi::Value glfwGetMonitorPos(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; int32_t x{}, y{}; GLFW_TRY(env, GLFWAPI::glfwGetMonitorPos(args[0], &x, &y)); return CPPToNapi(info)(std::map<std::string, int32_t>{// {"x", x}, {"y", y}}); } // GLFWAPI void glfwGetMonitorWorkarea(GLFWmonitor* monitor, int* xpos, int* ypos, int* width, int* // height); Napi::Value glfwGetMonitorWorkarea(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; int32_t x{}, y{}, width{}, height{}; GLFW_TRY(env, GLFWAPI::glfwGetMonitorWorkarea(args[0], &x, &y, &width, &height)); return CPPToNapi(info)(std::map<std::string, int32_t>{// {"x", x}, {"y", y}, {"width", width}, {"height", height}}); } // GLFWAPI void glfwGetMonitorPhysicalSize(GLFWmonitor* monitor, int* widthMM, int* heightMM); Napi::Value glfwGetMonitorPhysicalSize(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; int32_t width{}, height{}; GLFW_TRY(env, GLFWAPI::glfwGetMonitorPhysicalSize(args[0], &width, &height)); return CPPToNapi(info)(std::map<std::string, int32_t>{// {"width", width}, {"height", height}}); } // GLFWAPI void glfwGetMonitorContentScale(GLFWmonitor* monitor, float* xscale, float* yscale); Napi::Value glfwGetMonitorContentScale(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; float xscale{}, yscale{}; GLFW_TRY(env, GLFWAPI::glfwGetMonitorContentScale(args[0], &xscale, &yscale)); return CPPToNapi(info)(std::map<std::string, int32_t>{// {"xscale", xscale}, {"yscale", yscale}}); } // GLFWAPI const char* glfwGetMonitorName(GLFWmonitor* monitor); Napi::Value glfwGetMonitorName(Napi::CallbackInfo const& info) { CallbackArgs args{info}; auto name = GLFWAPI::glfwGetMonitorName(args[0]); return CPPToNapi(info)(std::string{name == nullptr ? name : ""}); } // GLFWAPI void glfwSetMonitorUserPointer(GLFWmonitor* monitor, void* pointer); // Napi::Value glfwSetMonitorUserPointer(Napi::CallbackInfo const& info); // GLFWAPI void* glfwGetMonitorUserPointer(GLFWmonitor* monitor); // Napi::Value glfwGetMonitorUserPointer(Napi::CallbackInfo const& info); // GLFWAPI const GLFWvidmode* glfwGetVideoModes(GLFWmonitor* monitor, int* count); Napi::Value glfwGetVideoModes(Napi::CallbackInfo const& info) { CallbackArgs args{info}; int32_t count{}; auto modes = GLFWAPI::glfwGetVideoModes(args[0], &count); std::vector<Napi::Object> modes_vec(count); int32_t i{0}; std::generate_n(modes_vec.begin(), count, [&]() mutable { GLFWvidmode mode = modes[i++]; return CPPToNapi(info)(std::map<std::string, int>{ {"width", mode.width}, {"height", mode.height}, {"redBits", mode.redBits}, {"greenBits", mode.greenBits}, {"blueBits", mode.blueBits}, {"refreshRate", mode.refreshRate}, }); }); return CPPToNapi(info)(modes_vec); } // GLFWAPI const GLFWvidmode* glfwGetVideoMode(GLFWmonitor* monitor); Napi::Value glfwGetVideoMode(Napi::CallbackInfo const& info) { CallbackArgs args{info}; auto mode = GLFWAPI::glfwGetVideoMode(args[0]); return CPPToNapi(info)(std::map<std::string, int>{ {"width", mode->width}, {"height", mode->height}, {"redBits", mode->redBits}, {"greenBits", mode->greenBits}, {"blueBits", mode->blueBits}, {"refreshRate", mode->refreshRate}, }); } // GLFWAPI void glfwSetGamma(GLFWmonitor* monitor, float gamma); void glfwSetGamma(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwSetGamma(args[0], args[1])); } // GLFWAPI const GLFWgammaramp* glfwGetGammaRamp(GLFWmonitor* monitor); Napi::Value glfwGetGammaRamp(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; auto ramp = GLFWAPI::glfwGetGammaRamp(args[0]); size_t size = ramp->size; auto js_ramp = Napi::Object::New(env); js_ramp.Set("size", CPPToNapi(info)(ramp->size)); js_ramp.Set("red", CPPToNapi(info)(std::make_tuple(ramp->red, size))); js_ramp.Set("green", CPPToNapi(info)(std::make_tuple(ramp->green, size))); js_ramp.Set("blue", CPPToNapi(info)(std::make_tuple(ramp->blue, size))); return js_ramp; } // GLFWAPI void glfwSetGammaRamp(GLFWmonitor* monitor, const GLFWgammaramp* ramp); void glfwSetGammaRamp(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFWmonitor* monitor = args[0]; Napi::Object js_ramp = args[1]; unsigned int size = NapiToCPP(js_ramp.Get("size")); unsigned short* red = NapiToCPP(js_ramp.Get("red")); unsigned short* green = NapiToCPP(js_ramp.Get("green")); unsigned short* blue = NapiToCPP(js_ramp.Get("blue")); GLFWgammaramp ramp{red, green, blue, size}; GLFW_TRY(env, GLFWAPI::glfwSetGammaRamp(monitor, &ramp)); } } // namespace nv
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/src/joystick.cpp
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "glfw.hpp" #include "macros.hpp" #include "napi.h" #include <nv_node/utilities/args.hpp> #include <nv_node/utilities/cpp_to_napi.hpp> namespace nv { // GLFWAPI int glfwJoystickPresent(int jid); Napi::Value glfwJoystickPresent(Napi::CallbackInfo const& info) { CallbackArgs args{info}; auto present = GLFWAPI::glfwJoystickPresent(args[0]); return CPPToNapi(info)(static_cast<bool>(present)); } // GLFWAPI const float* glfwGetJoystickAxes(int jid, int* count); Napi::Value glfwGetJoystickAxes(Napi::CallbackInfo const& info) { CallbackArgs args{info}; int32_t count{}; float const* axes = GLFWAPI::glfwGetJoystickAxes(args[0], &count); return CPPToNapi(info)(std::vector<float>{axes, axes + count}); } // GLFWAPI const unsigned char* glfwGetJoystickButtons(int jid, int* count); Napi::Value glfwGetJoystickButtons(Napi::CallbackInfo const& info) { CallbackArgs args{info}; int32_t count{}; uint8_t const* btns = GLFWAPI::glfwGetJoystickButtons(args[0], &count); return CPPToNapi(info)(std::vector<uint8_t>{btns, btns + count}); } // GLFWAPI const unsigned char* glfwGetJoystickHats(int jid, int* count); Napi::Value glfwGetJoystickHats(Napi::CallbackInfo const& info) { CallbackArgs args{info}; int32_t count{}; uint8_t const* hats = GLFWAPI::glfwGetJoystickHats(args[0], &count); return CPPToNapi(info)(std::vector<uint8_t>{hats, hats + count}); } // GLFWAPI const char* glfwGetJoystickName(int jid); Napi::Value glfwGetJoystickName(Napi::CallbackInfo const& info) { CallbackArgs args{info}; auto name = GLFWAPI::glfwGetJoystickName(args[0]); return CPPToNapi(info)(std::string{name == nullptr ? name : ""}); } // GLFWAPI const char* glfwGetJoystickGUID(int jid); Napi::Value glfwGetJoystickGUID(Napi::CallbackInfo const& info) { CallbackArgs args{info}; auto guid = GLFWAPI::glfwGetJoystickGUID(args[0]); return CPPToNapi(info)(std::string{guid == nullptr ? guid : ""}); } // GLFWAPI void glfwSetJoystickUserPointer(int jid, void* pointer); // Napi::Value glfwSetJoystickUserPointer(Napi::CallbackInfo const& info); // GLFWAPI void* glfwGetJoystickUserPointer(int jid); // Napi::Value glfwGetJoystickUserPointer(Napi::CallbackInfo const& info); // GLFWAPI int glfwJoystickIsGamepad(int jid); Napi::Value glfwJoystickIsGamepad(Napi::CallbackInfo const& info) { CallbackArgs args{info}; auto is_gamepad = GLFWAPI::glfwJoystickIsGamepad(args[0]); return CPPToNapi(info)(static_cast<bool>(is_gamepad)); } // GLFWAPI int glfwUpdateGamepadMappings(const char* string); void glfwUpdateGamepadMappings(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; std::string mappings = args[0]; GLFW_TRY(env, GLFWAPI::glfwUpdateGamepadMappings(mappings.data())); } // GLFWAPI const char* glfwGetGamepadName(int jid); Napi::Value glfwGetGamepadName(Napi::CallbackInfo const& info) { CallbackArgs args{info}; auto name = GLFWAPI::glfwGetGamepadName(args[0]); return CPPToNapi(info)(std::string{name == nullptr ? name : ""}); } // GLFWAPI int glfwGetGamepadState(int jid, GLFWgamepadstate* state); Napi::Value glfwGetGamepadState(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFWAPI::GLFWgamepadstate state{}; GLFW_TRY(env, GLFWAPI::glfwGetGamepadState(args[0], &state)); std::vector<float> axes; axes.reserve(sizeof(state.axes)); axes.insert(axes.begin(), state.axes, state.axes + 6); std::vector<unsigned char> buttons; buttons.reserve(sizeof(state.buttons)); buttons.insert(buttons.begin(), state.buttons, state.buttons + 15); auto js_state = Napi::Object::New(env); js_state.Set("axes", CPPToNapi(env)(axes)); js_state.Set("buttons", CPPToNapi(env)(buttons)); return js_state; } } // namespace nv
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/src/addon.hpp
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <napi.h> #include "glfw.hpp" namespace nv { // GLFWAPI int glfwInit(void); Napi::Value glfwInit(Napi::CallbackInfo const& info); // GLFWAPI void glfwTerminate(void); void glfwTerminate(Napi::CallbackInfo const& info); // GLFWAPI void glfwInitHint(int hint, int value); void glfwInitHint(Napi::CallbackInfo const& info); // GLFWAPI void glfwGetVersion(int* major, int* minor, int* rev); Napi::Value glfwGetVersion(Napi::CallbackInfo const& info); // GLFWAPI const char* glfwGetVersionString(void); Napi::Value glfwGetVersionString(Napi::CallbackInfo const& info); // GLFWAPI int glfwGetError(const char** description); Napi::Value glfwGetError(Napi::CallbackInfo const& info); // GLFWAPI GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun callback); void glfwSetErrorCallback(Napi::CallbackInfo const& info); // GLFWAPI GLFWmonitor** glfwGetMonitors(int* count); Napi::Value glfwGetMonitors(Napi::CallbackInfo const& info); // GLFWAPI GLFWmonitor* glfwGetPrimaryMonitor(void); Napi::Value glfwGetPrimaryMonitor(Napi::CallbackInfo const& info); // GLFWAPI void glfwGetMonitorPos(GLFWmonitor* monitor, int* xpos, int* ypos); Napi::Value glfwGetMonitorPos(Napi::CallbackInfo const& info); // GLFWAPI void glfwGetMonitorWorkarea(GLFWmonitor* monitor, int* xpos, int* ypos, int* width, int* // height); Napi::Value glfwGetMonitorWorkarea(Napi::CallbackInfo const& info); // GLFWAPI void glfwGetMonitorPhysicalSize(GLFWmonitor* monitor, int* widthMM, int* heightMM); Napi::Value glfwGetMonitorPhysicalSize(Napi::CallbackInfo const& info); // GLFWAPI void glfwGetMonitorContentScale(GLFWmonitor* monitor, float* xscale, float* yscale); Napi::Value glfwGetMonitorContentScale(Napi::CallbackInfo const& info); // GLFWAPI const char* glfwGetMonitorName(GLFWmonitor* monitor); Napi::Value glfwGetMonitorName(Napi::CallbackInfo const& info); // // GLFWAPI void glfwSetMonitorUserPointer(GLFWmonitor* monitor, void* pointer); // void glfwSetMonitorUserPointer(Napi::CallbackInfo const& info); // // GLFWAPI void* glfwGetMonitorUserPointer(GLFWmonitor* monitor); // Napi::Value glfwGetMonitorUserPointer(Napi::CallbackInfo const& info); // GLFWAPI GLFWmonitorfun glfwSetMonitorCallback(GLFWmonitorfun callback); void glfwSetMonitorCallback(Napi::CallbackInfo const& info); // GLFWAPI const GLFWvidmode* glfwGetVideoModes(GLFWmonitor* monitor, int* count); Napi::Value glfwGetVideoModes(Napi::CallbackInfo const& info); // GLFWAPI const GLFWvidmode* glfwGetVideoMode(GLFWmonitor* monitor); Napi::Value glfwGetVideoMode(Napi::CallbackInfo const& info); // GLFWAPI void glfwSetGamma(GLFWmonitor* monitor, float gamma); void glfwSetGamma(Napi::CallbackInfo const& info); // GLFWAPI const GLFWgammaramp* glfwGetGammaRamp(GLFWmonitor* monitor); Napi::Value glfwGetGammaRamp(Napi::CallbackInfo const& info); // GLFWAPI void glfwSetGammaRamp(GLFWmonitor* monitor, const GLFWgammaramp* ramp); void glfwSetGammaRamp(Napi::CallbackInfo const& info); // GLFWAPI void glfwDefaultWindowHints(void); Napi::Value glfwDefaultWindowHints(Napi::CallbackInfo const& info); // GLFWAPI void glfwWindowHint(int hint, int value); Napi::Value glfwWindowHint(Napi::CallbackInfo const& info); // GLFWAPI void glfwWindowHintString(int hint, const char* value); Napi::Value glfwWindowHintString(Napi::CallbackInfo const& info); // GLFWAPI GLFWwindow* glfwCreateWindow(int width, int height, const char* title, GLFWmonitor* // monitor, GLFWwindow* share); Napi::Value glfwCreateWindow(Napi::CallbackInfo const& info); // #ifdef __linux__ // // void glfwReparentWindow(GLFWwindow* window); // Napi::Value glfwReparentWindow(Napi::CallbackInfo const& info); // #endif // GLFWAPI void glfwDestroyWindow(GLFWwindow* window); Napi::Value glfwDestroyWindow(Napi::CallbackInfo const& info); // GLFWAPI int glfwWindowShouldClose(GLFWwindow* window); Napi::Value glfwWindowShouldClose(Napi::CallbackInfo const& info); // GLFWAPI void glfwSetWindowShouldClose(GLFWwindow* window, int value); void glfwSetWindowShouldClose(Napi::CallbackInfo const& info); // GLFWAPI void glfwSetWindowTitle(GLFWwindow* window, const char* title); void glfwSetWindowTitle(Napi::CallbackInfo const& info); // GLFWAPI void glfwSetWindowIcon(GLFWwindow* window, int count, const GLFWimage* images); void glfwSetWindowIcon(Napi::CallbackInfo const& info); // GLFWAPI void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos); Napi::Value glfwGetWindowPos(Napi::CallbackInfo const& info); // GLFWAPI void glfwSetWindowPos(GLFWwindow* window, int xpos, int ypos); void glfwSetWindowPos(Napi::CallbackInfo const& info); // GLFWAPI void glfwGetWindowSize(GLFWwindow* window, int* width, int* height); Napi::Value glfwGetWindowSize(Napi::CallbackInfo const& info); // GLFWAPI void glfwSetWindowSizeLimits(GLFWwindow* window, int minwidth, int minheight, int // maxwidth, int maxheight); void glfwSetWindowSizeLimits(Napi::CallbackInfo const& info); // GLFWAPI void glfwSetWindowAspectRatio(GLFWwindow* window, int numer, int denom); void glfwSetWindowAspectRatio(Napi::CallbackInfo const& info); // GLFWAPI void glfwSetWindowSize(GLFWwindow* window, int width, int height); void glfwSetWindowSize(Napi::CallbackInfo const& info); // GLFWAPI void glfwGetFramebufferSize(GLFWwindow* window, int* width, int* height); Napi::Value glfwGetFramebufferSize(Napi::CallbackInfo const& info); // GLFWAPI void glfwGetWindowFrameSize(GLFWwindow* window, int* left, int* top, int* right, int* // bottom); Napi::Value glfwGetWindowFrameSize(Napi::CallbackInfo const& info); // GLFWAPI void glfwGetWindowContentScale(GLFWwindow* window, float* xscale, float* yscale); Napi::Value glfwGetWindowContentScale(Napi::CallbackInfo const& info); // GLFWAPI float glfwGetWindowOpacity(GLFWwindow* window); Napi::Value glfwGetWindowOpacity(Napi::CallbackInfo const& info); // GLFWAPI void glfwSetWindowOpacity(GLFWwindow* window, float opacity); void glfwSetWindowOpacity(Napi::CallbackInfo const& info); // GLFWAPI void glfwIconifyWindow(GLFWwindow* window); Napi::Value glfwIconifyWindow(Napi::CallbackInfo const& info); // GLFWAPI void glfwRestoreWindow(GLFWwindow* window); Napi::Value glfwRestoreWindow(Napi::CallbackInfo const& info); // GLFWAPI void glfwMaximizeWindow(GLFWwindow* window); Napi::Value glfwMaximizeWindow(Napi::CallbackInfo const& info); // GLFWAPI void glfwShowWindow(GLFWwindow* window); Napi::Value glfwShowWindow(Napi::CallbackInfo const& info); // GLFWAPI void glfwHideWindow(GLFWwindow* window); Napi::Value glfwHideWindow(Napi::CallbackInfo const& info); // GLFWAPI void glfwFocusWindow(GLFWwindow* window); Napi::Value glfwFocusWindow(Napi::CallbackInfo const& info); // GLFWAPI void glfwRequestWindowAttention(GLFWwindow* window); Napi::Value glfwRequestWindowAttention(Napi::CallbackInfo const& info); // GLFWAPI GLFWmonitor* glfwGetWindowMonitor(GLFWwindow* window); Napi::Value glfwGetWindowMonitor(Napi::CallbackInfo const& info); // GLFWAPI void glfwSetWindowMonitor(GLFWwindow* window, GLFWmonitor* monitor, int xpos, int ypos, // int width, int height, int refreshRate); void glfwSetWindowMonitor(Napi::CallbackInfo const& info); // GLFWAPI int glfwGetWindowAttrib(GLFWwindow* window, int attrib); Napi::Value glfwGetWindowAttrib(Napi::CallbackInfo const& info); // GLFWAPI void glfwSetWindowAttrib(GLFWwindow* window, int attrib, int value); void glfwSetWindowAttrib(Napi::CallbackInfo const& info); // GLFWAPI void glfwSetWindowUserPointer(GLFWwindow* window, void* pointer); // void glfwSetWindowUserPointer(Napi::CallbackInfo const& info); // GLFWAPI void* glfwGetWindowUserPointer(GLFWwindow* window); // Napi::Value glfwGetWindowUserPointer(Napi::CallbackInfo const& info); // GLFWAPI GLFWwindowposfun glfwSetWindowPosCallback(GLFWwindow* window, GLFWwindowposfun callback); void glfwSetWindowPosCallback(Napi::CallbackInfo const& info); // GLFWAPI GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun // callback); void glfwSetWindowSizeCallback(Napi::CallbackInfo const& info); // GLFWAPI GLFWwindowclosefun glfwSetWindowCloseCallback(GLFWwindow* window, GLFWwindowclosefun // callback); void glfwSetWindowCloseCallback(Napi::CallbackInfo const& info); // GLFWAPI GLFWwindowrefreshfun glfwSetWindowRefreshCallback(GLFWwindow* window, // GLFWwindowrefreshfun callback); void glfwSetWindowRefreshCallback(Napi::CallbackInfo const& info); // GLFWAPI GLFWwindowfocusfun glfwSetWindowFocusCallback(GLFWwindow* window, GLFWwindowfocusfun // callback); void glfwSetWindowFocusCallback(Napi::CallbackInfo const& info); // GLFWAPI GLFWwindowiconifyfun glfwSetWindowIconifyCallback(GLFWwindow* window, // GLFWwindowiconifyfun callback); void glfwSetWindowIconifyCallback(Napi::CallbackInfo const& info); // GLFWAPI GLFWwindowmaximizefun glfwSetWindowMaximizeCallback(GLFWwindow* window, // GLFWwindowmaximizefun callback); void glfwSetWindowMaximizeCallback(Napi::CallbackInfo const& info); // GLFWAPI GLFWframebuffersizefun glfwSetFramebufferSizeCallback(GLFWwindow* window, // GLFWframebuffersizefun callback); void glfwSetFramebufferSizeCallback(Napi::CallbackInfo const& info); // GLFWAPI GLFWwindowcontentscalefun glfwSetWindowContentScaleCallback(GLFWwindow* window, // GLFWwindowcontentscalefun callback); void glfwSetWindowContentScaleCallback(Napi::CallbackInfo const& info); // GLFWAPI void glfwPollEvents(void); void glfwPollEvents(Napi::CallbackInfo const& info); // GLFWAPI void glfwWaitEvents(void); void glfwWaitEvents(Napi::CallbackInfo const& info); // GLFWAPI void glfwWaitEventsTimeout(double timeout); void glfwWaitEventsTimeout(Napi::CallbackInfo const& info); // GLFWAPI void glfwPostEmptyEvent(void); void glfwPostEmptyEvent(Napi::CallbackInfo const& info); // GLFWAPI int glfwGetInputMode(GLFWwindow* window, int mode); Napi::Value glfwGetInputMode(Napi::CallbackInfo const& info); // GLFWAPI void glfwSetInputMode(GLFWwindow* window, int mode, int value); void glfwSetInputMode(Napi::CallbackInfo const& info); // GLFWAPI int glfwRawMouseMotionSupported(void); Napi::Value glfwRawMouseMotionSupported(Napi::CallbackInfo const& info); // GLFWAPI const char* glfwGetKeyName(int key, int scancode); Napi::Value glfwGetKeyName(Napi::CallbackInfo const& info); // GLFWAPI int glfwGetKeyScancode(int key); Napi::Value glfwGetKeyScancode(Napi::CallbackInfo const& info); // GLFWAPI int glfwGetKey(GLFWwindow* window, int key); Napi::Value glfwGetKey(Napi::CallbackInfo const& info); // GLFWAPI int glfwGetMouseButton(GLFWwindow* window, int button); Napi::Value glfwGetMouseButton(Napi::CallbackInfo const& info); // GLFWAPI void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos); Napi::Value glfwGetCursorPos(Napi::CallbackInfo const& info); // GLFWAPI void glfwSetCursorPos(GLFWwindow* window, double xpos, double ypos); void glfwSetCursorPos(Napi::CallbackInfo const& info); // GLFWAPI GLFWcursor* glfwCreateCursor(const GLFWimage* image, int xhot, int yhot); Napi::Value glfwCreateCursor(Napi::CallbackInfo const& info); // GLFWAPI GLFWcursor* glfwCreateStandardCursor(int shape); Napi::Value glfwCreateStandardCursor(Napi::CallbackInfo const& info); // GLFWAPI void glfwDestroyCursor(GLFWcursor* cursor); void glfwDestroyCursor(Napi::CallbackInfo const& info); // GLFWAPI void glfwSetCursor(GLFWwindow* window, GLFWcursor* cursor); void glfwSetCursor(Napi::CallbackInfo const& info); // GLFWAPI GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun callback); void glfwSetKeyCallback(Napi::CallbackInfo const& info); // GLFWAPI GLFWcharfun glfwSetCharCallback(GLFWwindow* window, GLFWcharfun callback); void glfwSetCharCallback(Napi::CallbackInfo const& info); // GLFWAPI GLFWcharmodsfun glfwSetCharModsCallback(GLFWwindow* window, GLFWcharmodsfun callback); void glfwSetCharModsCallback(Napi::CallbackInfo const& info); // GLFWAPI GLFWmousebuttonfun glfwSetMouseButtonCallback(GLFWwindow* window, GLFWmousebuttonfun // callback); void glfwSetMouseButtonCallback(Napi::CallbackInfo const& info); // GLFWAPI GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun callback); void glfwSetCursorPosCallback(Napi::CallbackInfo const& info); // GLFWAPI GLFWcursorenterfun glfwSetCursorEnterCallback(GLFWwindow* window, GLFWcursorenterfun // callback); void glfwSetCursorEnterCallback(Napi::CallbackInfo const& info); // GLFWAPI GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun callback); void glfwSetScrollCallback(Napi::CallbackInfo const& info); // GLFWAPI GLFWdropfun glfwSetDropCallback(GLFWwindow* window, GLFWdropfun callback); void glfwSetDropCallback(Napi::CallbackInfo const& info); // GLFWAPI int glfwJoystickPresent(int jid); Napi::Value glfwJoystickPresent(Napi::CallbackInfo const& info); // GLFWAPI const float* glfwGetJoystickAxes(int jid, int* count); Napi::Value glfwGetJoystickAxes(Napi::CallbackInfo const& info); // GLFWAPI const unsigned char* glfwGetJoystickButtons(int jid, int* count); Napi::Value glfwGetJoystickButtons(Napi::CallbackInfo const& info); // GLFWAPI const unsigned char* glfwGetJoystickHats(int jid, int* count); Napi::Value glfwGetJoystickHats(Napi::CallbackInfo const& info); // GLFWAPI const char* glfwGetJoystickName(int jid); Napi::Value glfwGetJoystickName(Napi::CallbackInfo const& info); // GLFWAPI const char* glfwGetJoystickGUID(int jid); Napi::Value glfwGetJoystickGUID(Napi::CallbackInfo const& info); // // GLFWAPI void glfwSetJoystickUserPointer(int jid, void* pointer); // void glfwSetJoystickUserPointer(Napi::CallbackInfo const& info); // // GLFWAPI void* glfwGetJoystickUserPointer(int jid); // Napi::Value glfwGetJoystickUserPointer(Napi::CallbackInfo const& info); // GLFWAPI int glfwJoystickIsGamepad(int jid); Napi::Value glfwJoystickIsGamepad(Napi::CallbackInfo const& info); // GLFWAPI GLFWjoystickfun glfwSetJoystickCallback(GLFWjoystickfun callback); void glfwSetJoystickCallback(Napi::CallbackInfo const& info); // GLFWAPI int glfwUpdateGamepadMappings(const char* string); void glfwUpdateGamepadMappings(Napi::CallbackInfo const& info); // GLFWAPI const char* glfwGetGamepadName(int jid); Napi::Value glfwGetGamepadName(Napi::CallbackInfo const& info); // GLFWAPI int glfwGetGamepadState(int jid, GLFWgamepadstate* state); Napi::Value glfwGetGamepadState(Napi::CallbackInfo const& info); // GLFWAPI void glfwSetClipboardString(GLFWwindow* window, const char* string); void glfwSetClipboardString(Napi::CallbackInfo const& info); // GLFWAPI const char* glfwGetClipboardString(GLFWwindow* window); Napi::Value glfwGetClipboardString(Napi::CallbackInfo const& info); // GLFWAPI double glfwGetTime(void); Napi::Value glfwGetTime(Napi::CallbackInfo const& info); // GLFWAPI void glfwSetTime(double time); void glfwSetTime(Napi::CallbackInfo const& info); // GLFWAPI uint64_t glfwGetTimerValue(void); Napi::Value glfwGetTimerValue(Napi::CallbackInfo const& info); // GLFWAPI uint64_t glfwGetTimerFrequency(void); Napi::Value glfwGetTimerFrequency(Napi::CallbackInfo const& info); // GLFWAPI void glfwMakeContextCurrent(GLFWwindow* window); void glfwMakeContextCurrent(Napi::CallbackInfo const& info); // GLFWAPI GLFWwindow* glfwGetCurrentContext(void); Napi::Value glfwGetCurrentContext(Napi::CallbackInfo const& info); // GLFWAPI void glfwSwapBuffers(GLFWwindow* window); void glfwSwapBuffers(Napi::CallbackInfo const& info); // GLFWAPI void glfwSwapInterval(int interval); void glfwSwapInterval(Napi::CallbackInfo const& info); // GLFWAPI int glfwExtensionSupported(const char* extension); Napi::Value glfwExtensionSupported(Napi::CallbackInfo const& info); // GLFWAPI GLFWglproc glfwGetProcAddress(const char* procname); Napi::Value glfwGetProcAddress(Napi::CallbackInfo const& info); // GLFWAPI int glfwVulkanSupported(void); Napi::Value glfwVulkanSupported(Napi::CallbackInfo const& info); // GLFWAPI const char** glfwGetRequiredInstanceExtensions(uint32_t* count); Napi::Value glfwGetRequiredInstanceExtensions(Napi::CallbackInfo const& info); // TODO: // #if defined(VK_VERSION_1_0) // // GLFWAPI GLFWvkproc glfwGetInstanceProcAddress(VkInstance instance, const char* procname); // Napi::Value glfwGetInstanceProcAddress(Napi::CallbackInfo const& info); // // GLFWAPI int glfwGetPhysicalDevicePresentationSupport(VkInstance instance, VkPhysicalDevice // device, uint32_t // // queuefamily); // Napi::Value glfwGetPhysicalDevicePresentationSupport(Napi::CallbackInfo const& info); // // GLFWAPI VkResult glfwCreateWindowSurface(VkInstance instance, GLFWwindow* window, const // VkAllocationCallbacks* // // allocator, VkSurfaceKHR* surface); // Napi::Value glfwCreateWindowSurface(Napi::CallbackInfo const& info); // #endif } // namespace nv
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/src/addon.cpp
// Copyright (c) 2020-2022, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "addon.hpp" #include "glfw.hpp" #include "macros.hpp" #include <nv_node/utilities/args.hpp> #include <nv_node/utilities/cpp_to_napi.hpp> namespace nv { // GLFWAPI int glfwInit(void); Napi::Value glfwInit(Napi::CallbackInfo const& info) { auto env = info.Env(); GLFW_EXPECT_TRUE(env, GLFWAPI::glfwInit()); return info.This(); } // GLFWAPI void glfwTerminate(void); void glfwTerminate(Napi::CallbackInfo const& info) { auto env = info.Env(); GLFW_TRY(env, GLFWAPI::glfwTerminate()); } // GLFWAPI void glfwInitHint(int hint, int value); void glfwInitHint(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwInitHint(args[0], args[1])); } // GLFWAPI void glfwGetVersion(int* major, int* minor, int* rev); Napi::Value glfwGetVersion(Napi::CallbackInfo const& info) { auto env = info.Env(); int32_t major{}, minor{}, rev{}; GLFW_TRY(env, GLFWAPI::glfwGetVersion(&major, &minor, &rev)); return CPPToNapi(info)(std::map<std::string, int32_t>{// {"major", major}, {"minor", minor}, {"rev", rev}}); } // GLFWAPI const char* glfwGetVersionString(void); Napi::Value glfwGetVersionString(Napi::CallbackInfo const& info) { auto version = GLFWAPI::glfwGetVersionString(); return CPPToNapi(info)(std::string{version == nullptr ? "" : version}); } // GLFWAPI int glfwGetError(const char** description); Napi::Value glfwGetError(Napi::CallbackInfo const& info) { auto env = info.Env(); const char* err = nullptr; const int code = GLFWAPI::glfwGetError(&err); if (code == GLFW_NO_ERROR) { return env.Undefined(); } return nv::glfwError(env, code, err, __FILE__, __LINE__).Value(); } // GLFWAPI const char* glfwGetKeyName(int key, int scancode); Napi::Value glfwGetKeyName(Napi::CallbackInfo const& info) { CallbackArgs args{info}; auto name = GLFWAPI::glfwGetKeyName(args[0], args[1]); return CPPToNapi(info)(std::string{name == nullptr ? "" : name}); } // GLFWAPI int glfwGetKeyScancode(int key); Napi::Value glfwGetKeyScancode(Napi::CallbackInfo const& info) { CallbackArgs args{info}; return CPPToNapi(info)(GLFWAPI::glfwGetKeyScancode(args[0])); } // GLFWAPI double glfwGetTime(void); Napi::Value glfwGetTime(Napi::CallbackInfo const& info) { return CPPToNapi(info)(GLFWAPI::glfwGetTime()); } // GLFWAPI void glfwSetTime(double time); void glfwSetTime(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwSetTime(args[0])); } // GLFWAPI uint64_t glfwGetTimerValue(void); Napi::Value glfwGetTimerValue(Napi::CallbackInfo const& info) { return CPPToNapi(info)(GLFWAPI::glfwGetTimerValue()); } // GLFWAPI uint64_t glfwGetTimerFrequency(void); Napi::Value glfwGetTimerFrequency(Napi::CallbackInfo const& info) { return CPPToNapi(info)(GLFWAPI::glfwGetTimerFrequency()); } // GLFWAPI void glfwSwapInterval(int interval); void glfwSwapInterval(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFW_TRY(env, GLFWAPI::glfwSwapInterval(args[0])); } // GLFWAPI int glfwExtensionSupported(const char* extension); Napi::Value glfwExtensionSupported(Napi::CallbackInfo const& info) { CallbackArgs args{info}; std::string extension = args[0]; auto is_extension_supported = GLFWAPI::glfwExtensionSupported(extension.data()); return CPPToNapi(info)(static_cast<bool>(is_extension_supported)); } // GLFWAPI GLFWglproc glfwGetProcAddress(const char* procname); Napi::Value glfwGetProcAddress(Napi::CallbackInfo const& info) { CallbackArgs args{info}; std::string name = args[0]; auto addr = GLFWAPI::glfwGetProcAddress(name.data()); return CPPToNapi(info)(reinterpret_cast<char*>(addr)); } // GLFWAPI const char** glfwGetRequiredInstanceExtensions(uint32_t* count); Napi::Value glfwGetRequiredInstanceExtensions(Napi::CallbackInfo const& info) { uint32_t count{}; const char** exts = GLFWAPI::glfwGetRequiredInstanceExtensions(&count); return CPPToNapi(info)(std::vector<std::string>{exts, exts + count}); } } // namespace nv Napi::Object initModule(Napi::Env env, Napi::Object exports) { EXPORT_FUNC(env, exports, "init", nv::glfwInit); EXPORT_FUNC(env, exports, "terminate", nv::glfwTerminate); EXPORT_FUNC(env, exports, "initHint", nv::glfwInitHint); EXPORT_FUNC(env, exports, "getVersion", nv::glfwGetVersion); EXPORT_FUNC(env, exports, "getVersionString", nv::glfwGetVersionString); EXPORT_FUNC(env, exports, "setErrorCallback", nv::glfwSetErrorCallback); EXPORT_FUNC(env, exports, "getMonitors", nv::glfwGetMonitors); EXPORT_FUNC(env, exports, "getPrimaryMonitor", nv::glfwGetPrimaryMonitor); EXPORT_FUNC(env, exports, "getMonitorPos", nv::glfwGetMonitorPos); EXPORT_FUNC(env, exports, "getMonitorWorkarea", nv::glfwGetMonitorWorkarea); EXPORT_FUNC(env, exports, "getMonitorPhysicalSize", nv::glfwGetMonitorPhysicalSize); EXPORT_FUNC(env, exports, "getMonitorContentScale", nv::glfwGetMonitorContentScale); EXPORT_FUNC(env, exports, "getMonitorName", nv::glfwGetMonitorName); EXPORT_FUNC(env, exports, "setMonitorCallback", nv::glfwSetMonitorCallback); EXPORT_FUNC(env, exports, "getVideoModes", nv::glfwGetVideoModes); EXPORT_FUNC(env, exports, "getVideoMode", nv::glfwGetVideoMode); EXPORT_FUNC(env, exports, "setGamma", nv::glfwSetGamma); EXPORT_FUNC(env, exports, "getGammaRamp", nv::glfwGetGammaRamp); EXPORT_FUNC(env, exports, "setGammaRamp", nv::glfwSetGammaRamp); EXPORT_FUNC(env, exports, "defaultWindowHints", nv::glfwDefaultWindowHints); EXPORT_FUNC(env, exports, "windowHint", nv::glfwWindowHint); EXPORT_FUNC(env, exports, "windowHintString", nv::glfwWindowHintString); EXPORT_FUNC(env, exports, "createWindow", nv::glfwCreateWindow); // #ifdef __linux__ // EXPORT_FUNC(env, exports, "reparentWindow", nv::glfwReparentWindow); // #endif EXPORT_FUNC(env, exports, "destroyWindow", nv::glfwDestroyWindow); EXPORT_FUNC(env, exports, "windowShouldClose", nv::glfwWindowShouldClose); EXPORT_FUNC(env, exports, "setWindowShouldClose", nv::glfwSetWindowShouldClose); EXPORT_FUNC(env, exports, "setWindowTitle", nv::glfwSetWindowTitle); EXPORT_FUNC(env, exports, "setWindowIcon", nv::glfwSetWindowIcon); EXPORT_FUNC(env, exports, "getWindowPos", nv::glfwGetWindowPos); EXPORT_FUNC(env, exports, "setWindowPos", nv::glfwSetWindowPos); EXPORT_FUNC(env, exports, "getWindowSize", nv::glfwGetWindowSize); EXPORT_FUNC(env, exports, "setWindowSizeLimits", nv::glfwSetWindowSizeLimits); EXPORT_FUNC(env, exports, "setWindowAspectRatio", nv::glfwSetWindowAspectRatio); EXPORT_FUNC(env, exports, "setWindowSize", nv::glfwSetWindowSize); EXPORT_FUNC(env, exports, "getFramebufferSize", nv::glfwGetFramebufferSize); EXPORT_FUNC(env, exports, "getWindowFrameSize", nv::glfwGetWindowFrameSize); EXPORT_FUNC(env, exports, "getWindowContentScale", nv::glfwGetWindowContentScale); EXPORT_FUNC(env, exports, "getWindowOpacity", nv::glfwGetWindowOpacity); EXPORT_FUNC(env, exports, "setWindowOpacity", nv::glfwSetWindowOpacity); EXPORT_FUNC(env, exports, "iconifyWindow", nv::glfwIconifyWindow); EXPORT_FUNC(env, exports, "restoreWindow", nv::glfwRestoreWindow); EXPORT_FUNC(env, exports, "maximizeWindow", nv::glfwMaximizeWindow); EXPORT_FUNC(env, exports, "showWindow", nv::glfwShowWindow); EXPORT_FUNC(env, exports, "hideWindow", nv::glfwHideWindow); EXPORT_FUNC(env, exports, "focusWindow", nv::glfwFocusWindow); EXPORT_FUNC(env, exports, "requestWindowAttention", nv::glfwRequestWindowAttention); EXPORT_FUNC(env, exports, "getWindowMonitor", nv::glfwGetWindowMonitor); EXPORT_FUNC(env, exports, "setWindowMonitor", nv::glfwSetWindowMonitor); EXPORT_FUNC(env, exports, "getWindowAttrib", nv::glfwGetWindowAttrib); EXPORT_FUNC(env, exports, "setWindowAttrib", nv::glfwSetWindowAttrib); EXPORT_FUNC(env, exports, "setWindowPosCallback", nv::glfwSetWindowPosCallback); EXPORT_FUNC(env, exports, "setWindowSizeCallback", nv::glfwSetWindowSizeCallback); EXPORT_FUNC(env, exports, "setWindowCloseCallback", nv::glfwSetWindowCloseCallback); EXPORT_FUNC(env, exports, "setWindowRefreshCallback", nv::glfwSetWindowRefreshCallback); EXPORT_FUNC(env, exports, "setWindowFocusCallback", nv::glfwSetWindowFocusCallback); EXPORT_FUNC(env, exports, "setWindowIconifyCallback", nv::glfwSetWindowIconifyCallback); EXPORT_FUNC(env, exports, "setWindowMaximizeCallback", nv::glfwSetWindowMaximizeCallback); EXPORT_FUNC(env, exports, "setFramebufferSizeCallback", nv::glfwSetFramebufferSizeCallback); EXPORT_FUNC(env, exports, "setWindowContentScaleCallback", nv::glfwSetWindowContentScaleCallback); EXPORT_FUNC(env, exports, "pollEvents", nv::glfwPollEvents); EXPORT_FUNC(env, exports, "waitEvents", nv::glfwWaitEvents); EXPORT_FUNC(env, exports, "waitEventsTimeout", nv::glfwWaitEventsTimeout); EXPORT_FUNC(env, exports, "postEmptyEvent", nv::glfwPostEmptyEvent); EXPORT_FUNC(env, exports, "getInputMode", nv::glfwGetInputMode); EXPORT_FUNC(env, exports, "setInputMode", nv::glfwSetInputMode); EXPORT_FUNC(env, exports, "rawMouseMotionSupported", nv::glfwRawMouseMotionSupported); EXPORT_FUNC(env, exports, "getKeyName", nv::glfwGetKeyName); EXPORT_FUNC(env, exports, "getKeyScancode", nv::glfwGetKeyScancode); EXPORT_FUNC(env, exports, "getKey", nv::glfwGetKey); EXPORT_FUNC(env, exports, "getMouseButton", nv::glfwGetMouseButton); EXPORT_FUNC(env, exports, "getCursorPos", nv::glfwGetCursorPos); EXPORT_FUNC(env, exports, "setCursorPos", nv::glfwSetCursorPos); EXPORT_FUNC(env, exports, "createCursor", nv::glfwCreateCursor); EXPORT_FUNC(env, exports, "createStandardCursor", nv::glfwCreateStandardCursor); EXPORT_FUNC(env, exports, "destroyCursor", nv::glfwDestroyCursor); EXPORT_FUNC(env, exports, "setCursor", nv::glfwSetCursor); EXPORT_FUNC(env, exports, "setKeyCallback", nv::glfwSetKeyCallback); EXPORT_FUNC(env, exports, "setCharCallback", nv::glfwSetCharCallback); EXPORT_FUNC(env, exports, "setCharModsCallback", nv::glfwSetCharModsCallback); EXPORT_FUNC(env, exports, "setMouseButtonCallback", nv::glfwSetMouseButtonCallback); EXPORT_FUNC(env, exports, "setCursorPosCallback", nv::glfwSetCursorPosCallback); EXPORT_FUNC(env, exports, "setCursorEnterCallback", nv::glfwSetCursorEnterCallback); EXPORT_FUNC(env, exports, "setScrollCallback", nv::glfwSetScrollCallback); EXPORT_FUNC(env, exports, "setDropCallback", nv::glfwSetDropCallback); EXPORT_FUNC(env, exports, "joystickPresent", nv::glfwJoystickPresent); EXPORT_FUNC(env, exports, "getJoystickAxes", nv::glfwGetJoystickAxes); EXPORT_FUNC(env, exports, "getJoystickButtons", nv::glfwGetJoystickButtons); EXPORT_FUNC(env, exports, "getJoystickHats", nv::glfwGetJoystickHats); EXPORT_FUNC(env, exports, "getJoystickName", nv::glfwGetJoystickName); EXPORT_FUNC(env, exports, "getJoystickGUID", nv::glfwGetJoystickGUID); EXPORT_FUNC(env, exports, "joystickIsGamepad", nv::glfwJoystickIsGamepad); EXPORT_FUNC(env, exports, "setJoystickCallback", nv::glfwSetJoystickCallback); EXPORT_FUNC(env, exports, "updateGamepadMappings", nv::glfwUpdateGamepadMappings); EXPORT_FUNC(env, exports, "getGamepadName", nv::glfwGetGamepadName); EXPORT_FUNC(env, exports, "getGamepadState", nv::glfwGetGamepadState); EXPORT_FUNC(env, exports, "setClipboardString", nv::glfwSetClipboardString); EXPORT_FUNC(env, exports, "getClipboardString", nv::glfwGetClipboardString); EXPORT_FUNC(env, exports, "getTime", nv::glfwGetTime); EXPORT_FUNC(env, exports, "setTime", nv::glfwSetTime); EXPORT_FUNC(env, exports, "getTimerValue", nv::glfwGetTimerValue); EXPORT_FUNC(env, exports, "getTimerFrequency", nv::glfwGetTimerFrequency); EXPORT_FUNC(env, exports, "makeContextCurrent", nv::glfwMakeContextCurrent); EXPORT_FUNC(env, exports, "getCurrentContext", nv::glfwGetCurrentContext); EXPORT_FUNC(env, exports, "swapBuffers", nv::glfwSwapBuffers); EXPORT_FUNC(env, exports, "swapInterval", nv::glfwSwapInterval); EXPORT_FUNC(env, exports, "extensionSupported", nv::glfwExtensionSupported); EXPORT_FUNC(env, exports, "getProcAddress", nv::glfwGetProcAddress); EXPORT_FUNC(env, exports, "vulkanSupported", nv::glfwVulkanSupported); EXPORT_FUNC(env, exports, "getRequiredInstanceExtensions", nv::glfwGetRequiredInstanceExtensions); EXPORT_ENUM(env, exports, "VERSION_MAJOR", GLFW_VERSION_MAJOR); EXPORT_ENUM(env, exports, "VERSION_MINOR", GLFW_VERSION_MINOR); EXPORT_ENUM(env, exports, "VERSION_REVISION", GLFW_VERSION_REVISION); EXPORT_ENUM(env, exports, "TRUE", GLFW_TRUE); EXPORT_ENUM(env, exports, "FALSE", GLFW_FALSE); EXPORT_ENUM(env, exports, "RELEASE", GLFW_RELEASE); EXPORT_ENUM(env, exports, "PRESS", GLFW_PRESS); EXPORT_ENUM(env, exports, "REPEAT", GLFW_REPEAT); EXPORT_ENUM(env, exports, "HAT_CENTERED", GLFW_HAT_CENTERED); EXPORT_ENUM(env, exports, "HAT_UP", GLFW_HAT_UP); EXPORT_ENUM(env, exports, "HAT_RIGHT", GLFW_HAT_RIGHT); EXPORT_ENUM(env, exports, "HAT_DOWN", GLFW_HAT_DOWN); EXPORT_ENUM(env, exports, "HAT_LEFT", GLFW_HAT_LEFT); EXPORT_ENUM(env, exports, "HAT_RIGHT_UP", GLFW_HAT_RIGHT_UP); EXPORT_ENUM(env, exports, "HAT_RIGHT_DOWN", GLFW_HAT_RIGHT_DOWN); EXPORT_ENUM(env, exports, "HAT_LEFT_UP", GLFW_HAT_LEFT_UP); EXPORT_ENUM(env, exports, "HAT_LEFT_DOWN", GLFW_HAT_LEFT_DOWN); EXPORT_ENUM(env, exports, "KEY_UNKNOWN", GLFW_KEY_UNKNOWN); EXPORT_ENUM(env, exports, "KEY_SPACE", GLFW_KEY_SPACE); EXPORT_ENUM(env, exports, "KEY_APOSTROPHE", GLFW_KEY_APOSTROPHE); EXPORT_ENUM(env, exports, "KEY_COMMA", GLFW_KEY_COMMA); EXPORT_ENUM(env, exports, "KEY_MINUS", GLFW_KEY_MINUS); EXPORT_ENUM(env, exports, "KEY_PERIOD", GLFW_KEY_PERIOD); EXPORT_ENUM(env, exports, "KEY_SLASH", GLFW_KEY_SLASH); EXPORT_ENUM(env, exports, "KEY_0", GLFW_KEY_0); EXPORT_ENUM(env, exports, "KEY_1", GLFW_KEY_1); EXPORT_ENUM(env, exports, "KEY_2", GLFW_KEY_2); EXPORT_ENUM(env, exports, "KEY_3", GLFW_KEY_3); EXPORT_ENUM(env, exports, "KEY_4", GLFW_KEY_4); EXPORT_ENUM(env, exports, "KEY_5", GLFW_KEY_5); EXPORT_ENUM(env, exports, "KEY_6", GLFW_KEY_6); EXPORT_ENUM(env, exports, "KEY_7", GLFW_KEY_7); EXPORT_ENUM(env, exports, "KEY_8", GLFW_KEY_8); EXPORT_ENUM(env, exports, "KEY_9", GLFW_KEY_9); EXPORT_ENUM(env, exports, "KEY_SEMICOLON", GLFW_KEY_SEMICOLON); EXPORT_ENUM(env, exports, "KEY_EQUAL", GLFW_KEY_EQUAL); EXPORT_ENUM(env, exports, "KEY_A", GLFW_KEY_A); EXPORT_ENUM(env, exports, "KEY_B", GLFW_KEY_B); EXPORT_ENUM(env, exports, "KEY_C", GLFW_KEY_C); EXPORT_ENUM(env, exports, "KEY_D", GLFW_KEY_D); EXPORT_ENUM(env, exports, "KEY_E", GLFW_KEY_E); EXPORT_ENUM(env, exports, "KEY_F", GLFW_KEY_F); EXPORT_ENUM(env, exports, "KEY_G", GLFW_KEY_G); EXPORT_ENUM(env, exports, "KEY_H", GLFW_KEY_H); EXPORT_ENUM(env, exports, "KEY_I", GLFW_KEY_I); EXPORT_ENUM(env, exports, "KEY_J", GLFW_KEY_J); EXPORT_ENUM(env, exports, "KEY_K", GLFW_KEY_K); EXPORT_ENUM(env, exports, "KEY_L", GLFW_KEY_L); EXPORT_ENUM(env, exports, "KEY_M", GLFW_KEY_M); EXPORT_ENUM(env, exports, "KEY_N", GLFW_KEY_N); EXPORT_ENUM(env, exports, "KEY_O", GLFW_KEY_O); EXPORT_ENUM(env, exports, "KEY_P", GLFW_KEY_P); EXPORT_ENUM(env, exports, "KEY_Q", GLFW_KEY_Q); EXPORT_ENUM(env, exports, "KEY_R", GLFW_KEY_R); EXPORT_ENUM(env, exports, "KEY_S", GLFW_KEY_S); EXPORT_ENUM(env, exports, "KEY_T", GLFW_KEY_T); EXPORT_ENUM(env, exports, "KEY_U", GLFW_KEY_U); EXPORT_ENUM(env, exports, "KEY_V", GLFW_KEY_V); EXPORT_ENUM(env, exports, "KEY_W", GLFW_KEY_W); EXPORT_ENUM(env, exports, "KEY_X", GLFW_KEY_X); EXPORT_ENUM(env, exports, "KEY_Y", GLFW_KEY_Y); EXPORT_ENUM(env, exports, "KEY_Z", GLFW_KEY_Z); EXPORT_ENUM(env, exports, "KEY_LEFT_BRACKET", GLFW_KEY_LEFT_BRACKET); EXPORT_ENUM(env, exports, "KEY_BACKSLASH", GLFW_KEY_BACKSLASH); EXPORT_ENUM(env, exports, "KEY_RIGHT_BRACKET", GLFW_KEY_RIGHT_BRACKET); EXPORT_ENUM(env, exports, "KEY_GRAVE_ACCENT", GLFW_KEY_GRAVE_ACCENT); EXPORT_ENUM(env, exports, "KEY_WORLD_1", GLFW_KEY_WORLD_1); EXPORT_ENUM(env, exports, "KEY_WORLD_2", GLFW_KEY_WORLD_2); EXPORT_ENUM(env, exports, "KEY_ESCAPE", GLFW_KEY_ESCAPE); EXPORT_ENUM(env, exports, "KEY_ENTER", GLFW_KEY_ENTER); EXPORT_ENUM(env, exports, "KEY_TAB", GLFW_KEY_TAB); EXPORT_ENUM(env, exports, "KEY_BACKSPACE", GLFW_KEY_BACKSPACE); EXPORT_ENUM(env, exports, "KEY_INSERT", GLFW_KEY_INSERT); EXPORT_ENUM(env, exports, "KEY_DELETE", GLFW_KEY_DELETE); EXPORT_ENUM(env, exports, "KEY_RIGHT", GLFW_KEY_RIGHT); EXPORT_ENUM(env, exports, "KEY_LEFT", GLFW_KEY_LEFT); EXPORT_ENUM(env, exports, "KEY_DOWN", GLFW_KEY_DOWN); EXPORT_ENUM(env, exports, "KEY_UP", GLFW_KEY_UP); EXPORT_ENUM(env, exports, "KEY_PAGE_UP", GLFW_KEY_PAGE_UP); EXPORT_ENUM(env, exports, "KEY_PAGE_DOWN", GLFW_KEY_PAGE_DOWN); EXPORT_ENUM(env, exports, "KEY_HOME", GLFW_KEY_HOME); EXPORT_ENUM(env, exports, "KEY_END", GLFW_KEY_END); EXPORT_ENUM(env, exports, "KEY_CAPS_LOCK", GLFW_KEY_CAPS_LOCK); EXPORT_ENUM(env, exports, "KEY_SCROLL_LOCK", GLFW_KEY_SCROLL_LOCK); EXPORT_ENUM(env, exports, "KEY_NUM_LOCK", GLFW_KEY_NUM_LOCK); EXPORT_ENUM(env, exports, "KEY_PRINT_SCREEN", GLFW_KEY_PRINT_SCREEN); EXPORT_ENUM(env, exports, "KEY_PAUSE", GLFW_KEY_PAUSE); EXPORT_ENUM(env, exports, "KEY_F1", GLFW_KEY_F1); EXPORT_ENUM(env, exports, "KEY_F2", GLFW_KEY_F2); EXPORT_ENUM(env, exports, "KEY_F3", GLFW_KEY_F3); EXPORT_ENUM(env, exports, "KEY_F4", GLFW_KEY_F4); EXPORT_ENUM(env, exports, "KEY_F5", GLFW_KEY_F5); EXPORT_ENUM(env, exports, "KEY_F6", GLFW_KEY_F6); EXPORT_ENUM(env, exports, "KEY_F7", GLFW_KEY_F7); EXPORT_ENUM(env, exports, "KEY_F8", GLFW_KEY_F8); EXPORT_ENUM(env, exports, "KEY_F9", GLFW_KEY_F9); EXPORT_ENUM(env, exports, "KEY_F10", GLFW_KEY_F10); EXPORT_ENUM(env, exports, "KEY_F11", GLFW_KEY_F11); EXPORT_ENUM(env, exports, "KEY_F12", GLFW_KEY_F12); EXPORT_ENUM(env, exports, "KEY_F13", GLFW_KEY_F13); EXPORT_ENUM(env, exports, "KEY_F14", GLFW_KEY_F14); EXPORT_ENUM(env, exports, "KEY_F15", GLFW_KEY_F15); EXPORT_ENUM(env, exports, "KEY_F16", GLFW_KEY_F16); EXPORT_ENUM(env, exports, "KEY_F17", GLFW_KEY_F17); EXPORT_ENUM(env, exports, "KEY_F18", GLFW_KEY_F18); EXPORT_ENUM(env, exports, "KEY_F19", GLFW_KEY_F19); EXPORT_ENUM(env, exports, "KEY_F20", GLFW_KEY_F20); EXPORT_ENUM(env, exports, "KEY_F21", GLFW_KEY_F21); EXPORT_ENUM(env, exports, "KEY_F22", GLFW_KEY_F22); EXPORT_ENUM(env, exports, "KEY_F23", GLFW_KEY_F23); EXPORT_ENUM(env, exports, "KEY_F24", GLFW_KEY_F24); EXPORT_ENUM(env, exports, "KEY_F25", GLFW_KEY_F25); EXPORT_ENUM(env, exports, "KEY_KP_0", GLFW_KEY_KP_0); EXPORT_ENUM(env, exports, "KEY_KP_1", GLFW_KEY_KP_1); EXPORT_ENUM(env, exports, "KEY_KP_2", GLFW_KEY_KP_2); EXPORT_ENUM(env, exports, "KEY_KP_3", GLFW_KEY_KP_3); EXPORT_ENUM(env, exports, "KEY_KP_4", GLFW_KEY_KP_4); EXPORT_ENUM(env, exports, "KEY_KP_5", GLFW_KEY_KP_5); EXPORT_ENUM(env, exports, "KEY_KP_6", GLFW_KEY_KP_6); EXPORT_ENUM(env, exports, "KEY_KP_7", GLFW_KEY_KP_7); EXPORT_ENUM(env, exports, "KEY_KP_8", GLFW_KEY_KP_8); EXPORT_ENUM(env, exports, "KEY_KP_9", GLFW_KEY_KP_9); EXPORT_ENUM(env, exports, "KEY_KP_DECIMAL", GLFW_KEY_KP_DECIMAL); EXPORT_ENUM(env, exports, "KEY_KP_DIVIDE", GLFW_KEY_KP_DIVIDE); EXPORT_ENUM(env, exports, "KEY_KP_MULTIPLY", GLFW_KEY_KP_MULTIPLY); EXPORT_ENUM(env, exports, "KEY_KP_SUBTRACT", GLFW_KEY_KP_SUBTRACT); EXPORT_ENUM(env, exports, "KEY_KP_ADD", GLFW_KEY_KP_ADD); EXPORT_ENUM(env, exports, "KEY_KP_ENTER", GLFW_KEY_KP_ENTER); EXPORT_ENUM(env, exports, "KEY_KP_EQUAL", GLFW_KEY_KP_EQUAL); EXPORT_ENUM(env, exports, "KEY_LEFT_SHIFT", GLFW_KEY_LEFT_SHIFT); EXPORT_ENUM(env, exports, "KEY_LEFT_CONTROL", GLFW_KEY_LEFT_CONTROL); EXPORT_ENUM(env, exports, "KEY_LEFT_ALT", GLFW_KEY_LEFT_ALT); EXPORT_ENUM(env, exports, "KEY_LEFT_SUPER", GLFW_KEY_LEFT_SUPER); EXPORT_ENUM(env, exports, "KEY_RIGHT_SHIFT", GLFW_KEY_RIGHT_SHIFT); EXPORT_ENUM(env, exports, "KEY_RIGHT_CONTROL", GLFW_KEY_RIGHT_CONTROL); EXPORT_ENUM(env, exports, "KEY_RIGHT_ALT", GLFW_KEY_RIGHT_ALT); EXPORT_ENUM(env, exports, "KEY_RIGHT_SUPER", GLFW_KEY_RIGHT_SUPER); EXPORT_ENUM(env, exports, "KEY_MENU", GLFW_KEY_MENU); EXPORT_ENUM(env, exports, "KEY_LAST", GLFW_KEY_LAST); EXPORT_ENUM(env, exports, "MOD_SHIFT", GLFW_MOD_SHIFT); EXPORT_ENUM(env, exports, "MOD_CONTROL", GLFW_MOD_CONTROL); EXPORT_ENUM(env, exports, "MOD_ALT", GLFW_MOD_ALT); EXPORT_ENUM(env, exports, "MOD_SUPER", GLFW_MOD_SUPER); EXPORT_ENUM(env, exports, "MOD_CAPS_LOCK", GLFW_MOD_CAPS_LOCK); EXPORT_ENUM(env, exports, "MOD_NUM_LOCK", GLFW_MOD_NUM_LOCK); EXPORT_ENUM(env, exports, "MOUSE_BUTTON_1", GLFW_MOUSE_BUTTON_1); EXPORT_ENUM(env, exports, "MOUSE_BUTTON_2", GLFW_MOUSE_BUTTON_2); EXPORT_ENUM(env, exports, "MOUSE_BUTTON_3", GLFW_MOUSE_BUTTON_3); EXPORT_ENUM(env, exports, "MOUSE_BUTTON_4", GLFW_MOUSE_BUTTON_4); EXPORT_ENUM(env, exports, "MOUSE_BUTTON_5", GLFW_MOUSE_BUTTON_5); EXPORT_ENUM(env, exports, "MOUSE_BUTTON_6", GLFW_MOUSE_BUTTON_6); EXPORT_ENUM(env, exports, "MOUSE_BUTTON_7", GLFW_MOUSE_BUTTON_7); EXPORT_ENUM(env, exports, "MOUSE_BUTTON_8", GLFW_MOUSE_BUTTON_8); EXPORT_ENUM(env, exports, "MOUSE_BUTTON_LAST", GLFW_MOUSE_BUTTON_LAST); EXPORT_ENUM(env, exports, "MOUSE_BUTTON_LEFT", GLFW_MOUSE_BUTTON_LEFT); EXPORT_ENUM(env, exports, "MOUSE_BUTTON_RIGHT", GLFW_MOUSE_BUTTON_RIGHT); EXPORT_ENUM(env, exports, "MOUSE_BUTTON_MIDDLE", GLFW_MOUSE_BUTTON_MIDDLE); EXPORT_ENUM(env, exports, "JOYSTICK_1", GLFW_JOYSTICK_1); EXPORT_ENUM(env, exports, "JOYSTICK_2", GLFW_JOYSTICK_2); EXPORT_ENUM(env, exports, "JOYSTICK_3", GLFW_JOYSTICK_3); EXPORT_ENUM(env, exports, "JOYSTICK_4", GLFW_JOYSTICK_4); EXPORT_ENUM(env, exports, "JOYSTICK_5", GLFW_JOYSTICK_5); EXPORT_ENUM(env, exports, "JOYSTICK_6", GLFW_JOYSTICK_6); EXPORT_ENUM(env, exports, "JOYSTICK_7", GLFW_JOYSTICK_7); EXPORT_ENUM(env, exports, "JOYSTICK_8", GLFW_JOYSTICK_8); EXPORT_ENUM(env, exports, "JOYSTICK_9", GLFW_JOYSTICK_9); EXPORT_ENUM(env, exports, "JOYSTICK_10", GLFW_JOYSTICK_10); EXPORT_ENUM(env, exports, "JOYSTICK_11", GLFW_JOYSTICK_11); EXPORT_ENUM(env, exports, "JOYSTICK_12", GLFW_JOYSTICK_12); EXPORT_ENUM(env, exports, "JOYSTICK_13", GLFW_JOYSTICK_13); EXPORT_ENUM(env, exports, "JOYSTICK_14", GLFW_JOYSTICK_14); EXPORT_ENUM(env, exports, "JOYSTICK_15", GLFW_JOYSTICK_15); EXPORT_ENUM(env, exports, "JOYSTICK_16", GLFW_JOYSTICK_16); EXPORT_ENUM(env, exports, "JOYSTICK_LAST", GLFW_JOYSTICK_LAST); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_A", GLFW_GAMEPAD_BUTTON_A); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_B", GLFW_GAMEPAD_BUTTON_B); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_X", GLFW_GAMEPAD_BUTTON_X); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_Y", GLFW_GAMEPAD_BUTTON_Y); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_LEFT_BUMPER", GLFW_GAMEPAD_BUTTON_LEFT_BUMPER); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_RIGHT_BUMPER", GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_BACK", GLFW_GAMEPAD_BUTTON_BACK); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_START", GLFW_GAMEPAD_BUTTON_START); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_GUIDE", GLFW_GAMEPAD_BUTTON_GUIDE); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_LEFT_THUMB", GLFW_GAMEPAD_BUTTON_LEFT_THUMB); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_RIGHT_THUMB", GLFW_GAMEPAD_BUTTON_RIGHT_THUMB); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_DPAD_UP", GLFW_GAMEPAD_BUTTON_DPAD_UP); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_DPAD_RIGHT", GLFW_GAMEPAD_BUTTON_DPAD_RIGHT); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_DPAD_DOWN", GLFW_GAMEPAD_BUTTON_DPAD_DOWN); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_DPAD_LEFT", GLFW_GAMEPAD_BUTTON_DPAD_LEFT); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_LAST", GLFW_GAMEPAD_BUTTON_LAST); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_CROSS", GLFW_GAMEPAD_BUTTON_CROSS); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_CIRCLE", GLFW_GAMEPAD_BUTTON_CIRCLE); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_SQUARE", GLFW_GAMEPAD_BUTTON_SQUARE); EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_TRIANGLE", GLFW_GAMEPAD_BUTTON_TRIANGLE); EXPORT_ENUM(env, exports, "GAMEPAD_AXIS_LEFT_X", GLFW_GAMEPAD_AXIS_LEFT_X); EXPORT_ENUM(env, exports, "GAMEPAD_AXIS_LEFT_Y", GLFW_GAMEPAD_AXIS_LEFT_Y); EXPORT_ENUM(env, exports, "GAMEPAD_AXIS_RIGHT_X", GLFW_GAMEPAD_AXIS_RIGHT_X); EXPORT_ENUM(env, exports, "GAMEPAD_AXIS_RIGHT_Y", GLFW_GAMEPAD_AXIS_RIGHT_Y); EXPORT_ENUM(env, exports, "GAMEPAD_AXIS_LEFT_TRIGGER", GLFW_GAMEPAD_AXIS_LEFT_TRIGGER); EXPORT_ENUM(env, exports, "GAMEPAD_AXIS_RIGHT_TRIGGER", GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER); EXPORT_ENUM(env, exports, "GAMEPAD_AXIS_LAST", GLFW_GAMEPAD_AXIS_LAST); EXPORT_ENUM(env, exports, "NO_ERROR", GLFW_NO_ERROR); EXPORT_ENUM(env, exports, "NOT_INITIALIZED", GLFW_NOT_INITIALIZED); EXPORT_ENUM(env, exports, "NO_CURRENT_CONTEXT", GLFW_NO_CURRENT_CONTEXT); EXPORT_ENUM(env, exports, "INVALID_ENUM", GLFW_INVALID_ENUM); EXPORT_ENUM(env, exports, "INVALID_VALUE", GLFW_INVALID_VALUE); EXPORT_ENUM(env, exports, "OUT_OF_MEMORY", GLFW_OUT_OF_MEMORY); EXPORT_ENUM(env, exports, "API_UNAVAILABLE", GLFW_API_UNAVAILABLE); EXPORT_ENUM(env, exports, "VERSION_UNAVAILABLE", GLFW_VERSION_UNAVAILABLE); EXPORT_ENUM(env, exports, "PLATFORM_ERROR", GLFW_PLATFORM_ERROR); EXPORT_ENUM(env, exports, "FORMAT_UNAVAILABLE", GLFW_FORMAT_UNAVAILABLE); EXPORT_ENUM(env, exports, "NO_WINDOW_CONTEXT", GLFW_NO_WINDOW_CONTEXT); EXPORT_ENUM(env, exports, "FOCUSED", GLFW_FOCUSED); EXPORT_ENUM(env, exports, "ICONIFIED", GLFW_ICONIFIED); EXPORT_ENUM(env, exports, "RESIZABLE", GLFW_RESIZABLE); EXPORT_ENUM(env, exports, "VISIBLE", GLFW_VISIBLE); EXPORT_ENUM(env, exports, "DECORATED", GLFW_DECORATED); EXPORT_ENUM(env, exports, "AUTO_ICONIFY", GLFW_AUTO_ICONIFY); EXPORT_ENUM(env, exports, "FLOATING", GLFW_FLOATING); EXPORT_ENUM(env, exports, "MAXIMIZED", GLFW_MAXIMIZED); EXPORT_ENUM(env, exports, "CENTER_CURSOR", GLFW_CENTER_CURSOR); EXPORT_ENUM(env, exports, "TRANSPARENT_FRAMEBUFFER", GLFW_TRANSPARENT_FRAMEBUFFER); EXPORT_ENUM(env, exports, "HOVERED", GLFW_HOVERED); EXPORT_ENUM(env, exports, "FOCUS_ON_SHOW", GLFW_FOCUS_ON_SHOW); EXPORT_ENUM(env, exports, "RED_BITS", GLFW_RED_BITS); EXPORT_ENUM(env, exports, "GREEN_BITS", GLFW_GREEN_BITS); EXPORT_ENUM(env, exports, "BLUE_BITS", GLFW_BLUE_BITS); EXPORT_ENUM(env, exports, "ALPHA_BITS", GLFW_ALPHA_BITS); EXPORT_ENUM(env, exports, "DEPTH_BITS", GLFW_DEPTH_BITS); EXPORT_ENUM(env, exports, "STENCIL_BITS", GLFW_STENCIL_BITS); EXPORT_ENUM(env, exports, "ACCUM_RED_BITS", GLFW_ACCUM_RED_BITS); EXPORT_ENUM(env, exports, "ACCUM_GREEN_BITS", GLFW_ACCUM_GREEN_BITS); EXPORT_ENUM(env, exports, "ACCUM_BLUE_BITS", GLFW_ACCUM_BLUE_BITS); EXPORT_ENUM(env, exports, "ACCUM_ALPHA_BITS", GLFW_ACCUM_ALPHA_BITS); EXPORT_ENUM(env, exports, "AUX_BUFFERS", GLFW_AUX_BUFFERS); EXPORT_ENUM(env, exports, "STEREO", GLFW_STEREO); EXPORT_ENUM(env, exports, "SAMPLES", GLFW_SAMPLES); EXPORT_ENUM(env, exports, "SRGB_CAPABLE", GLFW_SRGB_CAPABLE); EXPORT_ENUM(env, exports, "REFRESH_RATE", GLFW_REFRESH_RATE); EXPORT_ENUM(env, exports, "DOUBLEBUFFER", GLFW_DOUBLEBUFFER); EXPORT_ENUM(env, exports, "CLIENT_API", GLFW_CLIENT_API); EXPORT_ENUM(env, exports, "CONTEXT_VERSION_MAJOR", GLFW_CONTEXT_VERSION_MAJOR); EXPORT_ENUM(env, exports, "CONTEXT_VERSION_MINOR", GLFW_CONTEXT_VERSION_MINOR); EXPORT_ENUM(env, exports, "CONTEXT_REVISION", GLFW_CONTEXT_REVISION); EXPORT_ENUM(env, exports, "CONTEXT_ROBUSTNESS", GLFW_CONTEXT_ROBUSTNESS); EXPORT_ENUM(env, exports, "OPENGL_FORWARD_COMPAT", GLFW_OPENGL_FORWARD_COMPAT); EXPORT_ENUM(env, exports, "OPENGL_DEBUG_CONTEXT", GLFW_OPENGL_DEBUG_CONTEXT); EXPORT_ENUM(env, exports, "OPENGL_PROFILE", GLFW_OPENGL_PROFILE); EXPORT_ENUM(env, exports, "CONTEXT_RELEASE_BEHAVIOR", GLFW_CONTEXT_RELEASE_BEHAVIOR); EXPORT_ENUM(env, exports, "CONTEXT_NO_ERROR", GLFW_CONTEXT_NO_ERROR); EXPORT_ENUM(env, exports, "CONTEXT_CREATION_API", GLFW_CONTEXT_CREATION_API); EXPORT_ENUM(env, exports, "SCALE_TO_MONITOR", GLFW_SCALE_TO_MONITOR); EXPORT_ENUM(env, exports, "COCOA_RETINA_FRAMEBUFFER", GLFW_COCOA_RETINA_FRAMEBUFFER); EXPORT_ENUM(env, exports, "COCOA_FRAME_NAME", GLFW_COCOA_FRAME_NAME); EXPORT_ENUM(env, exports, "COCOA_GRAPHICS_SWITCHING", GLFW_COCOA_GRAPHICS_SWITCHING); EXPORT_ENUM(env, exports, "X11_CLASS_NAME", GLFW_X11_CLASS_NAME); EXPORT_ENUM(env, exports, "X11_INSTANCE_NAME", GLFW_X11_INSTANCE_NAME); EXPORT_ENUM(env, exports, "NO_API", GLFW_NO_API); EXPORT_ENUM(env, exports, "OPENGL_API", GLFW_OPENGL_API); EXPORT_ENUM(env, exports, "OPENGL_ES_API", GLFW_OPENGL_ES_API); EXPORT_ENUM(env, exports, "NO_ROBUSTNESS", GLFW_NO_ROBUSTNESS); EXPORT_ENUM(env, exports, "NO_RESET_NOTIFICATION", GLFW_NO_RESET_NOTIFICATION); EXPORT_ENUM(env, exports, "LOSE_CONTEXT_ON_RESET", GLFW_LOSE_CONTEXT_ON_RESET); EXPORT_ENUM(env, exports, "OPENGL_ANY_PROFILE", GLFW_OPENGL_ANY_PROFILE); EXPORT_ENUM(env, exports, "OPENGL_CORE_PROFILE", GLFW_OPENGL_CORE_PROFILE); EXPORT_ENUM(env, exports, "OPENGL_COMPAT_PROFILE", GLFW_OPENGL_COMPAT_PROFILE); EXPORT_ENUM(env, exports, "CURSOR", GLFW_CURSOR); EXPORT_ENUM(env, exports, "STICKY_KEYS", GLFW_STICKY_KEYS); EXPORT_ENUM(env, exports, "STICKY_MOUSE_BUTTONS", GLFW_STICKY_MOUSE_BUTTONS); EXPORT_ENUM(env, exports, "LOCK_KEY_MODS", GLFW_LOCK_KEY_MODS); EXPORT_ENUM(env, exports, "RAW_MOUSE_MOTION", GLFW_RAW_MOUSE_MOTION); EXPORT_ENUM(env, exports, "CURSOR_NORMAL", GLFW_CURSOR_NORMAL); EXPORT_ENUM(env, exports, "CURSOR_HIDDEN", GLFW_CURSOR_HIDDEN); EXPORT_ENUM(env, exports, "CURSOR_DISABLED", GLFW_CURSOR_DISABLED); EXPORT_ENUM(env, exports, "ANY_RELEASE_BEHAVIOR", GLFW_ANY_RELEASE_BEHAVIOR); EXPORT_ENUM(env, exports, "RELEASE_BEHAVIOR_FLUSH", GLFW_RELEASE_BEHAVIOR_FLUSH); EXPORT_ENUM(env, exports, "RELEASE_BEHAVIOR_NONE", GLFW_RELEASE_BEHAVIOR_NONE); EXPORT_ENUM(env, exports, "NATIVE_CONTEXT_API", GLFW_NATIVE_CONTEXT_API); EXPORT_ENUM(env, exports, "EGL_CONTEXT_API", GLFW_EGL_CONTEXT_API); EXPORT_ENUM(env, exports, "OSMESA_CONTEXT_API", GLFW_OSMESA_CONTEXT_API); EXPORT_ENUM(env, exports, "ARROW_CURSOR", GLFW_ARROW_CURSOR); EXPORT_ENUM(env, exports, "IBEAM_CURSOR", GLFW_IBEAM_CURSOR); EXPORT_ENUM(env, exports, "CROSSHAIR_CURSOR", GLFW_CROSSHAIR_CURSOR); EXPORT_ENUM(env, exports, "HAND_CURSOR", GLFW_HAND_CURSOR); EXPORT_ENUM(env, exports, "HRESIZE_CURSOR", GLFW_HRESIZE_CURSOR); EXPORT_ENUM(env, exports, "VRESIZE_CURSOR", GLFW_VRESIZE_CURSOR); EXPORT_ENUM(env, exports, "CONNECTED", GLFW_CONNECTED); EXPORT_ENUM(env, exports, "DISCONNECTED", GLFW_DISCONNECTED); EXPORT_ENUM(env, exports, "JOYSTICK_HAT_BUTTONS", GLFW_JOYSTICK_HAT_BUTTONS); EXPORT_ENUM(env, exports, "COCOA_CHDIR_RESOURCES", GLFW_COCOA_CHDIR_RESOURCES); EXPORT_ENUM(env, exports, "COCOA_MENUBAR", GLFW_COCOA_MENUBAR); EXPORT_ENUM(env, exports, "DONT_CARE", GLFW_DONT_CARE); return exports; } NODE_API_MODULE(nv, initModule);
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/src/errors.hpp
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "glfw.hpp" namespace nv { namespace detail { inline std::string glfwGetErrorName(int code) { switch (code) { case GLFW_NO_ERROR: return "no error"; case GLFW_NOT_INITIALIZED: return "not initialized"; case GLFW_NO_CURRENT_CONTEXT: return "no current context"; case GLFW_INVALID_ENUM: return "invalid enum"; case GLFW_INVALID_VALUE: return "invalid value"; case GLFW_OUT_OF_MEMORY: return "out of memory"; case GLFW_API_UNAVAILABLE: return "api unavailable"; case GLFW_VERSION_UNAVAILABLE: return "version unavailable"; case GLFW_PLATFORM_ERROR: return "platform error"; case GLFW_FORMAT_UNAVAILABLE: return "format unavailable"; case GLFW_NO_WINDOW_CONTEXT: return "no window context"; default: return "unknown error"; } } } // namespace detail inline Napi::Error glfwError( Napi::Env const& env, const int code, const char* err, const char* file, const uint32_t line) { auto name = detail::glfwGetErrorName(code); auto msg = std::string{name} + " " + std::string{err} + "\n at " + std::string{file} + ":" + std::to_string(line); return Napi::Error::New(env, msg); } } // namespace nv
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/src/cursor.cpp
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "glfw.hpp" #include "macros.hpp" #include <nv_node/utilities/args.hpp> #include <nv_node/utilities/cpp_to_napi.hpp> namespace nv { // GLFWAPI int glfwRawMouseMotionSupported(void); Napi::Value glfwRawMouseMotionSupported(Napi::CallbackInfo const& info) { return CPPToNapi(info)(static_cast<bool>(GLFWAPI::glfwRawMouseMotionSupported())); } // GLFWAPI GLFWcursor* glfwCreateCursor(const GLFWimage* image, int xhot, int yhot); Napi::Value glfwCreateCursor(Napi::CallbackInfo const& info) { CallbackArgs args{info}; auto obj = info[0].As<Napi::Object>(); GLFWimage image{// NapiToCPP(obj.Get("width")), NapiToCPP(obj.Get("height")), NapiToCPP(obj.Get("pixels"))}; std::map<std::string, int32_t> pos = args[1]; return CPPToNapi(info)(GLFWAPI::glfwCreateCursor(&image, pos["x"], pos["y"])); } // GLFWAPI GLFWcursor* glfwCreateStandardCursor(int shape); Napi::Value glfwCreateStandardCursor(Napi::CallbackInfo const& info) { CallbackArgs args{info}; GLFWcursor* cursor = GLFWAPI::glfwCreateStandardCursor(args[0]); return CPPToNapi(info)(cursor); } // GLFWAPI void glfwDestroyCursor(GLFWcursor* cursor); void glfwDestroyCursor(Napi::CallbackInfo const& info) { auto env = info.Env(); CallbackArgs args{info}; GLFWcursor* cursor = args[0]; GLFW_TRY(env, GLFWAPI::glfwDestroyCursor(cursor)); } } // namespace nv
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/src/events.cpp
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "glfw.hpp" #include "macros.hpp" #include <nv_node/utilities/args.hpp> namespace nv { // GLFWAPI void glfwPollEvents(void); void glfwPollEvents(Napi::CallbackInfo const& info) { GLFW_TRY(info.Env(), GLFWAPI::glfwPollEvents()); } // GLFWAPI void glfwWaitEvents(void); void glfwWaitEvents(Napi::CallbackInfo const& info) { GLFW_TRY(info.Env(), GLFWAPI::glfwWaitEvents()); } // GLFWAPI void glfwWaitEventsTimeout(double timeout); void glfwWaitEventsTimeout(Napi::CallbackInfo const& info) { GLFW_TRY(info.Env(), GLFWAPI::glfwWaitEventsTimeout(info[0].ToNumber())); } // GLFWAPI void glfwPostEmptyEvent(void); void glfwPostEmptyEvent(Napi::CallbackInfo const& info) { GLFW_TRY(info.Env(), GLFWAPI::glfwPostEmptyEvent()); } } // namespace nv
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/src/macros.hpp
// Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "errors.hpp" #include "glfw.hpp" #define EXPORT_PROP(exports, name, val) exports.Set(name, val); #define EXPORT_ENUM(env, exports, name, val) \ EXPORT_PROP(exports, name, Napi::Number::New(env, val)); #define EXPORT_FUNC(env, exports, name, func) \ exports.DefineProperty(Napi::PropertyDescriptor::Function( \ env, \ exports, \ Napi::String::New(env, name), \ func, \ static_cast<napi_property_attributes>(napi_writable | napi_enumerable | napi_configurable), \ nullptr)); #define GLFW_THROW(env, code, err) \ NAPI_THROW(nv::glfwError(env, code, err, __FILE__, __LINE__), (e).Undefined()) #define GLFW_THROW_ASYNC(task, code, err) \ (task)->Reject(nv::glfwError((task)->Env(), code, err, __FILE__, __LINE__).Value()); \ return (task)->Promise() #define GLFW_TRY(env, expr) \ do { \ (expr); \ const char* err = NULL; \ int const code = GLFWAPI::glfwGetError(&err); \ if (code != GLFW_NO_ERROR) { GLFW_THROW(env, code, err); } \ } while (0) #define GLFW_TRY_VOID(env, expr) \ do { \ (expr); \ const char* err = NULL; \ int const code = GLFWAPI::glfwGetError(&err); \ if (code != GLFW_NO_ERROR) { return; } \ } while (0) #define GLFW_TRY_ASYNC(env, expr) \ do { \ (expr); \ const char* err = NULL; \ int const code = GLFWAPI::glfwGetError(&err); \ if (code != GLFW_NO_ERROR) { GLFW_THROW_ASYNC(env, code, err); } \ } while (0) #define GLFW_EXPECT_TRUE(env, expr) \ do { \ if ((expr) != GLFW_TRUE) { \ const char* err = NULL; \ int const code = GLFWAPI::glfwGetError(&err); \ GLFW_THROW(env, code, err); \ } \ } while (0)
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/test/tsconfig.json
{ "extends": "../tsconfig.json", "include": [ "../src/**/*.ts", "../test/**/*.ts" ], "compilerOptions": { "target": "esnext", "module": "commonjs", "allowJs": true, "importHelpers": false, "noEmitHelpers": false, "noEmitOnError": false, "sourceMap": false, "inlineSources": false, "inlineSourceMap": false, "downlevelIteration": false, "baseUrl": "../", "paths": { "@rapidsai/glfw": ["src/index"], "@rapidsai/glfw/*": ["src/*"] } } }
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/test/cuda-gl-interop-tests.js
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. test.skip('CUDA-GL interop', () => { require('@rapidsai/glfw').createWindow(testCUDAGLInterop, true).open(); function testCUDAGLInterop() { const assert = require('assert'); const {Uint8Buffer, CUDA} = require('@rapidsai/cuda'); const {Buffer: GLBuffer} = require('@luma.gl/core'); const {WebGL2RenderingContext} = require('@rapidsai/webgl'); const gl = new WebGL2RenderingContext(); const hostResult1 = Buffer.alloc(16); const hostResult2 = Buffer.alloc(16); const hostResult3 = Buffer.alloc(16); const hostBuf = Buffer.alloc(16).fill(7); const cudaBuf = new Uint8Buffer(16).copyFrom(hostBuf).copyInto(hostResult1); const lumaBuf = new GLBuffer(gl, {target: gl.ARRAY_BUFFER, accessor: {size: 1, type: gl.UNSIGNED_BYTE}}); lumaBuf.reallocate(cudaBuf.length * lumaBuf.accessor.BYTES_PER_VERTEX); const cudaGLPtr = CUDA.runtime.cudaGraphicsGLRegisterBuffer(lumaBuf.handle.ptr, 0); CUDA.runtime.cudaGraphicsMapResources([cudaGLPtr]); const cudaGLMem = CUDA.runtime.cudaGraphicsResourceGetMappedPointer(cudaGLPtr); new Uint8Buffer(cudaGLMem).copyFrom(hostBuf).copyInto(hostResult2); CUDA.runtime.cudaGraphicsUnmapResources([cudaGLPtr]); CUDA.runtime.cudaGraphicsUnregisterResource(cudaGLPtr); lumaBuf.getData({dstData: hostResult3}); assert.ok(hostResult1.equals(hostBuf)); assert.ok(hostResult2.equals(hostBuf)); assert.ok(hostResult3.equals(hostBuf)); } });
0
rapidsai_public_repos/node/modules/glfw
rapidsai_public_repos/node/modules/glfw/test/glfw-tests.ts
// Copyright (c) 2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. test('nothing', () => {});
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/jsdom/package.json
{ "name": "@rapidsai/jsdom", "version": "22.12.2", "description": "JSDOM extensions for running browser-ish code in platform-native (and headless) GPU-accelerated GLFW windows", "license": "Apache-2.0", "main": "index.js", "types": "build/js", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "homepage": "https://github.com/rapidsai/node/tree/main/modules/jsdom#readme", "bugs": { "url": "https://github.com/rapidsai/node/issues" }, "repository": { "type": "git", "url": "git+https://github.com/rapidsai/node.git" }, "scripts": { "clean": "rimraf build doc compile_commands.json", "doc": "rimraf doc && typedoc --options typedoc.js", "test": "yarn test-import && node -r dotenv/config node_modules/.bin/jest -c jest.config.js", "test-import": "node -r dotenv/config --experimental-vm-modules test/test-import.js", "build": "yarn tsc:build", "compile": "yarn tsc:build", "rebuild": "yarn tsc:build", "tsc:clean": "rimraf build/js", "tsc:build": "yarn tsc:clean && tsc -p ./tsconfig.json", "tsc:watch": "yarn tsc:clean && tsc -p ./tsconfig.json -w" }, "dependencies": { "@babel/core": "7.15.5", "@babel/preset-env": "7.15.6", "@babel/preset-react": "7.14.5", "@babel/register": "7.15.3", "@cwasm/webp": "0.1.5", "@rapidsai/core": "~22.12.2", "@rapidsai/glfw": "~22.12.2", "@types/jsdom": "16.2.13", "@types/parse5": "6.0.3", "canvas": "^2.11.0", "clone-deep": "4.0.1", "cross-fetch": "3.1.4", "fetch-readablestream": "0.2.0", "jsdom": "16.6.0", "react": "17.0.2", "react-dom": "17.0.2", "rxjs": "6.6.7", "source-map-support": "^0.5.20", "svg2img": "0.9.3", "sync-request": "6.1.0", "usertiming": "0.1.8", "web-streams-polyfill": "2.1.1" }, "files": [ "build", "LICENSE", "index.js", "README.md", "package.json" ] }
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/jsdom/index.js
// Copyright (c) 2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = require('./build/js/index');
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/jsdom/jest.config.js
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. try { require('dotenv').config(); } catch (e) { } module.exports = { "verbose": true, "testEnvironment": "node", "maxWorkers": process.env.PARALLEL_LEVEL || 1, "globals": { "ts-jest": { "diagnostics": false, "tsconfig": "test/tsconfig.json" } }, "rootDir": "./", "roots": [ "<rootDir>/test/" ], "moduleFileExtensions": [ "js", "ts", "tsx" ], "coverageReporters": [ "lcov" ], "coveragePathIgnorePatterns": [ "test\\/.*\\.(ts|tsx|js)$", "/node_modules/" ], "transform": { "^.+\\.jsx?$": "ts-jest", "^.+\\.tsx?$": "ts-jest" }, "transformIgnorePatterns": [ "/build/(js|Debug|Release)/*$", "/node_modules/(?!@tensorflow)/*$", "/node_modules/(?!web-stream-tools).+\\.js$" ], "testRegex": "(.*(-|\\.)(test|spec)s?)\\.(ts|tsx|js)$", "preset": "ts-jest", "testMatch": null, "moduleNameMapper": { "^@rapidsai\/jsdom(.*)": "<rootDir>/build/js/$1", } };
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/jsdom/tsconfig.json
{ "include": ["src"], "exclude": ["node_modules"], "compilerOptions": { "baseUrl": "./", "paths": { "@rapidsai/jsdom": ["src/index"], "@rapidsai/jsdom/*": ["src/*"] }, "target": "ESNEXT", "module": "commonjs", "outDir": "./build/js", /* Decorators */ "experimentalDecorators": true, /* Basic stuff */ "moduleResolution": "node", "skipLibCheck": true, "skipDefaultLibCheck": true, "lib": ["dom", "esnext", "esnext.asynciterable"], /* Control what is emitted */ "declaration": true, "declarationMap": true, "noEmitOnError": true, "removeComments": false, "downlevelIteration": true, /* Create inline sourcemaps with sources */ "sourceMap": false, "inlineSources": true, "inlineSourceMap": true, /* The most restrictive settings possible */ "strict": true, "importHelpers": true, "noEmitHelpers": true, "noImplicitAny": true, "noUnusedLocals": true, "noImplicitReturns": true, "allowUnusedLabels": false, "noUnusedParameters": true, "allowUnreachableCode": false, "noFallthroughCasesInSwitch": true, "forceConsistentCasingInFileNames": true } }
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/jsdom/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2019 NVIDIA Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/jsdom/typedoc.js
module.exports = { entryPoints: ['src/index.ts'], out: 'doc', name: '@rapidsai/jsdom', tsconfig: 'tsconfig.json', excludePrivate: true, excludeProtected: true, excludeExternals: true, };
0
rapidsai_public_repos/node/modules/jsdom
rapidsai_public_repos/node/modules/jsdom/.vscode/launch.json
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Debug Tests", "type": "node", "request": "launch", "cwd": "${workspaceFolder}", "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", "program": "${workspaceFolder}/node_modules/.bin/jest", "skipFiles": [ // "<node_internals>/**", "<node_internals>/**/fs/utils", // "${workspaceFolder}/node_modules/**" ], "env": { "NODE_NO_WARNINGS": "1", "NODE_ENV": "production", "READABLE_STREAM": "disable", }, "args": [ "--verbose", "--runInBand", "-c", "jest.config.js", "${input:TEST_FILE}" ] }, { "name": "Debug Import Tests", "type": "node", "request": "launch", "cwd": "${workspaceFolder}", "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", "program": "test/test-import.js", "skipFiles": [ // "<node_internals>/**", "<node_internals>/**/fs/utils", // "${workspaceFolder}/node_modules/**" ], "env": { "NODE_NO_WARNINGS": "1", "NODE_ENV": "production", "READABLE_STREAM": "disable", }, "runtimeArgs": [ "--trace-uncaught", "--experimental-vm-modules" ] }, ], "inputs": [ { "type": "command", "id": "TEST_FILE", "command": "shellCommand.execute", "args": { "cwd": "${workspaceFolder}/modules/jsdom", "description": "Select a file to debug", "command": "./node_modules/.bin/jest --listTests | sed -r \"s@$PWD/test/@@g\"", } }, ], }
0
rapidsai_public_repos/node/modules/jsdom
rapidsai_public_repos/node/modules/jsdom/.vscode/tasks.json
{ "version": "2.0.0", "tasks": [ { "type": "npm", "group": "build", "label": "Recompile @rapidsai/jsdom TS (fast)", "script": "tsc:build", "detail": "yarn tsc:build", "problemMatcher": ["$tsc"], }, ], }
0
rapidsai_public_repos/node/modules/jsdom
rapidsai_public_repos/node/modules/jsdom/src/index.ts
// Copyright (c) 2021-2023, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as jsdom from 'jsdom'; import {GLFWWindowOptions, installGLFWWindow} from './polyfills/glfw'; import {installJSDOMUtils} from './polyfills/jsdom'; import {mjolnirHammerResolvers} from './polyfills/modules/mjolnir'; import {reactMapGLMapboxResolvers} from './polyfills/modules/reactmapgl'; import {createResolve, ResolversMap} from './polyfills/modules/resolve'; import {createContextFactory} from './polyfills/modules/vm'; import {createObjectUrlAndTmpDir} from './polyfills/object-url'; import { AnimationFrameRequestedCallback, defaultFrameScheduler, installAnimationFrame } from './polyfills/raf'; import {installWorker} from './polyfills/worker'; import {ImageLoader} from './resourceloader'; export interface RapidsJSDOMOptions extends jsdom.ConstructorOptions { module?: {path: string}; frameRate?: number; glfwOptions?: GLFWWindowOptions; resolvers?: ResolversMap; babel?: false|Partial<import('@babel/core').TransformOptions>; reportUnhandledExceptions?: boolean; onAnimationFrameRequested?: AnimationFrameRequestedCallback; } export class RapidsJSDOM extends jsdom.JSDOM { static defaultOptions = { frameRate: 60, glfwOptions: {}, reportUnhandledExceptions: true, onAnimationFrameRequested: undefined, babel: { babelrc: false, presets: [['@babel/preset-react', {'useBuiltIns': true}]], } as import('@babel/core').TransformOptions }; static fromReactComponent(componentPath: string, jsdomOptions: RapidsJSDOMOptions = {}, reactProps = {}) { const jsdom = new RapidsJSDOM(jsdomOptions); return Object.assign(jsdom, { loaded: jsdom.loaded.then( () => jsdom.window.evalFn( async () => { const {createElement} = require('react'); const {render} = require('react-dom'); return await window.eval(`import('${componentPath}')`).then((Component: any) => { render(createElement(Component.default || Component, reactProps), document.body.appendChild(document.createElement('div'))); }); }, {componentPath, reactProps})) }); } public loaded: Promise<jsdom.DOMWindow>; constructor(options: RapidsJSDOMOptions = {}) { const opts = Object.assign({}, RapidsJSDOM.defaultOptions, options); const {path: dir = process.cwd()} = opts.module ?? require.main ?? module; const babel = Object.assign( {}, RapidsJSDOM.defaultOptions.babel, !opts.babel ? {} : opts.babel, {cwd: dir}); const {url, tmpdir} = createObjectUrlAndTmpDir(); const imageLoader = new ImageLoader(url, dir); super(undefined, { ...opts, url, resources: imageLoader, pretendToBeVisual: true, runScripts: options.runScripts ?? 'outside-only', beforeParse: (window) => { if (opts.reportUnhandledExceptions) { // installUnhandledExceptionListeners(); } const { frameRate, glfwOptions, onAnimationFrameRequested = defaultFrameScheduler(window, frameRate), } = opts; window = [ installWorker, installGLFWWindow(glfwOptions), installAnimationFrame(onAnimationFrameRequested), installJSDOMUtils({ dir, createContext: createContextFactory(window, dir), resolve: createResolve({ ...opts.resolvers, ...mjolnirHammerResolvers(), ...reactMapGLMapboxResolvers(), }), }) ].reduce((window, fn) => fn(window), window); const polyfillFetchPath = require.resolve('./polyfills/fetch'); const polyfillImagePath = require.resolve('./polyfills/image'); const polyfillCanvasPath = require.resolve('./polyfills/canvas'); const polyfillStreamsPath = require.resolve('./polyfills/streams'); const polyfillObjectURLPath = require.resolve('./polyfills/object-url'); const polyfillTransformPath = require.resolve('./polyfills/modules/transform'); window.evalFn(() => { const {createTransform} = require(polyfillTransformPath) as typeof import('./polyfills/modules/transform'); const {extensions: _extensions, transform: _transform} = createTransform({ ...babel, preTransform(path: string, code: string) { // prepend a fix for mapbox-gl's serialization code if (path.includes('mapbox-gl/dist/mapbox-gl') || path.includes('maplibre-gl/dist/maplibre-gl')) { return `\ Object.defineProperty(({}).constructor, '_classRegistryKey', {value: 'Object', writable: false}); ${code}`; } return code; } }); Object.assign(window.jsdom.global.require, {extensions: _extensions}); Object.assign(window.jsdom.global.require.main, {_extensions, _transform}); const {installFetch} = require(polyfillFetchPath) as typeof import('./polyfills/fetch'); const {installImageData, installImageDecode} = require(polyfillImagePath) as typeof import('./polyfills/image'); const {installGetContext} = require(polyfillCanvasPath) as typeof import('./polyfills/canvas'); const {installStreams} = require(polyfillStreamsPath) as typeof import('./polyfills/streams'); const {installObjectURL} = require(polyfillObjectURLPath) as typeof import('./polyfills/object-url'); [installFetch, installStreams, installObjectURL(tmpdir), installImageData, installImageDecode, installGetContext, ].reduce((window, fn) => fn(window), window); imageLoader.svg2img = (require('svg2img')) as typeof import('svg2img').default; }, { babel, tmpdir, frameRate, glfwOptions, imageLoader, polyfillFetchPath, polyfillImagePath, polyfillCanvasPath, polyfillStreamsPath, polyfillObjectURLPath, polyfillTransformPath, onAnimationFrameRequested, }); } }); this.loaded = Promise.resolve(this.window); } } function installUnhandledExceptionListeners() { process.on('uncaughtException' as any, (err: Error, origin: any) => { /* eslint-disable @typescript-eslint/restrict-template-expressions */ process.stderr.write(`Uncaught Exception\n` + (origin ? `Origin: ${origin}\n` : '') + `Exception: ${err && err.stack || err}\n`); }); process.on('unhandledRejection' as any, (err: Error, promise: any) => { /* eslint-disable @typescript-eslint/restrict-template-expressions */ process.stderr.write(`Unhandled Promise Rejection\n` + (promise ? `Promise: ${promise}\n` : '') + `Exception: ${err && err.stack || err}\n`); }); }
0
rapidsai_public_repos/node/modules/jsdom
rapidsai_public_repos/node/modules/jsdom/src/resourceloader.ts
// Copyright (c) 2021-2022, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as webp from '@cwasm/webp'; import * as jsdom from 'jsdom'; import * as Url from 'url'; export class ImageLoader extends jsdom.ResourceLoader { declare private _svg2img: typeof import('svg2img').default; public set svg2img(f: typeof import('svg2img').default) { this._svg2img = f; } constructor(private _url: string, private _cwd: string) { super(); } fetch(url: string, options: jsdom.FetchOptions) { // Hack since JSDOM 16.2.2: If loading a relative file // from our dummy localhost URI, translate to a file:// URI. if (url.startsWith(this._url)) { // url = url.slice(this._url.length); } const isDataURL = url && url.startsWith('data:'); if (isDataURL) { const result = this._loadDataURL(url, options); if (result) { return <any>result; } } const isFilePath = url && !isDataURL && !Url.parse(url).protocol; if (isFilePath) { // if (url.startsWith('/')) { url = url.slice(1); } return super.fetch(`file://${this._cwd}/${url}`, options); } return super.fetch(url, options); } private _loadDataURL(url: string, options: jsdom.FetchOptions) { const {mediaType, encoding, contents} = parseDataURLPrefix(url); switch (mediaType) { case 'image/webp': // return loadWebpDataUrl(webp, encoding, contents); case 'image/svg+xml': // return loadSVGDataUrl(this._svg2img, encoding, contents, options); default: break; } return undefined; } } function parseDataURLPrefix(url: string) { const comma = url.indexOf(',', 5); const prefix = url.slice(5, url.indexOf(',', 5)); let mediaType = 'text/plain'; let encoding = ''; [mediaType, encoding] = prefix.indexOf(';') ? prefix.split(';') : [prefix, '']; return {mediaType, encoding, prefix, contents: url.slice(comma + 1)}; } function loadSVGDataUrl(svg2img: typeof import('svg2img').default, encoding: string, contents: string, {element}: jsdom.FetchOptions) { const options = {width: element?.offsetWidth, height: element?.offsetHeight}; const data = (() => { switch (encoding) { case 'base64': // return Buffer.from(contents).toString('base64'); default: return decodeURIComponent(contents).trim(); } })(); return new Promise<Buffer>((resolve, reject) => { svg2img(data, options, (err, data: Buffer) => { // err == null ? resolve(data) : reject(err); }); }); } function loadWebpDataUrl(webp: typeof import('@cwasm/webp'), encoding: string, contents: string) { const data = (() => { switch (encoding) { case 'base64': // return Buffer.from(contents, 'base64'); default: return Buffer.from(decodeURIComponent(contents).trim()); } })(); return new Promise<ImageData>((resolve, reject) => { try { resolve(webp.decode(data)); } catch (e) { reject(e); } }); }
0
rapidsai_public_repos/node/modules/jsdom/src
rapidsai_public_repos/node/modules/jsdom/src/polyfills/streams.ts
// Copyright (c) 2021-2022, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as jsdom from 'jsdom'; export function installStreams(window: jsdom.DOMWindow) { const streams = require('web-streams-polyfill'); window.jsdom.global.ReadableStream ??= streams.ReadableStream; window.jsdom.global.WritableStream ??= streams.WritableStream; window.jsdom.global.TransformStream ??= streams.TransformStream; window.jsdom.global.CountQueuingStrategy ??= streams.CountQueuingStrategy; window.jsdom.global.ByteLengthQueuingStrategy ??= streams.ByteLengthQueuingStrategy; return window; }
0
rapidsai_public_repos/node/modules/jsdom/src
rapidsai_public_repos/node/modules/jsdom/src/polyfills/image.ts
// Copyright (c) 2021-2022, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as jsdom from 'jsdom'; export function installImageData(window: jsdom.DOMWindow) { window.jsdom.global.ImageData ??= require('canvas').ImageData; return window; } export function installImageDecode(window: jsdom.DOMWindow) { // eslint-disable-next-line @typescript-eslint/unbound-method window.HTMLImageElement.prototype.decode ??= function decode(this: HTMLImageElement) { return new Promise<void>((resolve, reject) => { const cleanup = () => { this.removeEventListener('load', onload); this.removeEventListener('error', onerror); }; const onload = () => { resolve(); cleanup(); }; const onerror = () => { reject(); cleanup(); }; this.addEventListener('load', onload); this.addEventListener('error', onerror); }); }; return window; }
0
rapidsai_public_repos/node/modules/jsdom/src
rapidsai_public_repos/node/modules/jsdom/src/polyfills/object-url.ts
// Copyright (c) 2021-2022, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {mkdtempSync, unlinkSync, writeFileSync} from 'fs'; import * as jsdom from 'jsdom'; import * as os from 'os'; import * as Path from 'path'; export function createObjectUrlAndTmpDir() { const tmpdir = mkdtempSync(os.tmpdir() + Path.sep); const url = `http://${Path.basename(tmpdir)}/`.toLowerCase(); return {url, tmpdir}; } export function installObjectURL(tmpdir: string) { return function installObjectURL(window: jsdom.DOMWindow) { let filesCount = 0; const map = new Map<URL, string>(); window.jsdom.global.URL ??= window.URL; [window.URL, window.jsdom.global.URL].forEach((URL) => { URL.createObjectURL ??= createObjectURL; URL.revokeObjectURL ??= revokeObjectURL; }); return window; function createObjectURL(blob: Blob) { const path = Path.join(tmpdir, `${filesCount++}`); writeFileSync(path, window.jsdom.utils.implForWrapper(blob)._buffer); const url = new window.jsdom.global.URL(`file://${path}`); map.set(url, path); return url; } function revokeObjectURL(url: any) { if (map.has(url)) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const p = map.get(url)!; map.delete(url); unlinkSync(p); } } }; }
0
rapidsai_public_repos/node/modules/jsdom/src
rapidsai_public_repos/node/modules/jsdom/src/polyfills/worker.ts
// Copyright (c) 2022, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as fs from 'fs'; import * as jsdom from 'jsdom'; import {Worker, WorkerOptions} from 'worker_threads'; export function installWorker(window: jsdom.DOMWindow) { window.Worker = class JSDOMWorker extends Worker { constructor(filename: string|URL, options?: WorkerOptions) { // /* eslint-disable-next-line @typescript-eslint/restrict-template-expressions */ if (`${filename}`.startsWith('file:')) { const contents = fs.readFileSync(filename, 'utf8'); if (!contents.startsWith('// rapidsai_jsdom_worker_preamble')) { /* eslint-disable-next-line @typescript-eslint/restrict-template-expressions */ fs.writeFileSync(filename, injectPreamble(`${filename}`, contents)); } } super(filename, options); } addEventListener(...[type, handler]: Parameters<Worker['addListener']>) { return this.addListener(type, handler); } removeEventListener(...[type, handler]: Parameters<Worker['removeListener']>) { return this.removeListener(type, handler); } }; return window; } function injectPreamble(filename: string, code: string) { return `// rapidsai_jsdom_worker_preamble const Url = require('url'); const Path = require('path'); const {Blob} = require('buffer'); const syncRequest = require('${require.resolve('sync-request')}'); class ImageData { constructor(data, width, height, settings) { if(typeof data === 'number') { settings = height, height = width, width = data, data = undefined; } if (data) { if (data.byteLength === 0) throw new RangeError("The input data has a zero byte length"); const pitch = (() => { if (data instanceof Uint16Array) { return 2; } if (data instanceof Uint8Array) { return 4; } if (data instanceof Uint8ClampedArray) { return 4; } throw new TypeError('Expected (Uint8ClampedArray, width[, height]), (Uint16Array, width[, height]) or (width, height)'); })(); if (typeof width !== 'number' || width !== width) throw new RangeError("The source width is zero"); if (typeof height !== 'number' || height !== height) height = (data.byteLength / pitch) / width; data = new Uint8ClampedArray(data.buffer); } else { if (typeof width !== 'number' || width !== width) throw new RangeError("The source width is zero"); if (typeof height !== 'number' || height !== height) throw new RangeError("The source height is zero"); data = new Uint8ClampedArray(width * height * 4); } this.data = data; this.width = width; this.height = height; } } const {parentPort} = require('worker_threads'); class WorkerGlobalScope extends require('events') { constructor(global) { super(); this.self = global; this.origin = '${filename}'; if (!global.fetch) { const {Headers, Request, Response, fetch} = require('${require.resolve('cross-fetch')}'); this.fetch = fetch; this.Headers = Headers; this.Request = Request; this.Response = Response; } const messageHandlersMap = new Map(); this.addEventListener = (type, handler) => { if (type === 'message') { const h = (data) => { handler({data}); }; messageHandlersMap.set(handler, h); parentPort.addListener(type, h); } else { this.addListener(type, handler); } } this.removeEventListener = (type, handler) => { if (type === 'message') { const h = messageHandlersMap.get(handler); messageHandlersMap.delete(handler); parentPort.removeListener(type, h); } else { this.removeListener(type, handler); } } Object.setPrototypeOf(global, this); } importScripts(...xs) { xs.filter(Boolean).forEach(x => { const isDataURI = x && x.startsWith('data:'); const isFilePath = x && !isDataURI && !Url.parse(x).protocol; if(isDataURI || isFilePath) { require(x); } else { eval(syncRequest('GET', x, {}).getBody('utf-8')); } }); } postMessage(data, ...xs) { parentPort.postMessage({data}, ...xs); } } global.self = new WorkerGlobalScope(Object.assign(global, {ImageData})).self; ${code}`; }
0
rapidsai_public_repos/node/modules/jsdom/src
rapidsai_public_repos/node/modules/jsdom/src/polyfills/raf.ts
// Copyright (c) 2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {glfw} from '@rapidsai/glfw'; import * as jsdom from 'jsdom'; export interface AnimationFrameRequest { active: boolean; flush: (onAnimationFrameFlushed?: AnimationFrameFlushedCallback) => void; } export type AnimationFrameFlushedCallback = (startTime: number, flushTime: number, frameTime: number) => any; export type AnimationFrameRequestedCallback = (request: AnimationFrameRequest) => any; const notMacOs = process.platform !== 'darwin'; export function installAnimationFrame(onAnimationFrameRequested: AnimationFrameRequestedCallback) { return (window: jsdom.DOMWindow) => { let callbacks0 = new Map<(time: number) => any, any>(); let callbacks1 = new Map<(time: number) => any, any>(); let callbacks = callbacks0; const startTime = window.performance.now(); const request = {active: false, flush: flushAnimationFrame}; const refresh = () => requestAnimationFrame(); window.addEventListener('move', refresh); window.addEventListener('resize', refresh); window.addEventListener('refresh', refresh); window.addEventListener('close', () => { window.removeEventListener('move', refresh); window.removeEventListener('resize', refresh); window.removeEventListener('refresh', refresh); }, {once: true}); return Object.assign(window, {requestAnimationFrame, cancelAnimationFrame}); function cancelAnimationFrame(cb?: (time: number) => any) { typeof cb === 'function' && callbacks.delete(cb); request.active = callbacks.size > 0; } function requestAnimationFrame(cb?: (endTime: number) => any) { typeof cb === 'function' && callbacks.set(cb, null); if (!request.active) { // onAnimationFrameRequested(Object.assign(request, {active: true})); } return cb; } function flushAnimationFrame(onAnimationFrameFlushed?: AnimationFrameFlushedCallback) { const flushTime = window.performance.now(); if (request.active) { request.active = false; const id = window.id; const initialState = window._clearMask || 0; // hack: reset the private `gl._clearMask` field so we know whether // to call swapBuffers() after all the listeners have been executed window._clearMask = 0; if (id > 0 && glfw.getCurrentContext() !== id) { glfw.makeContextCurrent(id); } if (callbacks.size > 0) { if (callbacks === callbacks0) { callbacks = callbacks1; callbacks0.forEach((_, cb) => cb(flushTime - startTime)); callbacks0 = new Map<(endTime: number) => any, any>(); } else { callbacks = callbacks0; callbacks1.forEach((_, cb) => cb(flushTime - startTime)); callbacks1 = new Map<(endTime: number) => any, any>(); } } const resultState = window._clearMask || 0; // Fix for MacOS: only swap buffers if gl.clear() was called const shouldSwap = notMacOs || (initialState || resultState); window._clearMask = 0; if (id > 0 && shouldSwap) { glfw.swapBuffers(id); } } if (typeof onAnimationFrameFlushed === 'function') { onAnimationFrameFlushed(startTime, flushTime, window.performance.now() - flushTime); } // glfw.pollEvents(); } }; } export function defaultFrameScheduler(window: jsdom.DOMWindow, fps = 60) { let request: AnimationFrameRequest|null = null; let interval: any = setInterval(() => { if (request) { const f = request.flush; request = null; f(() => {}); } window.poll && window.poll(); }, 1000 / fps); window.addEventListener('close', () => { interval && clearInterval(interval); request = interval = null; }, {once: true}); return (r_: AnimationFrameRequest) => { request = r_; }; }
0
rapidsai_public_repos/node/modules/jsdom/src
rapidsai_public_repos/node/modules/jsdom/src/polyfills/fetch.ts
// Copyright (c) 2021-2022, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as jsdom from 'jsdom'; import * as Path from 'path'; import * as Url from 'url'; export function installFetch(window: jsdom.DOMWindow) { const cwd: string = window.jsdom.global.__cwd; const { Headers, Request, Response, fetch, } = require('cross-fetch') as typeof import('cross-fetch'); window.jsdom.global.Headers = Headers; window.jsdom.global.Request = Request; window.jsdom.global.Response = Response; window.jsdom.global.fetch = function fileAwareFetch(url: string|Request, options: RequestInit = {}) { if (typeof url !== 'string' && ((url instanceof Request) || ('url' in url))) { return fetch(url, options); } const isDataURI = url && url.startsWith('data:'); const isFilePath = url && !isDataURI && !Url.parse(url).protocol; if (isFilePath) { if (url.startsWith('/')) { url = url.slice(1); } const loader = new jsdom.ResourceLoader(); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return loader .fetch(`file://localhost/${cwd}/${url}`, options)! // .then((x) => new Response(x, { status: 200, headers: { 'Content-Type': contentTypeFromPath(url as string), } })); } const headers = new Headers(options.headers || {}); if (!headers.has('User-Agent')) { // headers.append('User-Agent', window.navigator.userAgent); } return fetch(url, {...options, headers}); }; return window; } function contentTypeFromPath(url: string) { switch (Path.parse(url).ext) { case '.jpg': return 'image/jpeg'; case '.jpeg': return 'image/jpeg'; case '.gif': return 'image/gif'; case '.png': return 'image/png'; case '.txt': return 'text/plain'; case '.svg': return 'image/svg'; case '.json': return 'application/json'; case '.wasm': return 'application/wasm'; default: return 'application/octet-stream'; } }
0
rapidsai_public_repos/node/modules/jsdom/src
rapidsai_public_repos/node/modules/jsdom/src/polyfills/jsdom.ts
// Copyright (c) 2021-2023, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as jsdom from 'jsdom'; import * as Module from 'module'; import { createContextRequire as createRequire, CreateContextRequireOptions } from './modules/require'; declare module 'jsdom' { // clang-format off interface DOMWindow { import: (specifier: string) => Promise<any>; evalFn: <T>(script: () => T, globals?: Record<string, any>) => T; } // clang-format on } export function installJSDOMUtils(options: { createContext: (globals?: Record<string, any>) => import('vm').Context, }&Pick<CreateContextRequireOptions, 'dir'|'resolve'|'transform'|'extensions'>) { return (window: jsdom.DOMWindow) => { const {createContext} = options; const require = window.jsdom.global.require = createRequire({...options, context: createContext()}); window.import = window.jsdom.global.import = (specifier: string) => require.main._cachedDynamicImporter(specifier).then((m: any) => m.namespace); if (window.jsdom.utils.implForWrapper(window.document)._origin === 'null') { window.jsdom.utils.implForWrapper(window.document)._origin = ''; } window.evalFn = (f: () => any, globals: Record<string, any> = {}) => { const exports = {}; const context = createContext(globals); const source = `return (${f.toString()}).call(this);`; const filename = `evalmachine.<${f.name || 'anonymous'}>`; return require.main .exec(require, Module.wrap(source), filename, context) // .call(exports, exports, require, require.main, filename, '.'); }; return window; }; }
0
rapidsai_public_repos/node/modules/jsdom/src
rapidsai_public_repos/node/modules/jsdom/src/polyfills/glfw.ts
// Copyright (c) 2021-2022, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { glfw, GLFW, GLFWClientAPI, GLFWContextCreationAPI, GLFWInputMode, GLFWModifierKey, GLFWMouseButton, GLFWOpenGLProfile, GLFWStandardCursor, GLFWWindowAttribute, isHeadless, } from '@rapidsai/glfw'; import * as jsdom from 'jsdom'; import {performance} from 'perf_hooks'; import {Subscription} from 'rxjs'; import {dndEvents, GLFWDndEvent} from './events/dnd'; import {isAltKey, isCapsLock, isCtrlKey, isMetaKey, isShiftKey} from './events/event'; import {GLFWKeyboardEvent, keyboardEvents} from './events/keyboard'; import {GLFWMouseEvent, mouseEvents} from './events/mouse'; import {GLFWWheelEvent, wheelEvents} from './events/wheel'; import {GLFWWindowEvent, windowEvents} from './events/window'; let rootWindow: jsdom.DOMWindow|undefined = undefined; const childWindows = new Map<number, jsdom.DOMWindow>(); export type GLFWWindowOptions = Partial<{ x: number; // y: number; // scrollX: number; // scrollY: number; // swapInterval: number; // width: number; // height: number; // xscale: number; // yscale: number; // devicePixelRatio: number; // frameBufferWidth: number; // frameBufferHeight: number; // focused: boolean; // visible: boolean; // decorated: boolean; // maximized: boolean; // minimized: boolean; // resizable: boolean; // transparent: boolean; // forceNewWindow: boolean; // title: string; // debug: boolean; // openGLMajorVersion: number; // openGLMinorVersion: number; // openGLForwardCompat: boolean; // openGLClientAPI: GLFWClientAPI; // openGLProfile: GLFWOpenGLProfile; // openGLContextCreationAPI: GLFWContextCreationAPI; // }>; export function installGLFWWindow(windowOptions: GLFWWindowOptions = {}) { return (window: jsdom.DOMWindow) => { // Attatching properties let _id = 0; let _cursor = 0; let _mouseX = 0; let _mouseY = 0; let _buttons = 0; let _modifiers = 0; let _gl: any = null; let _mouseInWindow = false; let _subscriptions = new Subscription(); let { x: _x = 0, y: _y = 0, scrollX: _scrollX = 0, scrollY: _scrollY = 0, swapInterval: _swapInterval = 0, width: _width = 800, height: _height = 600, xscale: _xscale = 1, yscale: _yscale = 1, devicePixelRatio: _devicePixelRatio = 1, frameBufferWidth: _frameBufferWidth = _width * _devicePixelRatio, frameBufferHeight: _frameBufferHeight = _height * _devicePixelRatio, focused: _focused = !isHeadless, visible: _visible = !isHeadless, decorated: _decorated = !isHeadless, maximized: _maximized = false, minimized: _minimized = false, resizable: _resizable = !isHeadless, title: _title = 'Untitled', } = windowOptions; const { transparent: _transparent = false, forceNewWindow: _forceNewWindow = false, debug: _debug = false, openGLMajorVersion: _openGLMajorVersion = 4, openGLMinorVersion: _openGLMinorVersion = 6, openGLForwardCompat: _openGLForwardCompat = true, openGLClientAPI: _openGLClientAPI = GLFWClientAPI.OPENGL, openGLProfile: _openGLProfile = GLFWOpenGLProfile.ANY, openGLContextCreationAPI: _openGLContextCreationAPI = GLFWContextCreationAPI.EGL, } = windowOptions; Object.defineProperties(window, { id: { enumerable: true, configurable: false, get() { return _id; }, }, debug: { enumerable: true, configurable: false, get() { return _debug; }, }, xscale: { enumerable: true, configurable: false, get() { return _xscale; }, }, yscale: { enumerable: true, configurable: false, get() { return _yscale; }, }, focused: { enumerable: true, configurable: false, get() { return _focused; }, }, minimized: { enumerable: true, configurable: false, get() { return _minimized; }, }, maximized: { enumerable: true, configurable: false, get() { return _maximized; }, }, matchMedia: { enumerable: true, configurable: true, value: undefined, }, performance: { writable: false, enumerable: true, configurable: true, value: performance, }, transparent: { enumerable: true, configurable: false, get() { return _transparent; }, }, altKey: { enumerable: true, configurable: false, get() { return isAltKey(_modifiers); }, }, ctrlKey: { enumerable: true, configurable: false, get() { return isCtrlKey(_modifiers); }, }, metaKey: { enumerable: true, configurable: false, get() { return isMetaKey(_modifiers); }, }, shiftKey: { enumerable: true, configurable: false, get() { return isShiftKey(_modifiers); }, }, capsLock: { enumerable: true, configurable: false, get() { return isCapsLock(_modifiers); }, }, style: { enumerable: true, configurable: false, get() { // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; return { get width() { return self.width; }, set width(_: any) { self.width = _; }, get height() { return self.height; }, set height(_: any) { self.height = _; }, get cursor() { return self.cursor; }, set cursor(_: any) { self.cursor = _; }, }; } }, devicePixelRatio: { enumerable: true, configurable: false, get() { return _devicePixelRatio; }, }, frameBufferWidth: { enumerable: true, configurable: false, get() { return _frameBufferWidth; }, }, frameBufferHeight: { enumerable: true, configurable: false, get() { return _frameBufferHeight; }, }, openGLProfile: { enumerable: true, configurable: false, get() { return _openGLProfile; }, }, openGLClientAPI: { enumerable: true, configurable: false, get() { return _openGLClientAPI; }, }, openGLMajorVersion: { enumerable: true, configurable: false, get() { return _openGLMajorVersion; }, }, openGLMinorVersion: { enumerable: true, configurable: false, get() { return _openGLMinorVersion; }, }, openGLForwardCompat: { enumerable: true, configurable: false, get() { return _openGLForwardCompat; }, }, openGLContextCreationAPI: { enumerable: true, configurable: false, get() { return _openGLContextCreationAPI; }, }, }); Object.defineProperties(window, { x: { enumerable: true, configurable: false, get() { return _x; }, set(this: jsdom.DOMWindow, _: any) { if ((_ = cssToNumber(this, 'x', _)) !== _x) { _x = _; if (_id > 0) { glfw.setWindowPos(_id, {x: _x, y: _y}); } } }, }, y: { enumerable: true, configurable: false, get() { return _y; }, set(this: jsdom.DOMWindow, _: any) { if ((_ = cssToNumber(this, 'y', _)) !== _y) { _y = _; if (_id > 0) { glfw.setWindowPos(_id, {x: _x, y: _y}); } } }, }, width: { enumerable: true, configurable: false, get() { return _width; }, set(this: jsdom.DOMWindow, _: any) { if ((_ = cssToNumber(this, 'width', _)) !== _width) { _width = _; if (_id > 0) { glfw.setWindowSize(_id, {width: _width, height: _height}); } } }, }, height: { enumerable: true, configurable: false, get() { return _height; }, set(this: jsdom.DOMWindow, _: any) { if ((_ = cssToNumber(this, 'height', _)) !== _height) { _height = _; if (_id > 0) { glfw.setWindowSize(_id, {width: _width, height: _height}); } } }, }, title: { enumerable: true, configurable: false, get() { return _title; }, set(this: jsdom.DOMWindow, _: string) { _title = _; if (_id > 0) { glfw.setWindowTitle(_id, _title); } }, }, swapInterval: { enumerable: true, configurable: false, get(this: jsdom.DOMWindow) { return _swapInterval; }, set(this: jsdom.DOMWindow, _: number) { if (_swapInterval !== _) { if (_id > 0 && typeof _ === 'number') { // glfw.swapInterval(_swapInterval = _); } } }, }, visible: { enumerable: true, configurable: false, get(this: jsdom.DOMWindow) { return _visible; }, set(this: jsdom.DOMWindow, _: boolean) { if (!isHeadless && _visible !== _) { _visible = _; _visible ? window.show() : window.hide(); } }, }, decorated: { enumerable: true, configurable: false, get(this: jsdom.DOMWindow) { return _decorated; }, set(this: jsdom.DOMWindow, _: boolean) { if (_decorated !== _) { _decorated = _; if (_id > 0) { glfw.setWindowAttrib(_id, GLFWWindowAttribute.DECORATED, _); } } } }, resizable: { enumerable: true, configurable: false, get(this: jsdom.DOMWindow) { return _resizable; }, set(this: jsdom.DOMWindow, _: boolean) { if (_resizable !== _) { _resizable = _; if (_id > 0) { glfw.setWindowAttrib(_id, GLFWWindowAttribute.RESIZABLE, _); } } } }, cursor: { enumerable: true, configurable: false, get(this: jsdom.DOMWindow) { return _cursor; }, set(this: jsdom.DOMWindow, _: any) { _ = (() => { switch (_) { case 'pointer': return GLFWStandardCursor.HAND; case 'text': return GLFWStandardCursor.IBEAM; case 'crosshair': return GLFWStandardCursor.CROSSHAIR; case 'e-resize': case 'w-resize': case 'ew-resize': return GLFWStandardCursor.HRESIZE; case 'n-resize': case 's-resize': case 'ns-resize': return GLFWStandardCursor.VRESIZE; case 'auto': case 'none': case 'grab': case 'grabbing': case 'default': return GLFWStandardCursor.ARROW; default: { let key: keyof typeof GLFWStandardCursor; for (key in GLFWStandardCursor) { if (_ === GLFWStandardCursor[key]) { // return GLFWStandardCursor[key]; } } return GLFWStandardCursor.ARROW; } } })(); if (_cursor !== _) { _cursor = _; if (_id > 0) { switch (_) { case GLFWStandardCursor.ARROW: case GLFWStandardCursor.IBEAM: case GLFWStandardCursor.CROSSHAIR: case GLFWStandardCursor.HAND: case GLFWStandardCursor.HRESIZE: case GLFWStandardCursor.VRESIZE: glfw.setCursor(_id, _); break; default: break; } } } } }, mouseX: { enumerable: true, configurable: false, get() { return _mouseX; }, set(_: number) { _mouseX = _; }, }, mouseY: { enumerable: true, configurable: false, get() { return _mouseY; }, set(_: number) { _mouseY = _; }, }, mouseInWindow: { enumerable: true, configurable: false, get() { return _mouseInWindow; }, set(_: boolean) { _mouseInWindow = _; }, }, buttons: { enumerable: true, configurable: false, get() { return _buttons; }, set(_: number) { _buttons = _; }, }, scrollX: { enumerable: true, configurable: false, get() { return _scrollX; }, set(_: number) { _scrollX = _; }, }, scrollY: { enumerable: true, configurable: false, get() { return _scrollY; }, set(_: number) { _scrollY = _; }, }, modifiers: { enumerable: true, configurable: false, get() { return _modifiers; }, set(_: number) { _modifiers = _; }, }, _gl: { enumerable: false, configurable: false, get() { return _gl; }, set(this: jsdom.DOMWindow, _: any) { _gl = _; }, }, _clearMask: { enumerable: false, configurable: false, get() { return _gl ? _gl._clearMask : 0; }, set(_: any) { _gl && (_gl._clearMask = _); }, }, }); defineDOMEventListenerProperties(window, [ 'onblur', 'onfocus', 'onmove', 'onresize', 'onkeyup', 'onkeydown', 'onmousedown', 'onmouseup', 'onmousemove', 'onmouseenter', 'onmouseleave', 'onwheel', ]); defineDOMElementPropertyAliases(window.MouseEvent.prototype, [ {name: 'clientX', aliases: ['offsetX']}, {name: 'clientY', aliases: ['offsetY']}, ]); defineDOMElementPropertyAliases(window, [ {name: 'y', aliases: ['screenY', 'screenTop']}, {name: 'x', aliases: ['screenX', 'screenLeft']}, {name: 'scrollX', aliases: ['scrollLeft', 'pageXOffset']}, {name: 'scrollY', aliases: ['scrollTop', 'pageYOffset']}, {name: 'onwheel', aliases: ['onscroll', 'onmousewheel']}, { name: 'width', aliases: ['clientWidth', 'innerWidth', 'outerWidth', 'offsetWidth', 'scrollWidth'] }, { name: 'height', aliases: ['clientHeight', 'innerHeight', 'outerHeight', 'offsetHeight', 'scrollHeight'] }, ]); // Attaching functions window.setAttribute = function setAttribute(this: jsdom.DOMWindow, name: any, value: any) { if (name in this) { this[name] = value; } }.bind(window); window.getBoundingClientRect = function getBoundingClientRect(this: jsdom.DOMWindow) { return { x: 0, y: 0, width: this.width, height: this.height, left: 0, top: 0, right: this.width, bottom: this.height, }; }.bind(window); window.show = function show(this: jsdom.DOMWindow) { this.visible = true; glfw.showWindow(_id); return this; }.bind(window); window.hide = function hide(this: jsdom.DOMWindow) { this.visible = false; glfw.hideWindow(_id); return this; }.bind(window); window.poll = function poll(this: jsdom.DOMWindow) { if (_id > 0) { // fix for running in the node repl const {domain} = (global as any); const patchExit = (domain && typeof domain.exit !== 'function'); const patchEnter = (domain && typeof domain.enter !== 'function'); patchExit && (domain.exit = () => {}); patchEnter && (domain.enter = () => {}); glfw.pollEvents(); patchExit && (delete domain.exit); patchEnter && (delete domain.enter); } }.bind(window); window.dispatchEvent = function dispatchJSDOMEventAsGLFWEvent(this: jsdom.DOMWindow, event: any) { switch (event && event.type) { case 'close': { return this._dispatchGLFWWindowEventIntoDOM(GLFWWindowEvent.fromClose(this)); } case 'move': { const {x = _mouseX, y = _mouseY} = event; return this._dispatchGLFWWindowEventIntoDOM(GLFWWindowEvent.fromMove(this, x, y)); } case 'blur': { return this._dispatchGLFWWindowEventIntoDOM(GLFWWindowEvent.fromFocus(this, false)); } case 'focus': { return this._dispatchGLFWWindowEventIntoDOM(GLFWWindowEvent.fromFocus(this, true)); } case 'refresh': { return this._dispatchGLFWWindowEventIntoDOM(GLFWWindowEvent.fromRefresh(this)); } case 'resize': { const {width = _width, height = _height} = event; return this._dispatchGLFWWindowEventIntoDOM( GLFWWindowEvent.fromResize(this, width, height)); } case 'maximize': { return this._dispatchGLFWWindowEventIntoDOM(GLFWWindowEvent.fromMaximize(this, true)); } case 'minimize': { return this._dispatchGLFWWindowEventIntoDOM(GLFWWindowEvent.fromIconify(this, true)); } case 'restore': { return this._dispatchGLFWWindowEventIntoDOM(GLFWWindowEvent.fromIconify(this, false)); } case 'wheel': { const {deltaX = 0, deltaY = 0} = event; return this._dispatchGLFWWheelEventIntoDOM( GLFWWheelEvent.create(this, -deltaX / 10, -deltaY / 10)); } case 'keyup': case 'keydown': case 'keypress': { if ('scancode' in event) { const action = event.type === 'keyup' ? glfw.RELEASE : glfw.PRESS; return this._dispatchGLFWKeyboardEventIntoDOM(GLFWKeyboardEvent.fromKeyEvent( this, event.key, event.scancode, action, event.modifiers)); } return this._dispatchGLFWKeyboardEventIntoDOM( GLFWKeyboardEvent.fromDOMEvent(this, new window.KeyboardEvent(event.type, event))); } case 'mousemove': { const {x = _mouseX, y = _mouseY} = event; return this._dispatchGLFWMouseEventIntoDOM(GLFWMouseEvent.fromMouseMove(this, x, y)); } case 'mouseup': { const button = domToGLFWButton(event); if (button !== -1) { const {x = _mouseX, y = _mouseY} = event; event = GLFWMouseEvent.fromMouseButton(this, button, glfw.RELEASE, event.modifiers); return this._dispatchGLFWMouseEventIntoDOM(Object.assign(event, {_x: x, _y: y})); } return true; } case 'mousedown': { const button = domToGLFWButton(event); if (button !== -1) { const {x = _mouseX, y = _mouseY} = event; event = GLFWMouseEvent.fromMouseButton(this, button, glfw.PRESS, event.modifiers); return this._dispatchGLFWMouseEventIntoDOM(Object.assign(event, {_x: x, _y: y})); } return true; } case 'mouseenter': { const {x = _mouseX, y = _mouseY} = event; event = GLFWMouseEvent.fromMouseEnter(this, +true); return this._dispatchGLFWMouseEventIntoDOM(Object.assign(event, {_x: x, _y: y})); } case 'mouseleave': { const {x = _mouseX, y = _mouseY} = event; event = GLFWMouseEvent.fromMouseEnter(this, +false); return this._dispatchGLFWMouseEventIntoDOM(Object.assign(event, {_x: x, _y: y})); } default: break; } return true; function domToGLFWButton({button} = event || {}) { switch (button) { case 0: return GLFWMouseButton.MOUSE_BUTTON_LEFT; case 1: return GLFWMouseButton.MOUSE_BUTTON_MIDDLE; case 2: return GLFWMouseButton.MOUSE_BUTTON_RIGHT; default: return -1; } } }.bind(window); window.destroyGLFWWindow = function destroyGLFWWindow(this: jsdom.DOMWindow) { if (_id > 0) { const id = _id; _id = 0; if (!_forceNewWindow) { if (rootWindow === this) { rootWindow = undefined; childWindows.forEach((child) => child.destroyGLFWWindow()); childWindows.clear(); } else { childWindows.delete(id); } } if (_subscriptions) { // _subscriptions.unsubscribe(); } glfw.destroyWindow(id); } }.bind(window); window.createGLFWWindow = function createGLFWWindow(this: jsdom.DOMWindow) { try { glfw.windowHint(GLFWWindowAttribute.SAMPLES, 4); glfw.windowHint(GLFWWindowAttribute.DOUBLEBUFFER, true); glfw.windowHint(GLFWWindowAttribute.FOCUSED, window.focused); glfw.windowHint(GLFWWindowAttribute.FOCUS_ON_SHOW, window.focused); glfw.windowHint(GLFWWindowAttribute.VISIBLE, window.visible); glfw.windowHint(GLFWWindowAttribute.DECORATED, window.decorated); glfw.windowHint(GLFWWindowAttribute.RESIZABLE, window.resizable); glfw.windowHint(GLFWWindowAttribute.TRANSPARENT_FRAMEBUFFER, window.transparent); glfw.windowHint(GLFWWindowAttribute.CLIENT_API, window.openGLClientAPI); glfw.windowHint(GLFWWindowAttribute.OPENGL_DEBUG_CONTEXT, window.debug); glfw.windowHint(GLFWWindowAttribute.OPENGL_PROFILE, window.openGLProfile); glfw.windowHint(GLFWWindowAttribute.CONTEXT_VERSION_MAJOR, window.openGLMajorVersion); glfw.windowHint(GLFWWindowAttribute.CONTEXT_VERSION_MINOR, window.openGLMinorVersion); glfw.windowHint(GLFWWindowAttribute.OPENGL_FORWARD_COMPAT, window.openGLForwardCompat); glfw.windowHint(GLFWWindowAttribute.CONTEXT_CREATION_API, window.openGLContextCreationAPI); if (_forceNewWindow || !rootWindow) { _id = glfw.createWindow(window.width, window.height, window.title, null, null); } else { _id = glfw.createWindow(window.width, window.height, window.title, null, rootWindow.id); childWindows.set(_id, window); } glfw.setInputMode(window.id, GLFWInputMode.LOCK_KEY_MODS, true); glfw.setInputMode(window.id, GLFWInputMode.CURSOR, GLFW.CURSOR_NORMAL); glfw.makeContextCurrent(window.id); ({x: _x, y: _y} = glfw.getWindowPos(window.id)); ({width: _width, height: _height} = glfw.getWindowSize(window.id)); ({xscale: _xscale, yscale: _yscale} = glfw.getWindowContentScale(window.id)); ({width: _frameBufferWidth, height: _frameBufferHeight} = glfw.getFramebufferSize(window.id)); if (!_forceNewWindow && !rootWindow) { rootWindow = window; } if (_subscriptions) { _subscriptions.unsubscribe(); } _subscriptions = new Subscription(); window.cursor = _cursor; [dndEvents(window).subscribe(window._dispatchGLFWDropEventIntoDOM), mouseEvents(window).subscribe(window._dispatchGLFWMouseEventIntoDOM), wheelEvents(window).subscribe(window._dispatchGLFWWheelEventIntoDOM), windowEvents(window).subscribe(window._dispatchGLFWWindowEventIntoDOM), keyboardEvents(window).subscribe(window._dispatchGLFWKeyboardEventIntoDOM), ].forEach((subscription) => _subscriptions.add(subscription)); glfw.swapInterval(window.swapInterval); glfw.swapBuffers(window.id); window.poll(); } catch (e: any) { console.error(`Error creating GLFW window:\n${String(e && e.stack || e)}`); window.destroyGLFWWindow(); throw e; } return window; }.bind(window); window._dispatchGLFWDropEventIntoDOM = function dispatchGLFWDropEventIntoDOM( this: jsdom.DOMWindow, event: GLFWDndEvent) { return dispatchEventIntoDOM(this, event, this.Event); }.bind(window); window._dispatchGLFWMouseEventIntoDOM = function dispatchGLFWMouseEventIntoDOM( this: jsdom.DOMWindow, event: GLFWMouseEvent) { _mouseX = event.x; _mouseY = event.y; _buttons = event.buttons; _mouseInWindow = event.type !== 'mouseleave'; let m = _modifiers; m = event.altKey ? (m | GLFWModifierKey.MOD_ALT) : (m & ~GLFWModifierKey.MOD_ALT); m = event.ctrlKey ? (m | GLFWModifierKey.MOD_CONTROL) : (m & ~GLFWModifierKey.MOD_CONTROL); m = event.metaKey ? (m | GLFWModifierKey.MOD_SUPER) : (m & ~GLFWModifierKey.MOD_SUPER); m = event.shiftKey ? (m | GLFWModifierKey.MOD_SHIFT) : (m & ~GLFWModifierKey.MOD_SHIFT); m = event.capsLock ? (m | GLFWModifierKey.MOD_CAPS_LOCK) : (m & ~GLFWModifierKey.MOD_CAPS_LOCK); _modifiers = m; return dispatchEventIntoDOM(this, event, this.MouseEvent); }.bind(window); window._dispatchGLFWWheelEventIntoDOM = function dispatchGLFWWheelEventIntoDOM( this: jsdom.DOMWindow, event: GLFWWheelEvent) { _scrollX += event.deltaX; _scrollY += event.deltaY; return dispatchEventIntoDOM(this, event, this.WheelEvent); }.bind(window); window._dispatchGLFWWindowEventIntoDOM = function dispatchGLFWWindowEventIntoDOM( this: jsdom.DOMWindow, event: GLFWWindowEvent) { _x = event.x; _y = event.y; _width = event.width; _height = event.height; _xscale = event.xscale; _yscale = event.yscale; _focused = event.focused; _minimized = event.minimized; _maximized = event.maximized; _frameBufferWidth = event.frameBufferWidth; _frameBufferHeight = event.frameBufferHeight; _devicePixelRatio = Math.min(_frameBufferWidth / _width, _frameBufferHeight / _height); const result = dispatchEventIntoDOM(this, event, this.Event); if (event.type === 'close') { this.destroyGLFWWindow(); } return result; }.bind(window); window._dispatchGLFWKeyboardEventIntoDOM = function dispatchGLFWKeyboardEventIntoDOM( this: jsdom.DOMWindow, event: GLFWKeyboardEvent) { let m = _modifiers; m = event.altKey ? (m | GLFWModifierKey.MOD_ALT) : (m & ~GLFWModifierKey.MOD_ALT); m = event.ctrlKey ? (m | GLFWModifierKey.MOD_CONTROL) : (m & ~GLFWModifierKey.MOD_CONTROL); m = event.metaKey ? (m | GLFWModifierKey.MOD_SUPER) : (m & ~GLFWModifierKey.MOD_SUPER); m = event.shiftKey ? (m | GLFWModifierKey.MOD_SHIFT) : (m & ~GLFWModifierKey.MOD_SHIFT); m = event.capsLock ? (m | GLFWModifierKey.MOD_CAPS_LOCK) : (m & ~GLFWModifierKey.MOD_CAPS_LOCK); _modifiers = m; return dispatchEventIntoDOM(this, event, this.KeyboardEvent); }.bind(window); defineLayoutProps(window, window.Document.prototype); defineLayoutProps(window, window.HTMLElement.prototype); Object.defineProperties(window.SVGElement.prototype, { width: {get() { return {baseVal: {value: window.innerWidth}}; }}, height: {get() { return {baseVal: {value: window.innerHeight}}; }}, }); return window.createGLFWWindow(); }; } function dispatchEventIntoDOM(window: jsdom.DOMWindow, glfwEvent: any, EventCtor: any) { const target = window._inputEventTarget || window.document; if (target && target.dispatchEvent) { glfwEvent.target = target; const jsdomEvent = new EventCtor(glfwEvent.type, glfwEvent); const jsdomEventImpl = window.jsdom.utils.implForWrapper(jsdomEvent); for (const key in glfwEvent) { if (!key.startsWith('_')) { try { jsdomEventImpl[key] = glfwEvent[key]; } catch (e) { /**/ } } } return target.dispatchEvent(jsdomEvent); } return true; } function defineDOMEventListenerProperties(window: jsdom.DOMWindow, propertyNames: string[]) { propertyNames.forEach((name) => { const type = name.slice(2); const pname = Symbol(`_${name}Listener`); Object.defineProperty(window, name, { get() { return this[pname] || undefined; }, set(listener: (...args: any[]) => any) { if (typeof this[pname] === 'function') { this.removeEventListener(type, this[pname]); } if (typeof listener === 'function') { this[pname] = (e: any) => { e.preventDefault(); e.stopImmediatePropagation(); listener(e); }; this.addEventListener(type, this[pname], true); } } }); }); } function defineDOMElementPropertyAliases(element: any, aliases: {name: string, aliases: string[]}[]) { /* eslint-disable @typescript-eslint/unbound-method */ aliases.forEach(({name, aliases = []}) => { const descriptor = Object.getOwnPropertyDescriptor(element, name); if (descriptor) { descriptor.get = ((get) => get && function(this: any) { return get.call(this); })(descriptor.get); descriptor.set = ((set) => set && function(this: any, _: any) { return set.call(this, _); })(descriptor.set); aliases.forEach((alias) => Object.defineProperty(element, alias, descriptor)); } }); } function cssToNumber(window: jsdom.DOMWindow, prop: keyof jsdom.DOMWindow, value: any): number { switch (typeof value) { case 'number': return value; case 'string': { if (value.endsWith('px')) { return +(value.slice(0, -1)); } else if (value.endsWith('%')) { return +window[prop] * (+value.slice(0, -1) / 100); } } } return ((value = +value) !== value) ? +window[prop] : value; } function defineLayoutProps(window: jsdom.DOMWindow, proto: any) { ['width', 'height', 'screenY', 'screenX', 'screenTop', 'screenLeft', 'scrollTop', 'scrollLeft', 'scrollWidth', 'scrollHeight', 'pageXOffset', 'pageYOffset', 'clientWidth', 'clientHeight', 'innerWidth', 'innerHeight', 'outerWidth', 'outerHeight', 'offsetWidth', 'offsetHeight', ].forEach((k) => Object.defineProperty(proto, k, { get: () => window[k], set: () => {}, enumerable: true, configurable: true, })); proto.getBoundingClientRect = window.getBoundingClientRect.bind(window); return proto; }
0
rapidsai_public_repos/node/modules/jsdom/src
rapidsai_public_repos/node/modules/jsdom/src/polyfills/canvas.ts
// Copyright (c) 2021-2022, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as jsdom from 'jsdom'; export function installGetContext(window: jsdom.DOMWindow) { const gl = require('@rapidsai/webgl') as typeof import('@rapidsai/webgl'); // eslint-disable-next-line @typescript-eslint/unbound-method const JSDOM_getContext = window.HTMLCanvasElement.prototype.getContext; // Override Canvas's `getContext` method with one that initializes our WebGL bindings window.HTMLCanvasElement.prototype.getContext = getContext; class GLFWRenderingContext extends gl.WebGL2RenderingContext { constructor(canvas: HTMLCanvasElement, window: jsdom.DOMWindow, options?: WebGLContextAttributes) { super(options); this.canvas = canvas; this.window = window; if (!this.window._inputEventTarget) { this.window._inputEventTarget = canvas; } } private readonly window: jsdom.DOMWindow; public readonly canvas: HTMLCanvasElement; public get drawingBufferWidth() { return this.canvas.width; } public get drawingBufferHeight() { return this.canvas.height; } } window.jsdom.global.WebGLActiveInfo = gl.WebGLActiveInfo; window.jsdom.global.WebGLShaderPrecisionFormat = gl.WebGLShaderPrecisionFormat; window.jsdom.global.WebGLBuffer = gl.WebGLBuffer; window.jsdom.global.WebGLContextEvent = gl.WebGLContextEvent; window.jsdom.global.WebGLFramebuffer = gl.WebGLFramebuffer; window.jsdom.global.WebGLProgram = gl.WebGLProgram; window.jsdom.global.WebGLQuery = gl.WebGLQuery; window.jsdom.global.WebGLRenderbuffer = gl.WebGLRenderbuffer; window.jsdom.global.WebGLSampler = gl.WebGLSampler; window.jsdom.global.WebGLShader = gl.WebGLShader; window.jsdom.global.WebGLSync = gl.WebGLSync; window.jsdom.global.WebGLTexture = gl.WebGLTexture; window.jsdom.global.WebGLTransformFeedback = gl.WebGLTransformFeedback; window.jsdom.global.WebGLUniformLocation = gl.WebGLUniformLocation; window.jsdom.global.WebGLVertexArrayObject = gl.WebGLVertexArrayObject; window.jsdom.global.WebGLRenderingContext = GLFWRenderingContext; window.jsdom.global.WebGL2RenderingContext = GLFWRenderingContext; return window; type RenderingContextSettings = CanvasRenderingContext2DSettings|ImageBitmapRenderingContextSettings|WebGLContextAttributes; function getContext(contextId: '2d', options?: CanvasRenderingContext2DSettings): CanvasRenderingContext2D|null; function getContext(contextId: 'bitmaprenderer', options?: ImageBitmapRenderingContextSettings): ImageBitmapRenderingContext|null; function getContext(contextId: 'webgl', options?: WebGLContextAttributes): WebGLRenderingContext| null; function getContext(contextId: 'webgl2', options?: WebGLContextAttributes): WebGL2RenderingContext|null; function getContext(this: any, ...args: [ '2d'|'bitmaprenderer'|'webgl'|'webgl2'|'experimental-webgl', RenderingContextSettings? ]): RenderingContext|null { const [type, settings = {}] = args; switch (type) { case 'webgl': case 'webgl2': case 'experimental-webgl': { if (!this.gl) { // this.gl = new GLFWRenderingContext(this, window, settings); if (!window._gl) { window._gl = this.gl; } } return this.gl; } default: return JSDOM_getContext.apply(this, <any>args); } } }
0
rapidsai_public_repos/node/modules/jsdom/src/polyfills
rapidsai_public_repos/node/modules/jsdom/src/polyfills/modules/mjolnir.ts
// Copyright (c) 2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as Module from 'module'; export function mjolnirHammerResolvers() { return { 'mjolnir.js/src/utils/hammer': mjolnirHammerResolver, 'mjolnir.js/dist/es5/utils/hammer': mjolnirHammerResolver, 'mjolnir.js/dist/esm/utils/hammer': mjolnirHammerResolver, }; } function mjolnirHammerResolver(request: string, ...args: any[]) { request = request.replace('hammer', 'hammer.browser'); return (Module as any)._resolveFilename(request, ...args); }
0
rapidsai_public_repos/node/modules/jsdom/src/polyfills
rapidsai_public_repos/node/modules/jsdom/src/polyfills/modules/transform.ts
// Copyright (c) 2021-2022, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as babel from '@babel/core'; import * as fs from 'fs'; import * as Module from 'module'; import * as Path from 'path'; const cloneDeep = require('clone-deep'); const sourceMapSupport = require('source-map-support'); export type Transform = (path: string, code: string) => string; const identityTransform: Transform = (_: string, code: string) => code; export function createTransform({preTransform = identityTransform, ...opts}: {preTransform?: Transform}&Partial<babel.TransformOptions> = {}) { let transform = preTransform; if (opts) { const maps: any = {}; const transformOpts = normalizeOptions(opts); const installSourceMaps = supportSourceMaps(maps); transform = (path: string, code: string) => { const content = preTransform(path, code); // merge in base options and resolve all the plugins and presets relative to this file const compileOpts = babel.loadOptions({ // sourceRoot can be overwritten sourceRoot: Path.dirname(path) + Path.sep, ...cloneDeep(transformOpts), filename: path }); if (compileOpts) { const {sourceMaps = 'both'} = <any>compileOpts; const transformed = babel.transform(content, {...compileOpts, sourceMaps, ast: false}); if (transformed) { if (transformed.map) { installSourceMaps(); maps[path] = transformed.map; } return transformed.code || content; } } return content; }; } return {transform, extensions: compilersByExtension(transform)}; } function compilersByExtension(transform: Transform) { return { ...(Module as any)._extensions, // compile `.js` files even if "type": "module" is set in the file's package.json ['.js']: transformAndCompile, ['.jsx']: transformAndCompile, ['.mjs']: transformAndCompile, ['.cjs']: transformAndCompile, }; function transformAndCompile(module: Module, filename: string) { return (<any>module)._compile(transform(filename, fs.readFileSync(filename, 'utf8')), filename); } } function normalizeOptions(options: Partial<babel.TransformOptions>) { const opts = {...options, caller: {name: '@rapidsai/jsdom', ...options.caller}}; // Ensure that the working directory is resolved up front so that // things don't break if it changes later. opts.cwd = Path.resolve(opts.cwd || '.'); if (opts.ignore === undefined && opts.only === undefined) { opts.only = [ // Only compile things inside the current working directory. // $FlowIgnore new RegExp('^' + escapeRegExp(opts.cwd), 'i'), ]; opts.ignore = [ // Ignore any node_modules inside the current working directory. new RegExp( '^' + // $FlowIgnore escapeRegExp(opts.cwd) + '(?:' + Path.sep + '.*)?' + // $FlowIgnore escapeRegExp(Path.sep + 'node_modules' + Path.sep), 'i', ), ]; } return opts; function escapeRegExp(string: string) { return string.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'); } } function supportSourceMaps(maps: any) { let sourceMapsSupportInstalled = false; return () => { if (!sourceMapsSupportInstalled) { sourceMapSupport.install({ handleUncaughtExceptions: false, environment: 'node', retrieveSourceMap(filename: string) { const map = maps && maps[filename]; if (map) { return { url: null, map: map, }; } else { return null; } }, }); sourceMapsSupportInstalled = true; } }; }
0
rapidsai_public_repos/node/modules/jsdom/src/polyfills
rapidsai_public_repos/node/modules/jsdom/src/polyfills/modules/import.ts
// Copyright (c) 2021-2023, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {readFile} from 'fs/promises'; import * as Path from 'path'; import * as vm from 'vm'; import {SourceTextModule, SyntheticModule} from 'vm'; import {createContextRequire as createRequire, ESMSyntheticModule, Require} from './require'; Object.entries({SyntheticModule, SourceTextModule}).forEach(([name, Class]) => { if (!Class) { console.error(`${name} not found. ` + `@rapidsai/jsdom requires node is with the --experimental-vm-modules flag.`); process.exit(1); } }); export function createDynamicImporter( require: Require, outerContext: vm.Context, transform: (path: string, code: string) => string) { const moduleLinker = createModuleLinker(require, outerContext, transform); return importModuleDynamically; function importModuleDynamically( specifier: string, _script?: vm.Script, assertions: {[key: string]: any} = {}) { return moduleLinker(specifier, {context: outerContext}, {assert: assertions}) as any; } } export function createModuleLinker( require: Require, outerContext: vm.Context, transform: (path: string, code: string) => string) { return linkModule; function linkModule(specifier: string, {context}: {context: vm.Context} = {context: outerContext}, {assert: assertions}: {assert: {[key: string]: any}} = {assert: {}}) { const opts = { context, identifier: require.resolve(specifier), importModuleDynamically: createDynamicImporter(require, context, transform), } as (vm.SyntheticModuleOptions | vm.SourceTextModuleOptions); try { // Try importing as CJS first return tryRequire(opts, assertions); } catch (e1: any) { try { // If CJS throws, try importing as ESM return tryImport(opts, assertions); } catch (e2: any) { // throw[e1, e2]; } } } function tryRequire(opts: vm.SyntheticModuleOptions, assertions: {[key: string]: any}) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const path = opts.identifier!; const exports = require(path); if (!exports[ESMSyntheticModule]) { const keys = Object.keys(exports); if (exports.__esModule && !('default' in exports)) { exports.default = exports; keys[keys.indexOf('__esModule')] = 'default'; } const mod = new SyntheticModule(keys, function() { // keys.forEach((name) => this.setExport(name, exports[name])); }, opts); return linkAndEvaluate(exports[ESMSyntheticModule] = mod, assertions); } return Promise.resolve(exports[ESMSyntheticModule]); } function tryImport(opts: vm.SourceTextModuleOptions, assertions: {[key: string]: any}) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const path = opts.identifier!; const dir = Path.dirname(path); const ext = Path.extname(path); return readFile(path, 'utf8') .then((code) => { code = `var __dirname='${dir}';\n${code}`; code = `var __filename='${path}';\n${code}`; if (ext in require.extensions) { // code = transform(path, code); } return new SourceTextModule(code, opts); }) .then((module) => linkAndEvaluate(module, assertions)); } // eslint-disable-next-line @typescript-eslint/no-unused-vars function linkAndEvaluate(module: vm.Module, _assertions: {[key: string]: any}) { let r = require; const dir = Path.dirname(module.identifier); if (dir !== require.main.path) { r = createRequire({ dir, transform, parent: require.main, extensions: require.extensions, resolve: require.main.__resolve, context: module.context || outerContext, }); r.main._moduleCache = require.cache; r.main._resolveCache = require.main._resolveCache; } return module.link(createModuleLinker(r, r.main._context, transform)) .then(() => module.evaluate()) .then(() => module); } }
0
rapidsai_public_repos/node/modules/jsdom/src/polyfills
rapidsai_public_repos/node/modules/jsdom/src/polyfills/modules/require.ts
// Copyright (c) 2021-2023, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as fs from 'fs'; import * as Module from 'module'; import * as Path from 'path'; import * as vm from 'vm'; import {createDynamicImporter} from './import'; import {Resolver} from './resolve'; import {Transform} from './transform'; export interface Require extends NodeJS.Require { main: ContextModule; } /** * Creates a custom Module object which runs all required scripts in a provided vm context. */ export function createContextRequire(options: CreateContextRequireOptions) { return new ContextModule(options)._require; } let moduleId = 0; /** * Patch nodejs module system to support context, * compilation and module resolution overrides. */ const Module_: any = getRealModule(); const module_static__load = Module_._load; const module_static__cache = Module_._cache; const module_static__extensions_js = Module_._extensions['.js']; const module_static__resolveFilename = Module_._resolveFilename; const module_prototype__compile = Module_.prototype._compile; const module_prototype_load = Module_.prototype.load; export interface CreateContextRequireOptions { /** The directory from which to resolve requires for this module. */ dir: string; /** A vm.Context to be used as the context for any required modules. */ context: any; parent?: Module; /** A function to override the native module resolution. */ resolve?: Resolver; /** A function to transform code during dynamic import. */ transform?: Transform; /** An object containing any context specific require hooks to be used in this module. */ extensions?: Partial<NodeJS.RequireExtensions>; } export class ContextModule extends Module { declare public _context: vm.Context; declare public _proxyExports: Record<string, boolean>; declare public _moduleCache: NodeJS.Dict<NodeModule>; declare public _resolveCache: NodeJS.Dict<string>; declare public _extensions?: Partial<NodeJS.RequireExtensions>; declare public _require: Require; declare public __resolve: Resolver; declare public _transform: Transform; // This should return Promise<vm.Module>, but the TS typings are incorrect. declare public _cachedDynamicImporter: (specifier: string, script?: vm.Script, assertions?: {[key: string]: any}) => any; /** * Custom nodejs Module implementation which uses a provided * resolver, require hooks, and context. */ constructor({ parent = require.main ?? module, dir = parent.path, context, resolve, extensions, transform = (_path: string, code: string) => code, }: CreateContextRequireOptions) { const filename = Path.join(dir, `index.${moduleId++}.ctx`); super(filename, parent); this.filename = filename; this.paths = Module_._nodeModulePaths(dir); this._proxyExports = {}; this._moduleCache = {}; this._resolveCache = {}; this._transform = transform; this._extensions = extensions; this._require = createRequire(this, this); this._context = isContext(context) ? context : vm.createContext(context); if (typeof resolve === 'function') { this.__resolve = resolve; } else { this._resolveFilename = module_static__resolveFilename; } this._cachedDynamicImporter = createDynamicImporter( this._require, this._context, (path: string, code: string) => this._transform(path, code)); this.loaded = true; } public static _load(request: string, parent: Module, isMain: boolean) { return patched_static__load.call(ContextModule, request, parent, isMain); } public static _resolveFilename(request: string, parent: Module, isMain?: boolean, options?: { paths?: string[] }) { return patched_static__resolveFilename.call(ContextModule, request, parent, isMain, options); } public _resolveFilename(request: string, parent: Module, isMain?: boolean, options?: { paths?: string[]|undefined; }) { const cache = this._resolveCache; const cacheKey = `${parent.path}\x00${request}`; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (cache[cacheKey]) { return cache[cacheKey]!; } const resolved = this.__resolve(request, parent, isMain, options); if (resolved) { cache[cacheKey] = resolved; } return resolved; } public _compile(content: string, filename: string) { return patched_prototype__compile.call(this, content, filename); } public load(filename: string) { return patched_prototype_load.call(this, filename); } public exec(require: Require, content: string, filename: string, inner = this._context) { const outer = this._context; const options: vm.ScriptOptions = { filename, importModuleDynamically: this.createDynamicImporter(require, inner), }; return tryAndReset( () => { this._context = inner; }, () => runScript(inner, new vm.Script(content, options)), () => { this._context = outer; }, ); } public createDynamicImporter(require: Require = this._require, context = this._context) { return context === this._context // ? this._cachedDynamicImporter : createDynamicImporter(require, context, this._transform); } } /** * Use custom require cache for context modules * * @param request The file to resolve. * @param parent The module requiring this file. * @param isMain */ function patched_static__load(request: string, parent: Module, isMain: boolean): any { if (Module_.builtinModules.indexOf(request) !== -1) { return module_static__load(request, parent, isMain); } const module = findNearestContextModule(parent); if (module) { const filename = patched_static__resolveFilename(request, parent, isMain); // ensure native addons are added to the global static Module_._cache const cache = Path.extname(filename) === '.node' ? module_static__cache : module._moduleCache; const child = cache[filename]; if (child) { if (parent.children.indexOf(child) === -1) { // parent.children.push(child); } return child.exports; } Module_._cache = cache; } return tryAndReset( () => {}, () => module_static__load(request, parent, isMain), () => { Module_._cache = module_static__cache; }, ); } // compile `.js` files even if "type": "module" is set in the file's package.json function patched_static__extensions_js(module: any, filename: string) { module._compile(fs.readFileSync(filename, 'utf8'), filename); } /** * Hijack native file resolution using closest custom resolver. * * @param request The file to resolve. * @param parent The module requiring this file. */ function patched_static__resolveFilename( request: string, parent: Module, isMain?: boolean, options?: {paths?: string[]|undefined;}) { if (Module_.builtinModules.indexOf(request) === -1) { const module = findNearestContextModule(parent); if (module) { return tryAndReset( () => { Module_._resolveFilename = module_static__resolveFilename; }, () => module._resolveFilename(request, parent, isMain, options), () => { Module_._resolveFilename = patched_static__resolveFilename; }, ); } } return module_static__resolveFilename(request, parent, isMain, options) as string; } /** * Patch module.load to use the context's custom extensions if provided. * * @param filename */ function patched_prototype_load(this: Module, filename: string) { const module = findNearestContextModule(this) as ContextModule; if (module?._extensions) { const extension = Path.extname(filename); const compiler = module._extensions[extension]; if (compiler) { const original = Module_._extensions[extension]; return tryAndReset( () => { Module_._extensions[extension] = compiler; }, () => module_prototype_load.call(this, filename), () => { Module_._extensions[extension] = original; }, ); } } return module_prototype_load.call(this, filename); } /** * This overrides script compilation to ensure the nearest context module is used. * * @param content The file contents of the script. * @param filename The filename for the script. */ function patched_prototype__compile(this: Module, content: string, filename: string) { const module = findNearestContextModule(this); if (module) { const require = createRequire(this, module); const dirname = Path.dirname(filename); const exports = makeESMExportsProxy(this, this.exports); return module.exec(require, Module_.wrap(content), filename) .call(exports, exports, require, this, filename, dirname); } return module_prototype__compile.call(this, content, filename); } /** * Walks up a module tree to find the nearest context module. * * @param cur The starting module. */ function findNearestContextModule(mod: Module) { let cur: Module|null|undefined = mod; do { if (cur instanceof ContextModule) { return cur; } // eslint-disable-next-line no-cond-assign } while (cur = cur && cur.parent); return undefined; } /** * Helper which will run a vm script in a context. * Special case for JSDOM where `runVMScript` is used. * * @param context The vm context to run the script in (or a jsdom instance). * @param script The vm script to run. */ function runScript(context: vm.Context, script: vm.Script) { return context.runVMScript ? context.runVMScript(script) : script.runInContext(context.getInternalVMContext ? context.getInternalVMContext() : context); } function isContext(context: any) { return vm.isContext(context) || (typeof context.runVMScript === 'function' && typeof context.getInternalVMContext === 'function'); } function tryAndReset<Work extends() => any>(setup: () => any, work: Work, reset: () => any) { setup(); let result: ReturnType<Work>; try { result = work(); } catch (e) { reset(); throw e; } reset(); return result; } /** * Creates a require function bound to a module * and adds a `resolve` function the same as nodejs. * * @param mod The module to create a require function for. */ function createRequire(mod: Module, main = findNearestContextModule(mod)) { function require(id: string) { return tryAndReset( installModuleHooks, () => mod.require(id), uninstallModuleHooks, ); } function resolve(id: string, options?: {paths?: string[]|undefined;}) { return patched_static__resolveFilename(id, mod, false, options); } require.main = main; require.cache = main && main._moduleCache; require.resolve = resolve as NodeJS.RequireResolve; require.extensions = main && main._extensions || Module_._extensions; return require as Require; } let installedCount = 0; // Jest hijacks the Module builtin, this gets the real one. function getRealModule(): typeof Module { const M = Module as any; return M.__proto__ && M.__proto__.prototype ? M.__proto__ : M; } function installModuleHooks() { if (++installedCount === 1) { Module_._load = patched_static__load; Module_._extensions['.js'] = patched_static__extensions_js; Module_._resolveFilename = patched_static__resolveFilename; Module_.prototype._compile = patched_prototype__compile; Module_.prototype.load = patched_prototype_load; } } function uninstallModuleHooks() { if (--installedCount === 0) { Module_._load = module_static__load; Module_._extensions['.js'] = module_static__extensions_js; Module_._resolveFilename = module_static__resolveFilename; Module_.prototype._compile = module_prototype__compile; Module_.prototype.load = module_prototype_load; } } export const ESMSyntheticModule = Symbol('ESMSyntheticModule'); const ES6ExportsProxyHandler: ProxyHandler<any> = { set(target: any, p: string|symbol, v: any, receiver: any) { // const success = Reflect.set(target, p, v, receiver); if (success && p !== ESMSyntheticModule) { const mod = Reflect.get(target, ESMSyntheticModule, receiver); if (mod) { mod.setExport(p, v); } } return success; } }; const BuiltInES6ExportsProxyHandler = { ...ES6ExportsProxyHandler, get(target: any, p: string|symbol, receiver: any) { const value = Reflect.get(target, p, receiver); if (typeof value === 'function' && (p in target.constructor.prototype)) { return function(this: any) { // eslint-disable-next-line prefer-rest-params return value.apply(this === receiver ? target : this, arguments); }; } return value; } }; function makeESMExportsProxy(module: Module, exports: any) { let proxiedExports: any; if ((exports?.constructor?.name === 'Map') || // (exports?.constructor?.name === 'Set') || // (exports?.constructor?.name === 'WeakMap') || // (exports?.constructor?.name === 'WeakSet')) { proxiedExports = new Proxy(exports, BuiltInES6ExportsProxyHandler); } else { proxiedExports = new Proxy(exports, ES6ExportsProxyHandler); } Object.defineProperty(module, 'exports', { get() { return proxiedExports; }, set(value: any) { if (value !== proxiedExports) { if ((typeof value === 'function') || // (value && typeof value === 'object')) { proxiedExports = makeESMExportsProxy(module, value); } else { proxiedExports = value; } } }, }); return proxiedExports; }
0
rapidsai_public_repos/node/modules/jsdom/src/polyfills
rapidsai_public_repos/node/modules/jsdom/src/polyfills/modules/resolve.ts
// Copyright (c) 2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as Module from 'module'; import * as Path from 'path'; export type Resolver = (request: string, parent: Module, isMain?: boolean, options?: {paths?: string[]|undefined;}) => string; export type ResolversMap = { [path: string]: Resolver }; const nodeModulesWithSeparator = `node_modules${Path.sep}`; const nodeModulesWithSeparatorLength = nodeModulesWithSeparator.length; export function createResolve(resolvers?: ResolversMap): Resolver { resolvers = resolvers || {}; return resolve; function resolve(request: string, parent: Module, isMain?: boolean, options?: any) { // Normalize request path so custom resolvers can have a stable key // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const resolveFilename = resolvers![resolverKey(request, parent)]; return resolveFilename // ? resolveFilename(request, parent, isMain, options) : (<any>Module)._resolveFilename(request, parent, isMain, options); } function resolverKey(request: string, parent: Module) { const dir = '' + parent.path; const idx = dir.lastIndexOf(nodeModulesWithSeparator) ?? -1; const pre = dir.slice(~idx && idx + nodeModulesWithSeparatorLength || 0); return Path.join(pre, normalizeReq(request, parent)); } function normalizeReq(request: string, parent: Module) { if (Path.isAbsolute(request)) { const relative = Path.relative(parent.path, request); if (!relative.startsWith(`.${Path.sep}`)) { // return `.${Path.sep}${relative}`; } return relative; } return request; } }
0
rapidsai_public_repos/node/modules/jsdom/src/polyfills
rapidsai_public_repos/node/modules/jsdom/src/polyfills/modules/reactmapgl.ts
// Copyright (c) 2022, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as Module from 'module'; export function reactMapGLMapboxResolvers() { return { 'react-map-gl/src/utils/mapboxgl': reactMapGLMapboxResolver, 'react-map-gl/dist/es5/utils/mapboxgl': reactMapGLMapboxResolver, 'react-map-gl/dist/esm/utils/mapboxgl': reactMapGLMapboxResolver, 'react-map-gl/dist/es6/utils/mapboxgl': reactMapGLMapboxResolver, }; } function reactMapGLMapboxResolver(request: string, ...args: any[]) { request = request.replace('mapboxgl', 'mapboxgl.browser'); return (Module as any)._resolveFilename(request, ...args); }
0
rapidsai_public_repos/node/modules/jsdom/src/polyfills
rapidsai_public_repos/node/modules/jsdom/src/polyfills/modules/vm.ts
// Copyright (c) 2021-2022, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as jsdom from 'jsdom'; import * as vm from 'vm'; const { implSymbol, implForWrapper, wrapperForImpl, } = require('jsdom/lib/jsdom/living/generated/utils'); export function createContextFactory(window: jsdom.DOMWindow, cwd: string) { window.jsdom || (window.jsdom = {}); window.jsdom.utils || (window.jsdom.utils = {}); window.jsdom.utils.implSymbol = implSymbol; window.jsdom.utils.implForWrapper = implForWrapper; window.jsdom.utils.wrapperForImpl = wrapperForImpl; window.jsdom.global = implForWrapper(window)._globalObject; window.jsdom.global.__cwd = cwd; window.jsdom.global.URL = window.URL; window.jsdom.global.Blob = window.Blob; window.jsdom.global.Worker = window.Worker; return createContext; function createContext(globals: Record<string, any> = {}) { const outerGlobal = window.jsdom.global; const innerGlobal = Object.create(outerGlobal, { ...Object.getOwnPropertyDescriptors(global), ...Object.getOwnPropertyDescriptors(outerGlobal), global: {get: () => innerContext, configurable: true, enumerable: true}, globalThis: {get: () => innerContext, configurable: true, enumerable: true}, window: {value: window, configurable: true, enumerable: true, writable: false}, }); const innerProcess = Object.assign(clone(process), { __cwd: cwd, browser: true, cwd() { return this.__cwd; }, chdir(dir: string) { this.__cwd = dir; }, }); const innerContext = vm.createContext(Object.assign(innerGlobal, {process: innerProcess}, globals)); return installSymbolHasInstanceImpls(innerContext); } } const { getPrototypeOf, getOwnPropertyDescriptors, } = Object; const nodeGlobals = Object.keys(getOwnPropertyDescriptors(vm.runInNewContext('this'))); const clone = (obj: any) => Object.create(getPrototypeOf(obj), getOwnPropertyDescriptors(obj)); function installSymbolHasInstanceImpls(context: vm.Context) { nodeGlobals.forEach((name) => { const Constructor = context[name]; if (typeof Constructor === 'function') { const Prototype = Constructor.prototype; Object.defineProperty(Constructor, Symbol.hasInstance, { configurable: true, value: (x: any) => { if (x?.constructor?.name === name) { return true; } for (let p = x; p && (p = getPrototypeOf(p));) { if (p === Prototype) { return true; } } return false; }, }); } }); return context; }
0
rapidsai_public_repos/node/modules/jsdom/src/polyfills
rapidsai_public_repos/node/modules/jsdom/src/polyfills/events/monitor.ts
// Copyright (c) 2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {glfw, GLFW, GLFWmonitor, Monitor} from '@rapidsai/glfw'; import {map, publish, refCount} from 'rxjs/operators'; import {glfwCallbackAsObservable, GLFWEvent} from './event'; export function monitorEvents() { return glfwCallbackAsObservable(glfw.setMonitorCallback) .pipe(map(([_, ...rest]) => GLFWMonitorEvent.create(_, ...rest))) .pipe(publish(), refCount()); } class GLFWMonitorEvent extends GLFWEvent { public static create(monitor: GLFWmonitor, event: number) { const evt = new GLFWMonitorEvent(event === GLFW.CONNECTED ? 'monitorconnected' : 'monitordisconnected'); evt.target = new Monitor(monitor, event === GLFW.CONNECTED); return evt; } }
0
rapidsai_public_repos/node/modules/jsdom/src/polyfills
rapidsai_public_repos/node/modules/jsdom/src/polyfills/events/wheel.ts
// Copyright (c) 2021-2023, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {glfw} from '@rapidsai/glfw'; import {DOMWindow} from 'jsdom'; import {map, publish, refCount} from 'rxjs/operators'; import {GLFWEvent, windowCallbackAsObservable} from './event'; export function wheelEvents(window: DOMWindow) { return windowCallbackAsObservable(glfw.setScrollCallback, window.id) .pipe(map(([, ...rest]) => GLFWWheelEvent.create(window, ...rest))) .pipe(publish(), refCount()); } export class GLFWWheelEvent extends GLFWEvent { public static create(window: DOMWindow, xoffset: number, yoffset: number) { const evt = new GLFWWheelEvent('wheel'); evt.target = window; evt._x = window.mouseX; evt._y = window.mouseY; evt._deltaX = xoffset * -20; evt._deltaY = yoffset * -20; evt._deltaZ = 0; evt._buttons = window.buttons; evt._altKey = window.altKey; evt._ctrlKey = window.ctrlKey; evt._metaKey = window.metaKey; evt._shiftKey = window.shiftKey; evt._capsLock = window.capsLock; return evt; } private _x = 0; private _y = 0; private _deltaX = 0; private _deltaY = 0; private _deltaZ = 0; private _buttons = 0; private _altKey = false; private _ctrlKey = false; private _metaKey = false; private _shiftKey = false; private _capsLock = false; public get deltaMode() { return 0x00; } public get deltaX() { return this._deltaX; } public get deltaY() { return this._deltaY; } public get deltaZ() { return this._deltaZ; } public get x() { return this._x; } public get y() { return this._y; } public get pageX() { return this._x; } public get pageY() { return this._y; } public get clientX() { return this._x; } public get clientY() { return this._y; } public get offsetX() { return this._x; } public get offsetY() { return this._y; } public get screenX() { return this._x; } public get screenY() { return this._y; } public get which() { return this._buttons; } public get altKey() { return this._altKey; } public get buttons() { return this._buttons; } public get ctrlKey() { return this._ctrlKey; } public get metaKey() { return this._metaKey; } public get shiftKey() { return this._shiftKey; } public get capsLock() { return this._capsLock; } }
0
rapidsai_public_repos/node/modules/jsdom/src/polyfills
rapidsai_public_repos/node/modules/jsdom/src/polyfills/events/mouse.ts
// Copyright (c) 2021-2023, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {glfw, GLFWMouseButton} from '@rapidsai/glfw'; import {DOMWindow} from 'jsdom'; import {merge as mergeObservables} from 'rxjs'; import {flatMap, publish, refCount} from 'rxjs/operators'; import { GLFWEvent, isAltKey, isCapsLock, isCtrlKey, isMetaKey, isShiftKey, windowCallbackAsObservable } from './event'; export function mouseEvents(window: DOMWindow) { return mergeObservables( buttonUpdates(window), positionUpdates(window), boundaryUpdates(window), ); } function buttonUpdates(window: DOMWindow) { return windowCallbackAsObservable(glfw.setMouseButtonCallback, window.id) .pipe(flatMap(function*([, ...rest]) { const mouseEvt = GLFWMouseEvent.fromMouseButton(window, ...rest); yield mouseEvt; yield Object.assign(GLFWMouseEvent.fromMouseButton(window, ...rest), {type: `pointer${mouseEvt.type.slice(5)}`}); })) .pipe(publish(), refCount()); } function positionUpdates(window: DOMWindow) { return windowCallbackAsObservable(glfw.setCursorPosCallback, window.id) .pipe(flatMap(function*([, ...rest]) { const mouseEvt = GLFWMouseEvent.fromMouseMove(window, ...rest); yield mouseEvt; yield Object.assign(GLFWMouseEvent.fromMouseMove(window, ...rest), {type: `pointer${mouseEvt.type.slice(5)}`}); })) .pipe(publish(), refCount()); } function boundaryUpdates(window: DOMWindow) { return windowCallbackAsObservable(glfw.setCursorEnterCallback, window.id) .pipe(flatMap(function*([, ...rest]) { const mouseEvt = GLFWMouseEvent.fromMouseEnter(window, ...rest); yield mouseEvt; yield Object.assign(GLFWMouseEvent.fromMouseEnter(window, ...rest), {type: `pointer${mouseEvt.type.slice(5)}`}); })) .pipe(publish(), refCount()); } export class GLFWMouseEvent extends GLFWEvent { public static create(window: DOMWindow, type: string) { const evt = new GLFWMouseEvent(type); evt.target = window; evt._movementX = 0; evt._movementY = 0; evt._x = window.mouseX; evt._y = window.mouseY; evt._altKey = window.altKey; evt._buttons = window.buttons; evt._ctrlKey = window.ctrlKey; evt._metaKey = window.metaKey; evt._shiftKey = window.shiftKey; evt._capsLock = window.capsLock; return evt; } public static fromMouseMove(window: DOMWindow, x: number, y: number) { const evt = GLFWMouseEvent.create(window, 'mousemove'); evt._x = x; evt._y = y; evt._movementX = x - window.mouseX; evt._movementY = y - window.mouseY; return evt; } public static fromMouseEnter(window: DOMWindow, entered: number) { const evt = GLFWMouseEvent.create(window, entered ? 'mouseenter' : 'mouseleave'); ({x: evt._x, y: evt._y} = glfw.getCursorPos(window.id)); return evt; } public static fromMouseButton(window: DOMWindow, button: number, action: number, modifiers: number) { const down = action === glfw.PRESS; const evt = GLFWMouseEvent.create(window, down ? 'mousedown' : 'mouseup'); evt._altKey || (evt._altKey = isAltKey(modifiers)); evt._ctrlKey || (evt._ctrlKey = isCtrlKey(modifiers)); evt._metaKey || (evt._metaKey = isMetaKey(modifiers)); evt._shiftKey || (evt._shiftKey = isShiftKey(modifiers)); evt._capsLock || (evt._capsLock = isCapsLock(modifiers)); evt._button = button + (button == GLFWMouseButton.MOUSE_BUTTON_3 ? -1 : button == GLFWMouseButton.MOUSE_BUTTON_2 ? 1 : 0); evt._buttons = down ? window.buttons | (1 << button) : window.buttons & ~(1 << button); ({x: evt._x, y: evt._y} = glfw.getCursorPos(window.id)); return evt; } private _x = 0; private _y = 0; private _button = 0; private _buttons = 0; private _movementX = 0; private _movementY = 0; private _altKey = false; private _ctrlKey = false; private _metaKey = false; private _shiftKey = false; private _capsLock = false; public get x() { return this._x; } public get y() { return this._y; } public get pageX() { return this._x; } public get pageY() { return this._y; } public get clientX() { return this._x; } public get clientY() { return this._y; } public get offsetX() { return this._x; } public get offsetY() { return this._y; } public get screenX() { return this._x; } public get screenY() { return this._y; } public get which() { return this._buttons; } public get altKey() { return this._altKey; } public get button() { return this._button; } public get buttons() { return this._buttons; } public get ctrlKey() { return this._ctrlKey; } public get metaKey() { return this._metaKey; } public get shiftKey() { return this._shiftKey; } public get capsLock() { return this._capsLock; } public get movementX() { return this._movementX; } public get movementY() { return this._movementY; } }
0
rapidsai_public_repos/node/modules/jsdom/src/polyfills
rapidsai_public_repos/node/modules/jsdom/src/polyfills/events/event.ts
// Copyright (c) 2021-2023, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {GLFWModifierKey} from '@rapidsai/glfw'; import {Observable, Observer} from 'rxjs'; export const isAltKey = (modifiers: number) => (modifiers & GLFWModifierKey.MOD_ALT) !== 0; export const isCtrlKey = (modifiers: number) => (modifiers & GLFWModifierKey.MOD_CONTROL) !== 0; export const isMetaKey = (modifiers: number) => (modifiers & GLFWModifierKey.MOD_SUPER) !== 0; export const isShiftKey = (modifiers: number) => (modifiers & GLFWModifierKey.MOD_SHIFT) !== 0; export const isCapsLock = (modifiers: number) => (modifiers & GLFWModifierKey.MOD_CAPS_LOCK) !== 0; export class GLFWEvent { public target: any; public bubbles = true; public composed = false; public cancelable = true; public readonly type: string; constructor(type: string) { this.type = type; } public preventDefault() {} public stopPropagation() {} public stopImmediatePropagation() {} public get defaultPrevented() { return false; } public get srcElement() { return this.target; } public get relatedTarget() { return null; } public get currentTarget() { return this.target; } } type SetGLFWCallback = (cb: null|((...args: any) => void)) => void; type GLFWCallbackArgs<T extends SetGLFWCallback> = T extends(cb: (...args: infer P) => void) => any ? P : never; type SetWindowCallback = (ptr: number, cb: null|((...args: any) => void)) => void; type WindowCallbackArgs<T extends SetWindowCallback> = T extends(ptr: number, cb: (...args: infer P) => void) => any ? P : never; export function glfwCallbackAsObservable<C extends SetGLFWCallback>(setCallback: C) { type Args = GLFWCallbackArgs<C>; return new Observable<Args>((observer: Observer<Args>) => { const next = (..._: Args) => observer.next(_); const dispose = () => trySetCallback(setCallback.name, () => setCallback(null)); return trySetCallback(setCallback.name, () => setCallback(next)) ? dispose : () => {}; }); } export function windowCallbackAsObservable<C extends SetWindowCallback>(setCallback: C, windowId: number) { type Args = WindowCallbackArgs<C>; return new Observable<Args>((observer: Observer<Args>) => { const next = (..._: Args) => observer.next(_); const dispose = () => trySetCallback(setCallback.name, () => setCallback(windowId, null)); return trySetCallback(setCallback.name, () => setCallback(windowId, next)) ? dispose : () => {}; }); } function trySetCallback(name: string, work: () => void) { try { work(); } catch (e) { console.error(`glfw.${name} error:`, e); return false; } return true; }
0
rapidsai_public_repos/node/modules/jsdom/src/polyfills
rapidsai_public_repos/node/modules/jsdom/src/polyfills/events/window.ts
// Copyright (c) 2021-2023, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {glfw} from '@rapidsai/glfw'; import {DOMWindow} from 'jsdom'; import {merge as mergeObservables} from 'rxjs'; import {map, publish, refCount} from 'rxjs/operators'; import {GLFWEvent, windowCallbackAsObservable} from './event'; export function windowEvents(window: DOMWindow) { return mergeObservables( moveUpdates(window), sizeUpdates(window), scaleUpdates(window), framebufferSizeUpdates(window), closeUpdates(window), // refreshUpdates(window), focusUpdates(window), iconifyUpdates(window), maximizeUpdates(window), ); } function moveUpdates(window: DOMWindow) { return windowCallbackAsObservable(glfw.setWindowPosCallback, window.id) .pipe(map(([, ...rest]) => GLFWWindowEvent.fromMove(window, ...rest))) .pipe(publish(), refCount()); } function sizeUpdates(window: DOMWindow) { return windowCallbackAsObservable(glfw.setWindowSizeCallback, window.id) .pipe(map(([, ...rest]) => GLFWWindowEvent.fromResize(window, ...rest))) .pipe(publish(), refCount()); } function scaleUpdates(window: DOMWindow) { return windowCallbackAsObservable(glfw.setWindowContentScaleCallback, window.id) .pipe(map(([, ...rest]) => GLFWWindowEvent.fromScale(window, ...rest))) .pipe(publish(), refCount()); } function framebufferSizeUpdates(window: DOMWindow) { return windowCallbackAsObservable(glfw.setFramebufferSizeCallback, window.id) .pipe(map(([, ...rest]) => GLFWWindowEvent.fromFramebufferResize(window, ...rest))) .pipe(publish(), refCount()); } function closeUpdates(window: DOMWindow) { return windowCallbackAsObservable(glfw.setWindowCloseCallback, window.id) .pipe(map(([, ...rest]) => GLFWWindowEvent.fromClose(window, ...rest))) .pipe(publish(), refCount()); } // function refreshUpdates(window: DOMWindow) { // return windowCallbackAsObservable(glfw.setWindowRefreshCallback, window.id) // .pipe(map(([_, ...rest]) => GLFWWindowEvent.fromRefresh(window, ...rest))) // .pipe(publish(), refCount()); // } function focusUpdates(window: DOMWindow) { return windowCallbackAsObservable(glfw.setWindowFocusCallback, window.id) .pipe(map(([, ...rest]) => GLFWWindowEvent.fromFocus(window, ...rest))) .pipe(publish(), refCount()); } function iconifyUpdates(window: DOMWindow) { return windowCallbackAsObservable(glfw.setWindowIconifyCallback, window.id) .pipe(map(([, ...rest]) => GLFWWindowEvent.fromIconify(window, ...rest))) .pipe(publish(), refCount()); } function maximizeUpdates(window: DOMWindow) { return windowCallbackAsObservable(glfw.setWindowMaximizeCallback, window.id) .pipe(map(([, ...rest]) => GLFWWindowEvent.fromMaximize(window, ...rest))) .pipe(publish(), refCount()); } export class GLFWWindowEvent extends GLFWEvent { private static create(window: DOMWindow, type: string) { const evt = new GLFWWindowEvent(type); evt.target = window; evt._x = window.x; evt._y = window.y; evt._width = window.width; evt._height = window.height; evt._xscale = window.xscale; evt._yscale = window.yscale; evt._focused = window.focused; evt._minimized = window.minimized; evt._maximized = window.maximized; evt._frameBufferWidth = window.frameBufferWidth; evt._frameBufferHeight = window.frameBufferHeight; return evt; } public static fromMove(window: DOMWindow, x: number, y: number) { return Object.assign(GLFWWindowEvent.create(window, 'move'), {_x: x, _y: y}); } public static fromResize(window: DOMWindow, width: number, height: number) { return Object.assign(GLFWWindowEvent.create(window, 'resize'), { _width: width, _height: height, _frameBufferWidth: window.xscale * width, _frameBufferHeight: window.yscale * height }); } public static fromScale(window: DOMWindow, xscale: number, yscale: number) { return Object.assign(GLFWWindowEvent.create(window, 'contentscale'), { _xscale: xscale, _yscale: yscale, _width: window.frameBufferWidth / xscale, _height: window.frameBufferHeight / yscale, _frameBufferWidth: xscale * window.width, _frameBufferHeight: yscale * window.height, }); } public static fromFramebufferResize(window: DOMWindow, frameBufferWidth: number, frameBufferHeight: number) { return Object.assign(GLFWWindowEvent.create(window, 'framebufferresize'), { _frameBufferWidth: frameBufferWidth, _frameBufferHeight: frameBufferHeight, _width: frameBufferWidth / window.xscale, _height: frameBufferHeight / window.yscale, }); } public static fromClose(window: DOMWindow) { return GLFWWindowEvent.create(window, 'close'); } public static fromRefresh(window: DOMWindow) { return GLFWWindowEvent.create(window, 'refresh'); } public static fromFocus(window: DOMWindow, focused: boolean) { return Object.assign(GLFWWindowEvent.create(window, focused ? 'focus' : 'blur'), {_focused: !!focused}); } public static fromIconify(window: DOMWindow, minimized: boolean) { return Object.assign(GLFWWindowEvent.create(window, minimized ? 'minimized' : 'restored'), {_minimized: !!minimized}); } public static fromMaximize(window: DOMWindow, maximized: boolean) { return Object.assign(GLFWWindowEvent.create(window, maximized ? 'maximized' : 'restored'), {_maximized: !!maximized}); } private _x = 0; private _y = 0; private _width = 0; private _height = 0; private _xscale = 0; private _yscale = 0; private _focused = false; private _minimized = false; private _maximized = false; private _frameBufferWidth = 0; private _frameBufferHeight = 0; public get x() { return this._x; } public get y() { return this._y; } public get width() { return this._width; } public get height() { return this._height; } public get xscale() { return this._xscale; } public get yscale() { return this._yscale; } public get focused() { return this._focused; } public get minimized() { return this._minimized; } public get maximized() { return this._maximized; } public get frameBufferWidth() { return this._frameBufferWidth; } public get frameBufferHeight() { return this._frameBufferHeight; } }
0
rapidsai_public_repos/node/modules/jsdom/src/polyfills
rapidsai_public_repos/node/modules/jsdom/src/polyfills/events/dnd.ts
// Copyright (c) 2021-2023, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {glfw} from '@rapidsai/glfw'; import {DOMWindow} from 'jsdom'; import {map, publish, refCount} from 'rxjs/operators'; import {GLFWEvent, windowCallbackAsObservable} from './event'; export function dndEvents(window: DOMWindow) { return windowCallbackAsObservable(glfw.setDropCallback, window.id) .pipe(map(([, ...rest]) => GLFWDndEvent.create(window, ...rest))) .pipe(publish(), refCount()); } export class GLFWDndEvent extends GLFWEvent { public static create(window: DOMWindow, files: string[]) { const evt = new GLFWDndEvent('drop'); evt.target = window; evt._files = files; return evt; } private _files: string[] = []; public readonly types = []; public readonly dropEffect = 'none'; public readonly effectAllowed = 'all'; public get items() { return this._files; } public get files() { return this._files; } }
0
rapidsai_public_repos/node/modules/jsdom/src/polyfills
rapidsai_public_repos/node/modules/jsdom/src/polyfills/events/keyboard.ts
// Copyright (c) 2021-2023, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {glfw, GLFWInputMode, GLFWKey} from '@rapidsai/glfw'; import {DOMWindow} from 'jsdom'; import {merge as mergeObservables, Observable} from 'rxjs'; import {filter, flatMap, map, mergeAll, publish, refCount, withLatestFrom} from 'rxjs/operators'; import { GLFWEvent, isAltKey, isCapsLock, isCtrlKey, isMetaKey, isShiftKey, windowCallbackAsObservable } from './event'; export function keyboardEvents(window: DOMWindow) { const keys = keyUpdates(window); const specialKeys = keys.pipe(filter(isSpecialKey)).pipe(flatMap(function*(keyEvt) { yield keyEvt; // Also yield Delete 'keydown' events as 'keypress' if (keyEvt.key === 'Delete' && keyEvt.type === 'keydown') { yield keyEvt.asCharacter(127, 'keypress'); } })); const characterKeys = keys.pipe(filter(isCharacterKey), (charKeys) => characterUpdates(window, charKeys)); return mergeObservables(specialKeys, characterKeys); } function keyUpdates(window: DOMWindow) { return windowCallbackAsObservable(glfw.setKeyCallback, window.id) .pipe(map(([, ...rest]) => GLFWKeyboardEvent.fromKeyEvent(window, ...rest))) .pipe(publish(), refCount()); } function characterUpdates(window: DOMWindow, charKeys: Observable<GLFWKeyboardEvent>) { const charCodes = windowCallbackAsObservable(glfw.setCharCallback, window.id) .pipe(map(([, charCode]) => charCode), publish(), refCount()); return charCodes .pipe(withLatestFrom(charKeys, function*(charCode, keyEvt) { yield keyEvt; // Also yield 'keydown' events as 'keypress' yield keyEvt.asCharacter(charCode, 'keypress'); // GLFW doesn't dispatch keyup for character keys, so dispatch our own yield keyEvt.asCharacter(0, 'keyup'); })) .pipe(mergeAll()); } function isCharacterKey(evt: GLFWKeyboardEvent) { return !isSpecialKey(evt); } function isSpecialKey(evt: GLFWKeyboardEvent) { switch (evt._rawKey) { // GLFW dispatches spacebar as both a keyboard and character input event, // but glfw.getKeyName() doesn't return a name for it. case GLFWKey.KEY_SPACE: return false; // Arrow keys are special keys // Modifier keys are special keys case GLFWKey.KEY_UP: case GLFWKey.KEY_DOWN: case GLFWKey.KEY_LEFT: case GLFWKey.KEY_RIGHT: case GLFWKey.KEY_END: case GLFWKey.KEY_HOME: case GLFWKey.KEY_PAGE_UP: case GLFWKey.KEY_PAGE_DOWN: case GLFWKey.KEY_DELETE: case GLFWKey.KEY_BACKSPACE: case GLFWKey.KEY_CAPS_LOCK: case GLFWKey.KEY_LEFT_ALT: case GLFWKey.KEY_RIGHT_ALT: case GLFWKey.KEY_LEFT_CONTROL: case GLFWKey.KEY_RIGHT_CONTROL: case GLFWKey.KEY_LEFT_SUPER: case GLFWKey.KEY_RIGHT_SUPER: case GLFWKey.KEY_LEFT_SHIFT: case GLFWKey.KEY_RIGHT_SHIFT: return true; default: // If GLFW didn't return a key name, it's a special key return !evt._rawName || evt.key === 'Unidentified'; } } export class GLFWKeyboardEvent extends GLFWEvent { public static fromDOMEvent(window: DOMWindow, event: KeyboardEvent) { const evt = new GLFWKeyboardEvent(event.type); evt.target = window; evt._key = event.key; evt._code = event.code; evt._which = event.keyCode; evt._charCode = event.charCode; evt._repeat = event.repeat; evt._altKey = event.altKey; evt._ctrlKey = event.ctrlKey; evt._metaKey = event.metaKey; evt._shiftKey = event.shiftKey; evt._capsLock = false; if (event.getModifierState) { evt._capsLock = event.getModifierState('CapsLock'); } return evt; } public static fromKeyEvent( window: DOMWindow, key: number, scancode: number, action: number, modifiers: number) { const down = action !== glfw.RELEASE; const name = glfw.getKeyName(key, scancode); const evt = new GLFWKeyboardEvent(action === glfw.RELEASE ? 'keyup' : 'keydown'); evt._rawKey = key; evt._rawName = name; evt._rawScanCode = scancode; evt.target = window; evt._repeat = action === glfw.REPEAT; evt._key = glfwKeyToKey[key] || name || 'Unidentified'; evt._code = glfwKeyToCode[key] || (name && `Key${name.toUpperCase()}`) || 'Unidentified'; evt._which = glfwKeyToKeyCode[key] || key; evt._charCode = 0; const isCaps = key === GLFWKey.KEY_CAPS_LOCK; const isAlt = !isCaps && (key === GLFWKey.KEY_LEFT_ALT || key === GLFWKey.KEY_RIGHT_ALT); const isShift = !isAlt && (key === GLFWKey.KEY_LEFT_SHIFT || key === GLFWKey.KEY_RIGHT_SHIFT); const isSuper = !isShift && (key === GLFWKey.KEY_LEFT_SUPER || key === GLFWKey.KEY_RIGHT_SUPER); const isControl = !isSuper && (key === GLFWKey.KEY_LEFT_CONTROL || key === GLFWKey.KEY_RIGHT_CONTROL); if (!glfw.getInputMode(window.id, GLFWInputMode.LOCK_KEY_MODS)) { evt._capsLock = down ? isCaps || window.capsLock : !isCaps && window.capsLock; } else { evt._capsLock = isCaps ? window.capsLock ? !down : down : isCapsLock(modifiers); } if (down) { evt._altKey = isAlt || isAltKey(modifiers); evt._ctrlKey = isControl || isCtrlKey(modifiers); evt._metaKey = isSuper || isMetaKey(modifiers); evt._shiftKey = isShift || isShiftKey(modifiers); } else { evt._altKey = !isAlt && isAltKey(modifiers); evt._ctrlKey = !isControl && isCtrlKey(modifiers); evt._metaKey = !isSuper && isMetaKey(modifiers); evt._shiftKey = !isShift && isShiftKey(modifiers); } return evt; } public asCharacter(charCode: number, type = this.type, modifiers: number = this.target.modifiers) { if (this._rawKey === GLFWKey.KEY_DELETE) { charCode = 127; } const evt = new GLFWKeyboardEvent(type); evt.target = this.target; evt._charCode = charCode; evt._which = charCode || this._which; evt._rawKey = this._rawKey; evt._rawName = this._rawName; evt._rawScanCode = this._rawScanCode; evt._key = (charCode && String.fromCharCode(charCode)) || this._key; evt._repeat = this._repeat || this.type === 'keypress'; evt._code = glfwKeyToCode[this._rawKey] || `Key${this._rawName.toUpperCase()}`; evt._altKey = isAltKey(modifiers) || this._altKey; evt._ctrlKey = isCtrlKey(modifiers) || this._ctrlKey; evt._metaKey = isMetaKey(modifiers) || this._metaKey; evt._shiftKey = isShiftKey(modifiers) || this._shiftKey; evt._capsLock = isCapsLock(modifiers) || this._capsLock; return evt; } public isComposing = false; private _key = ''; private _code = ''; private _which = 0; private _repeat = false; private _altKey = false; private _ctrlKey = false; private _metaKey = false; private _shiftKey = false; private _capsLock = false; private _charCode: number|null = null; public _rawKey = 0; public _rawName = ''; public _rawScanCode = 0; public get key() { return this._key; } public get code() { return this._code; } public get which() { return this._which; } public get repeat() { return this._repeat; } public get keyCode() { return this._which; } public get charCode() { return this._charCode; } public get altKey() { return this._altKey; } public get ctrlKey() { return this._ctrlKey; } public get metaKey() { return this._metaKey; } public get shiftKey() { return this._shiftKey; } public get capsLock() { return this._capsLock; } } // Map of `GLFWKey` to `KeyboardEvent.prototype.code`: const glfwKeyToCode: any = { [GLFWKey.KEY_APOSTROPHE]: 'Quote', [GLFWKey.KEY_BACKSLASH]: 'Backslash', [GLFWKey.KEY_BACKSPACE]: 'Backspace', [GLFWKey.KEY_CAPS_LOCK]: 'CapsLock', [GLFWKey.KEY_COMMA]: 'Comma', [GLFWKey.KEY_DELETE]: 'Delete', [GLFWKey.KEY_DOWN]: 'ArrowDown', [GLFWKey.KEY_END]: 'End', [GLFWKey.KEY_ENTER]: 'Enter', [GLFWKey.KEY_EQUAL]: 'Equal', [GLFWKey.KEY_ESCAPE]: 'Escape', [GLFWKey.KEY_F10]: 'F10', [GLFWKey.KEY_F11]: 'F11', [GLFWKey.KEY_F12]: 'F12', [GLFWKey.KEY_F13]: 'F13', [GLFWKey.KEY_F14]: 'F14', [GLFWKey.KEY_F15]: 'F15', [GLFWKey.KEY_F16]: 'F16', [GLFWKey.KEY_F17]: 'F17', [GLFWKey.KEY_F18]: 'F18', [GLFWKey.KEY_F19]: 'F19', [GLFWKey.KEY_F1]: 'F1', [GLFWKey.KEY_F20]: 'F20', [GLFWKey.KEY_F21]: 'F21', [GLFWKey.KEY_F22]: 'F22', [GLFWKey.KEY_F23]: 'F23', [GLFWKey.KEY_F24]: 'F24', [GLFWKey.KEY_F25]: 'F25', [GLFWKey.KEY_F2]: 'F2', [GLFWKey.KEY_F3]: 'F3', [GLFWKey.KEY_F4]: 'F4', [GLFWKey.KEY_F5]: 'F5', [GLFWKey.KEY_F6]: 'F6', [GLFWKey.KEY_F7]: 'F7', [GLFWKey.KEY_F8]: 'F8', [GLFWKey.KEY_F9]: 'F9', [GLFWKey.KEY_GRAVE_ACCENT]: 'Backquote', [GLFWKey.KEY_HOME]: 'Home', [GLFWKey.KEY_INSERT]: 'Insert', [GLFWKey.KEY_KP_0]: 'Numpad0', [GLFWKey.KEY_KP_1]: 'Numpad1', [GLFWKey.KEY_KP_2]: 'Numpad2', [GLFWKey.KEY_KP_3]: 'Numpad3', [GLFWKey.KEY_KP_4]: 'Numpad4', [GLFWKey.KEY_KP_5]: 'Numpad5', [GLFWKey.KEY_KP_6]: 'Numpad6', [GLFWKey.KEY_KP_7]: 'Numpad7', [GLFWKey.KEY_KP_8]: 'Numpad8', [GLFWKey.KEY_KP_9]: 'Numpad9', [GLFWKey.KEY_KP_ADD]: 'NumpadAdd', [GLFWKey.KEY_KP_DECIMAL]: 'NumpadDecimal', [GLFWKey.KEY_KP_DIVIDE]: 'NumpadDivide', [GLFWKey.KEY_KP_ENTER]: 'NumpadEnter', [GLFWKey.KEY_KP_EQUAL]: 'NumpadEqual', [GLFWKey.KEY_KP_MULTIPLY]: 'NumpadMultiply', [GLFWKey.KEY_KP_SUBTRACT]: 'NumpadSubtract', [GLFWKey.KEY_LEFT]: 'ArrowLeft', [GLFWKey.KEY_LEFT_ALT]: 'AltLeft', [GLFWKey.KEY_LEFT_BRACKET]: 'BracketLeft', [GLFWKey.KEY_LEFT_CONTROL]: 'ControlLeft', [GLFWKey.KEY_LEFT_SHIFT]: 'ShiftLeft', [GLFWKey.KEY_LEFT_SUPER]: 'MetaLeft', [GLFWKey.KEY_MENU]: 'Menu', [GLFWKey.KEY_MINUS]: 'Minus', [GLFWKey.KEY_NUM_LOCK]: 'NumLock', [GLFWKey.KEY_PAGE_DOWN]: 'PageDown', [GLFWKey.KEY_PAGE_UP]: 'PageUp', [GLFWKey.KEY_PAUSE]: 'Pause', [GLFWKey.KEY_PERIOD]: 'Period', [GLFWKey.KEY_PRINT_SCREEN]: 'PrintScreen', [GLFWKey.KEY_RIGHT]: 'ArrowRight', [GLFWKey.KEY_RIGHT_ALT]: 'AltRight', [GLFWKey.KEY_RIGHT_BRACKET]: 'BracketRight', [GLFWKey.KEY_RIGHT_CONTROL]: 'ControlRight', [GLFWKey.KEY_RIGHT_SHIFT]: 'ShiftRight', [GLFWKey.KEY_RIGHT_SUPER]: 'MetaRight', [GLFWKey.KEY_SCROLL_LOCK]: 'ScrollLock', [GLFWKey.KEY_SEMICOLON]: 'Semicolon', [GLFWKey.KEY_SLASH]: 'Slash', [GLFWKey.KEY_SPACE]: 'Space', [GLFWKey.KEY_TAB]: 'Tab', [GLFWKey.KEY_UP]: 'ArrowUp', }; // Map of `GLFWKey` to `KeyboardEvent.prototype.key`: const glfwKeyToKey: any = Object.assign({}, glfwKeyToCode, { [GLFWKey.KEY_SPACE]: ' ', [GLFWKey.KEY_LEFT_ALT]: 'Alt', [GLFWKey.KEY_LEFT_CONTROL]: 'Control', [GLFWKey.KEY_LEFT_SHIFT]: 'Shift', [GLFWKey.KEY_LEFT_SUPER]: 'Super', [GLFWKey.KEY_RIGHT_ALT]: 'Alt', [GLFWKey.KEY_RIGHT_CONTROL]: 'Control', [GLFWKey.KEY_RIGHT_SHIFT]: 'Shift', [GLFWKey.KEY_RIGHT_SUPER]: 'Super', }); // Map of `GLFWKey` to `KeyboardEvent.prototype.which`: const glfwKeyToKeyCode: any = { [GLFWKey.KEY_APOSTROPHE]: 222, [GLFWKey.KEY_BACKSLASH]: 220, [GLFWKey.KEY_BACKSPACE]: 8, [GLFWKey.KEY_CAPS_LOCK]: 20, [GLFWKey.KEY_COMMA]: 188, [GLFWKey.KEY_DELETE]: 46, [GLFWKey.KEY_DOWN]: 40, [GLFWKey.KEY_END]: 35, [GLFWKey.KEY_ENTER]: 13, [GLFWKey.KEY_EQUAL]: 187, [GLFWKey.KEY_ESCAPE]: 27, [GLFWKey.KEY_F10]: 121, [GLFWKey.KEY_F11]: 122, [GLFWKey.KEY_F12]: 123, [GLFWKey.KEY_F13]: 123, [GLFWKey.KEY_F14]: 123, [GLFWKey.KEY_F15]: 123, [GLFWKey.KEY_F16]: 123, [GLFWKey.KEY_F17]: 123, [GLFWKey.KEY_F18]: 123, [GLFWKey.KEY_F19]: 123, [GLFWKey.KEY_F1]: 112, [GLFWKey.KEY_F20]: 123, [GLFWKey.KEY_F21]: 123, [GLFWKey.KEY_F22]: 123, [GLFWKey.KEY_F23]: 123, [GLFWKey.KEY_F24]: 123, [GLFWKey.KEY_F25]: 123, [GLFWKey.KEY_F2]: 113, [GLFWKey.KEY_F3]: 114, [GLFWKey.KEY_F4]: 115, [GLFWKey.KEY_F5]: 116, [GLFWKey.KEY_F6]: 117, [GLFWKey.KEY_F7]: 118, [GLFWKey.KEY_F8]: 119, [GLFWKey.KEY_F9]: 120, [GLFWKey.KEY_GRAVE_ACCENT]: 192, [GLFWKey.KEY_HOME]: 36, [GLFWKey.KEY_INSERT]: 45, [GLFWKey.KEY_KP_0]: 96, [GLFWKey.KEY_KP_1]: 97, [GLFWKey.KEY_KP_2]: 98, [GLFWKey.KEY_KP_3]: 99, [GLFWKey.KEY_KP_4]: 100, [GLFWKey.KEY_KP_5]: 101, [GLFWKey.KEY_KP_6]: 102, [GLFWKey.KEY_KP_7]: 103, [GLFWKey.KEY_KP_8]: 104, [GLFWKey.KEY_KP_9]: 105, [GLFWKey.KEY_KP_ADD]: 107, [GLFWKey.KEY_KP_DECIMAL]: 110, [GLFWKey.KEY_KP_DIVIDE]: 111, [GLFWKey.KEY_KP_ENTER]: 13, [GLFWKey.KEY_KP_EQUAL]: 187, [GLFWKey.KEY_KP_MULTIPLY]: 106, [GLFWKey.KEY_KP_SUBTRACT]: 109, [GLFWKey.KEY_LEFT]: 37, [GLFWKey.KEY_LEFT_ALT]: 18, [GLFWKey.KEY_LEFT_BRACKET]: 219, [GLFWKey.KEY_LEFT_CONTROL]: 17, [GLFWKey.KEY_LEFT_SHIFT]: 16, [GLFWKey.KEY_LEFT_SUPER]: 91, [GLFWKey.KEY_MENU]: 18, [GLFWKey.KEY_MINUS]: 189, [GLFWKey.KEY_NUM_LOCK]: 144, [GLFWKey.KEY_PAGE_DOWN]: 34, [GLFWKey.KEY_PAGE_UP]: 33, [GLFWKey.KEY_PAUSE]: 19, [GLFWKey.KEY_PERIOD]: 190, [GLFWKey.KEY_PRINT_SCREEN]: 144, [GLFWKey.KEY_RIGHT]: 39, [GLFWKey.KEY_RIGHT_ALT]: 18, [GLFWKey.KEY_RIGHT_BRACKET]: 221, [GLFWKey.KEY_RIGHT_CONTROL]: 17, [GLFWKey.KEY_RIGHT_SHIFT]: 16, [GLFWKey.KEY_RIGHT_SUPER]: 93, [GLFWKey.KEY_SCROLL_LOCK]: 145, [GLFWKey.KEY_SEMICOLON]: 186, [GLFWKey.KEY_SLASH]: 191, [GLFWKey.KEY_SPACE]: 32, [GLFWKey.KEY_TAB]: 9, [GLFWKey.KEY_UP]: 38, };
0
rapidsai_public_repos/node/modules/jsdom
rapidsai_public_repos/node/modules/jsdom/test/utils.ts
// Copyright (c) 2021-2023, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {RapidsJSDOM} from '@rapidsai/jsdom'; import * as jsdom from 'jsdom'; export let globalWindow: jsdom.DOMWindow; beforeAll(async () => { const opts = { ...RapidsJSDOM.defaultOptions, glfwOptions: {visible: false}, module: require.main, }; if (_transpileESMToCJS) { opts.babel.presets = [ // transpile all ESM to CJS ['@babel/preset-env', {targets: {node: 'current'}}], ...(opts.babel.presets || []), ]; } globalWindow = await (new RapidsJSDOM(opts)).loaded; }); afterAll(() => { if (globalWindow) { // globalWindow.dispatchEvent(new globalWindow.CloseEvent('close')); } }); let _transpileESMToCJS = false; export function transpileESMToCJS() { _transpileESMToCJS = true; } export const eval_ = (code: string) => globalWindow.evalFn(() => eval(code), {code});
0
rapidsai_public_repos/node/modules/jsdom
rapidsai_public_repos/node/modules/jsdom/test/window-tests.ts
// Copyright (c) 2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {globalWindow} from './utils'; describe('Window', () => { test('window.ImageData is from the canvas module', () => { expect(globalWindow.ImageData).toBe(require('canvas').ImageData); }); test('has an `id` property for the GLFW window', () => { expect(typeof globalWindow.id === 'number').toBeTruthy(); }); });
0
rapidsai_public_repos/node/modules/jsdom
rapidsai_public_repos/node/modules/jsdom/test/canvas-tests.ts
// Copyright (c) 2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {globalWindow} from './utils'; describe('HTMLCanvasElement', () => { test(`window.Image exists`, () => { expect(globalWindow.evalFn(() => { return (typeof Image !== 'undefined') && // (typeof HTMLImageElement !== 'undefined') && // (new Image()) instanceof HTMLImageElement; })) .toBe(true); }); test(`getContext('webgl2') returns our OpenGL context`, () => { expect(globalWindow.evalFn(() => { const gl = require('@rapidsai/webgl'); const {document} = window; const canvas = document.body.appendChild(document.createElement('canvas')); return canvas.getContext('webgl2') instanceof gl.WebGL2RenderingContext; })) .toBe(true); }); test(`getContext('webgl2') only creates one OpenGL context`, () => { expect(globalWindow.evalFn(() => { const {document} = window; const canvas = document.body.appendChild(document.createElement('canvas')); return canvas.getContext('webgl2') === canvas.getContext('webgl2'); })) .toBe(true); }); });
0
rapidsai_public_repos/node/modules/jsdom
rapidsai_public_repos/node/modules/jsdom/test/require-tests-transpiled.ts
// Copyright (c) 2023, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {eval_, transpileESMToCJS} from './utils'; transpileESMToCJS(); // this requires we transpile ESM to CJS with babel test('requires a local ESModule module', () => { const code = `require('./files/test-esm-module').default`; expect(typeof eval_(code)).toBe('object'); }); // this requires we transpile ESM to CJS with babel test('requires a local ESModule module that imports an ESModule', () => { const code = `require('./files/test-esm-import')`; const {importedModuleSharesGlobalsWithThisModule} = eval_(code).default; expect(importedModuleSharesGlobalsWithThisModule).toBe(true); });
0
rapidsai_public_repos/node/modules/jsdom
rapidsai_public_repos/node/modules/jsdom/test/tsconfig.json
{ "extends": "../tsconfig.json", "include": [ "../src/**/*.ts", "../test/**/*.ts" ], "compilerOptions": { "target": "esnext", "module": "commonjs", "allowJs": true, "importHelpers": false, "noEmitHelpers": false, "noEmitOnError": false, "sourceMap": false, "inlineSources": false, "inlineSourceMap": false, "downlevelIteration": false, "baseUrl": "../", "paths": { "@rapidsai/jsdom": ["src/index"], "@rapidsai/jsdom/*": ["src/*"] } } }
0
rapidsai_public_repos/node/modules/jsdom
rapidsai_public_repos/node/modules/jsdom/test/test-import.js
// Copyright (c) 2022-2023, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. const assert = require('assert'); const {RapidsJSDOM} = require('@rapidsai/jsdom'); (async () => { // const jsdom = new RapidsJSDOM({glfwOptions: {visible: false}}); await jsdom.loaded; assert((await jsdom.window.evalFn(async () => { const {importedModuleSharesGlobalsWithThisModule} = (await import('./files/test-esm-import')).default; return importedModuleSharesGlobalsWithThisModule; })) === true, 'test-esm-import and test-esm-module should share globals'); assert((await jsdom.window.evalFn(async () => { const {importedModuleSharesGlobalsWithThisModule} = (await import('./files/test-cjs-import')); return importedModuleSharesGlobalsWithThisModule; })) === true, 'test-cjs-import and test-cjs-module should share globals'); jsdom.window.dispatchEvent(new jsdom.window.CloseEvent('close')); return 0; })() .catch((e) => { console.error(e); return 1; }) .then(code => process.exit(code ?? 0));
0
rapidsai_public_repos/node/modules/jsdom
rapidsai_public_repos/node/modules/jsdom/test/require-tests.ts
// Copyright (c) 2021-2022, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {eval_, globalWindow} from './utils'; test('fails to require a non-existent file', () => { expect(() => globalWindow.eval(`require('./files/nonexistent_file')`)) // .toThrow(); }); test('requires a local CommonJS module', () => { const code = `require('./files/test-cjs-module')`; expect(typeof eval_(code)).toBe('object'); }); test('imports a local CommonJS module', async () => { const code = `import('./files/test-cjs-module')`; expect(typeof (await eval_(code))).toBe('object'); }); test('imports a local ESModule module', async () => { const code = `import('./files/test-esm-module')`; expect(typeof (await eval_(code)).default).toBe('object'); }); test('requires a local CommonJS module that imports an ESModule', () => { const code = `require('./files/test-cjs-import')`; const {importedModuleSharesGlobalsWithThisModule} = eval_(code); expect(importedModuleSharesGlobalsWithThisModule).toBe(true); }); test('imports a local CommonJS module that imports an ESModule', async () => { const code = `import('./files/test-cjs-import')`; const {importedModuleSharesGlobalsWithThisModule} = await eval_(code); expect(importedModuleSharesGlobalsWithThisModule).toBe(true); }); test('imports a local ESModule module that imports an ESModule', async () => { const code = `import('./files/test-esm-import')`; const {importedModuleSharesGlobalsWithThisModule} = (await eval_(code)).default; expect(importedModuleSharesGlobalsWithThisModule).toBe(true); }); test('CJS modules imported as ESM modules can modify their named exports ', async () => { const code = `import('./files/test-cjs-module')`; const testCJSModule = (await eval_(code)) as typeof import('./files/test-cjs-module'); expect(typeof testCJSModule).toBe('object'); expect(testCJSModule.foo).toEqual('foo'); testCJSModule.setFooToBar(); expect(testCJSModule.foo).toEqual('bar'); });
0
rapidsai_public_repos/node/modules/jsdom/test
rapidsai_public_repos/node/modules/jsdom/test/files/test-esm-module.js
Object.defineProperty(Object, 'aGlobalField', {value: 10}); export default {aGlobalField: Object.aGlobalField};
0
rapidsai_public_repos/node/modules/jsdom/test
rapidsai_public_repos/node/modules/jsdom/test/files/test-esm-import.js
import testESMModule from './test-esm-module'; export default { importedModuleSharesGlobalsWithThisModule: Object.aGlobalField === testESMModule.aGlobalField, };
0
rapidsai_public_repos/node/modules/jsdom/test
rapidsai_public_repos/node/modules/jsdom/test/files/test-cjs-import.js
const testCJSModule = require('./test-cjs-module'); module.exports = { importedModuleSharesGlobalsWithThisModule: Object.aGlobalField === testCJSModule.aGlobalField, };
0
rapidsai_public_repos/node/modules/jsdom/test
rapidsai_public_repos/node/modules/jsdom/test/files/test-cjs-module.js
Object.defineProperty(Object, 'aGlobalField', {value: 10}); exports.foo = 'foo'; exports.aGlobalField = Object.aGlobalField; exports.setFooToBar = () => { exports.foo = 'bar'; };
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/rmm/package.json
{ "name": "@rapidsai/rmm", "version": "22.12.2", "description": "RMM - NVIDIA RAPIDS Memory Manager", "main": "index.js", "types": "build/js", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "homepage": "https://github.com/rapidsai/node/tree/main/modules/rmm#readme", "bugs": { "url": "https://github.com/rapidsai/node/issues" }, "repository": { "type": "git", "url": "git+https://github.com/rapidsai/node.git" }, "scripts": { "install": "npx rapidsai-install-native-module", "clean": "rimraf build doc compile_commands.json", "doc": "rimraf doc && typedoc --options typedoc.js", "test": "node -r dotenv/config node_modules/.bin/jest -c jest.config.js", "build": "yarn tsc:build && yarn cpp:build", "build:debug": "yarn tsc:build && yarn cpp:build:debug", "compile": "yarn tsc:build && yarn cpp:compile", "compile:debug": "yarn tsc:build && yarn cpp:compile:debug", "rebuild": "yarn tsc:build && yarn cpp:rebuild", "rebuild:debug": "yarn tsc:build && yarn cpp:rebuild:debug", "cpp:clean": "npx cmake-js clean -O build/Release", "cpp:clean:debug": "npx cmake-js clean -O build/Debug", "cpp:build": "npx cmake-js build -g -O build/Release", "cpp:build:debug": "npx cmake-js build -g -D -O build/Debug", "cpp:compile": "npx cmake-js compile -g -O build/Release", "postcpp:compile": "npx rapidsai-merge-compile-commands", "cpp:compile:debug": "npx cmake-js compile -g -D -O build/Debug", "postcpp:compile:debug": "npx rapidsai-merge-compile-commands", "cpp:configure": "npx cmake-js configure -g -O build/Release", "postcpp:configure": "npx rapidsai-merge-compile-commands", "cpp:configure:debug": "npx cmake-js configure -g -D -O build/Debug", "postcpp:configure:debug": "npx rapidsai-merge-compile-commands", "cpp:rebuild": "npx cmake-js rebuild -g -O build/Release", "postcpp:rebuild": "npx rapidsai-merge-compile-commands", "cpp:rebuild:debug": "npx cmake-js rebuild -g -D -O build/Debug", "postcpp:rebuild:debug": "npx rapidsai-merge-compile-commands", "cpp:reconfigure": "npx cmake-js reconfigure -g -O build/Release", "postcpp:reconfigure": "npx rapidsai-merge-compile-commands", "cpp:reconfigure:debug": "npx cmake-js reconfigure -g -D -O build/Debug", "postcpp:reconfigure:debug": "npx rapidsai-merge-compile-commands", "tsc:clean": "rimraf build/js", "tsc:build": "yarn tsc:clean && tsc -p ./tsconfig.json", "tsc:watch": "yarn tsc:clean && tsc -p ./tsconfig.json -w", "dev:cpack:enabled": "echo $npm_package_name" }, "dependencies": { "@rapidsai/cuda": "~22.12.2" }, "files": [ "LICENSE", "README.md", "index.js", "package.json", "CMakeLists.txt", "src/node_rmm", "build/js" ] }
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/rmm/index.js
// Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = require('./build/js/index');
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/rmm/jest.config.js
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. try { require('dotenv').config(); } catch (e) {} module.exports = { 'verbose': true, 'testEnvironment': 'node', 'maxWorkers': process.env.PARALLEL_LEVEL || 1, 'globals': {'ts-jest': {'diagnostics': false, 'tsconfig': 'test/tsconfig.json'}}, 'rootDir': './', 'roots': ['<rootDir>/test/'], 'moduleFileExtensions': ['js', 'ts', 'tsx'], 'coverageReporters': ['lcov'], 'coveragePathIgnorePatterns': ['test\\/.*\\.(ts|tsx|js)$', '/node_modules/'], 'transform': {'^.+\\.jsx?$': 'ts-jest', '^.+\\.tsx?$': 'ts-jest'}, 'transformIgnorePatterns': ['/build/(js|Debug|Release)/*$', '/node_modules/(?!web-stream-tools).+\\.js$'], 'testRegex': '(.*(-|\\.)(test|spec)s?)\\.(ts|tsx|js)$', 'preset': 'ts-jest', 'testMatch': null, 'moduleNameMapper': { '^@rapidsai\/rmm(.*)': '<rootDir>/src/$1', '^\.\.\/(Debug|Release)\/(rapidsai_rmm.node)$': '<rootDir>/build/$1/$2', } };
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/rmm/CMakeLists.txt
#============================================================================= # Copyright (c) 2020-2022, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #============================================================================= cmake_minimum_required(VERSION 3.24.1 FATAL_ERROR) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) unset(CMAKE_LIBRARY_OUTPUT_DIRECTORY) unset(CMAKE_LIBRARY_OUTPUT_DIRECTORY CACHE) option(NODE_RAPIDS_USE_SCCACHE "Enable caching compilation results with sccache" ON) ################################################################################################### # - cmake modules --------------------------------------------------------------------------------- execute_process(COMMAND node -p "require('@rapidsai/core').cmake_modules_path" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" OUTPUT_VARIABLE NODE_RAPIDS_CMAKE_MODULES_PATH OUTPUT_STRIP_TRAILING_WHITESPACE) include("${NODE_RAPIDS_CMAKE_MODULES_PATH}/cmake_policies.cmake") project(rapidsai_rmm VERSION $ENV{npm_package_version} LANGUAGES C CXX) execute_process(COMMAND node -p "require('path').dirname(require.resolve('@rapidsai/core'))" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" OUTPUT_VARIABLE NODE_RAPIDS_CORE_MODULE_PATH OUTPUT_STRIP_TRAILING_WHITESPACE) execute_process(COMMAND node -p "require('path').dirname(require.resolve('@rapidsai/cuda'))" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" OUTPUT_VARIABLE NODE_RAPIDS_CUDA_MODULE_PATH OUTPUT_STRIP_TRAILING_WHITESPACE) include("${NODE_RAPIDS_CMAKE_MODULES_PATH}/ConfigureCXX.cmake") include("${NODE_RAPIDS_CMAKE_MODULES_PATH}/ConfigureCUDA.cmake") include("${NODE_RAPIDS_CMAKE_MODULES_PATH}/ConfigureNapi.cmake") include("${NODE_RAPIDS_CMAKE_MODULES_PATH}/ConfigureRMM.cmake") include("${NODE_RAPIDS_CMAKE_MODULES_PATH}/install_utils.cmake") ################################################################################################### # - rapidsai_rmm target ------------------------------------------------------------------------------- file(GLOB_RECURSE NODE_CUDA_SRC_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") add_library(${PROJECT_NAME} SHARED ${NODE_CUDA_SRC_FILES} ${CMAKE_JS_SRC}) set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "" SUFFIX ".node" BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN" CXX_STANDARD 17 CXX_STANDARD_REQUIRED ON CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON POSITION_INDEPENDENT_CODE ON INTERFACE_POSITION_INDEPENDENT_CODE ON ) target_compile_options(${PROJECT_NAME} PRIVATE "$<BUILD_INTERFACE:$<$<COMPILE_LANGUAGE:C>:${NODE_RAPIDS_CMAKE_C_FLAGS}>>" "$<BUILD_INTERFACE:$<$<COMPILE_LANGUAGE:CXX>:${NODE_RAPIDS_CMAKE_CXX_FLAGS}>>" "$<BUILD_INTERFACE:$<$<COMPILE_LANGUAGE:CUDA>:${NODE_RAPIDS_CMAKE_CUDA_FLAGS}>>" ) target_include_directories(${PROJECT_NAME} PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src>" "$<BUILD_INTERFACE:${NODE_RAPIDS_CUDA_MODULE_PATH}/src>" "$<BUILD_INTERFACE:${RAPIDS_CORE_INCLUDE_DIR}>" "$<BUILD_INTERFACE:${NAPI_INCLUDE_DIRS}>" ) target_compile_definitions(${PROJECT_NAME} PUBLIC "$<$<COMPILE_LANGUAGE:CXX>:CUDA_API_PER_THREAD_DEFAULT_STREAM>" "$<$<COMPILE_LANGUAGE:CUDA>:CUDA_API_PER_THREAD_DEFAULT_STREAM>" ) target_link_libraries(${PROJECT_NAME} PUBLIC ${CMAKE_JS_LIB} rmm::rmm "${NODE_RAPIDS_CUDA_MODULE_PATH}/build/${CMAKE_BUILD_TYPE}/rapidsai_cuda.node" "${NODE_RAPIDS_CORE_MODULE_PATH}/build/${CMAKE_BUILD_TYPE}/rapidsai_core.node") include("${NODE_RAPIDS_CMAKE_MODULES_PATH}/cuda_arch_helpers.cmake") generate_arch_specific_custom_targets( NAME ${PROJECT_NAME} ) generate_install_rules( NAME ${PROJECT_NAME} CUDA_ARCHITECTURES ${CMAKE_CUDA_ARCHITECTURES}) # Create a symlink to compile_commands.json for the llvm-vs-code-extensions.vscode-clangd plugin execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink ${CMAKE_CURRENT_BINARY_DIR}/compile_commands.json ${CMAKE_CURRENT_SOURCE_DIR}/compile_commands.json)
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/rmm/README.md
# <div align="left"><img src="https://rapids.ai/assets/images/rapids_logo.png" width="90px"/>&nbsp; node-rapids RMM - RAPIDS Memory Manager</div> ### Installation `npm install @rapidsai/rmm` ### About The js bindings for [RMM](https://github.com/rapidsai/rmm). For detailed node-RMM API, follow our [API Documentation](https://rapidsai.github.io/node/modules/rmm_src.html).
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/rmm/tsconfig.json
{ "include": ["src"], "exclude": ["node_modules"], "compilerOptions": { "baseUrl": "./", "paths": { "@rapidsai/rmm": ["src/index"], "@rapidsai/rmm/*": ["src/*"] }, "target": "ESNEXT", "module": "commonjs", "outDir": "./build/js", /* Decorators */ "experimentalDecorators": true, /* Basic stuff */ "moduleResolution": "node", "skipLibCheck": true, "skipDefaultLibCheck": true, "lib": ["dom", "esnext", "esnext.asynciterable"], /* Control what is emitted */ "declaration": true, "declarationMap": true, "noEmitOnError": true, "removeComments": false, "downlevelIteration": true, /* Create inline sourcemaps with sources */ "sourceMap": false, "inlineSources": true, "inlineSourceMap": true, /* The most restrictive settings possible */ "strict": true, "importHelpers": true, "noEmitHelpers": true, "noImplicitAny": true, "noUnusedLocals": true, "noImplicitReturns": true, "allowUnusedLabels": false, "noUnusedParameters": true, "allowUnreachableCode": false, "noFallthroughCasesInSwitch": true, "forceConsistentCasingInFileNames": true } }
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/rmm/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2019 NVIDIA Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------------------- include/visit_struct/visit_struct.hpp (modified): BSL 1.0 Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/rmm/typedoc.js
module.exports = { entryPoints: ['src/index.ts'], out: 'doc', name: '@rapidsai/rmm', tsconfig: 'tsconfig.json', excludePrivate: true, excludeProtected: true, excludeExternals: true, };
0
rapidsai_public_repos/node/modules/rmm
rapidsai_public_repos/node/modules/rmm/.vscode/launch.json
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "compounds": [ { "name": "Debug Tests (TS and C++)", "configurations": [ "Debug Tests (launch gdb)", // "Debug Tests (launch lldb)", "Debug Tests (attach node)", ] } ], "configurations": [ { "name": "Debug Tests (TS only)", "type": "node", "request": "launch", "cwd": "${workspaceFolder}", "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", "program": "${workspaceFolder}/node_modules/.bin/jest", "skipFiles": [ "<node_internals>/**", "${workspaceFolder}/node_modules/**" ], "env": { "NODE_NO_WARNINGS": "1", "NODE_ENV": "production", "READABLE_STREAM": "disable", }, "args": [ "--verbose", "--runInBand", "-c", "jest.config.js", "${input:TEST_FILE}" ] }, // { // "name": "Debug Tests (launch lldb)", // // hide the individual configurations from the debug dropdown list // "presentation": { "hidden": true }, // "type": "lldb", // "request": "launch", // "stdio": null, // "cwd": "${workspaceFolder}", // "preLaunchTask": "cpp:ensure:debug:build", // "env": { // "NODE_DEBUG": "1", // "NODE_NO_WARNINGS": "1", // "NODE_ENV": "production", // "READABLE_STREAM": "disable", // }, // "stopOnEntry": false, // "terminal": "console", // "program": "${input:NODE_BINARY}", // "initCommands": [ // "settings set target.disable-aslr false", // ], // "sourceLanguages": ["cpp", "cuda", "javascript"], // "args": [ // "--inspect=9229", // "--expose-internals", // "${workspaceFolder}/node_modules/.bin/jest", // "--verbose", // "--runInBand", // "-c", // "jest.config.js", // "${input:TEST_FILE}" // ], // }, { "name": "Debug Tests (launch gdb)", // hide the individual configurations from the debug dropdown list "presentation": { "hidden": true }, "type": "cppdbg", "request": "launch", "stopAtEntry": false, "externalConsole": false, "cwd": "${workspaceFolder}", "envFile": "${workspaceFolder}/.env", "MIMode": "gdb", "miDebuggerPath": "/usr/bin/gdb", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true } ], "program": "${input:NODE_BINARY}", "environment": [ { "name": "NODE_DEBUG", "value": "1" }, { "name": "NODE_NO_WARNINGS", "value": "1" }, { "name": "NODE_ENV", "value": "production" }, { "name": "READABLE_STREAM", "value": "disable" }, ], "args": [ "--inspect=9229", "--expose-internals", "${workspaceFolder}/node_modules/.bin/jest", "--verbose", "--runInBand", "-c", "jest.config.js", "${input:TEST_FILE}" ], }, { "name": "Debug Tests (attach node)", "type": "node", "request": "attach", // hide the individual configurations from the debug dropdown list "presentation": { "hidden": true }, "port": 9229, "timeout": 60000, "cwd": "${workspaceFolder}", "skipFiles": [ "<node_internals>/**", "${workspaceFolder}/node_modules/**" ], }, ], "inputs": [ { "type": "command", "id": "NODE_BINARY", "command": "shellCommand.execute", "args": { "description": "path to node", "command": "which node", "useFirstResult": true, } }, { "type": "command", "id": "TEST_FILE", "command": "shellCommand.execute", "args": { "cwd": "${workspaceFolder}/modules/rmm", "description": "Select a file to debug", "command": "./node_modules/.bin/jest --listTests | sed -r \"s@$PWD/test/@@g\"", } }, ], }
0
rapidsai_public_repos/node/modules/rmm
rapidsai_public_repos/node/modules/rmm/.vscode/tasks.json
{ "version": "2.0.0", "tasks": [ { "type": "shell", "label": "Rebuild node_rmm TS and C++ (slow)", "group": { "kind": "build", "isDefault": true, }, "command": "if [[ \"${input:CMAKE_BUILD_TYPE}\" == \"Release\" ]]; then yarn rebuild; else yarn rebuild:debug; fi", "problemMatcher": [ "$tsc", { "owner": "cuda", "fileLocation": ["relative", "${workspaceFolder}/build/${input:CMAKE_BUILD_TYPE}"], "pattern": { "file": 1, "line": 2, "severity": 3, "message": 4, "regexp": "^(.*)\\((\\d+)\\):\\s+(error|warning|note|info):\\s+(.*)$" } }, { "owner": "cpp", "fileLocation": ["relative", "${workspaceFolder}/build/${input:CMAKE_BUILD_TYPE}"], "pattern": { "file": 1, "line": 2, "severity": 4, "message": 5, "regexp": "^(.*):(\\d+):(\\d+):\\s+(error|warning|note|info):\\s+(.*)$" } }, ], }, { "type": "npm", "group": "build", "label": "Recompile node_rmm TS (fast)", "script": "tsc:build", "detail": "yarn tsc:build", "problemMatcher": ["$tsc"], }, { "type": "shell", "group": "build", "label": "Recompile node_rmm C++ (fast)", "command": "ninja -C ${workspaceFolder}/build/${input:CMAKE_BUILD_TYPE}", "problemMatcher": [ { "owner": "cuda", "fileLocation": ["relative", "${workspaceFolder}/build/${input:CMAKE_BUILD_TYPE}"], "pattern": { "file": 1, "line": 2, "severity": 3, "message": 4, "regexp": "^(.*)\\((\\d+)\\):\\s+(error|warning|note|info):\\s+(.*)$" } }, { "owner": "cpp", "fileLocation": ["relative", "${workspaceFolder}/build/${input:CMAKE_BUILD_TYPE}"], "pattern": { "file": 1, "line": 2, "severity": 4, "message": 5, "regexp": "^(.*):(\\d+):(\\d+):\\s+(error|warning|note|info):\\s+(.*)$" } }, ], }, ], "inputs": [ { "type": "pickString", "default": "Release", "id": "CMAKE_BUILD_TYPE", "options": ["Release", "Debug"], "description": "C++ Build Type", } ] }
0
rapidsai_public_repos/node/modules/rmm
rapidsai_public_repos/node/modules/rmm/src/node_rmm.ts
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {Memory} from '@rapidsai/cuda'; import {MemoryResourceType} from './addon'; /** @ignore */ export declare const _cpp_exports: any; export declare const per_device_resources: MemoryResource[]; /** * @summary Get the {@link MemoryResource} for the current device. * * <br/> * * Returns the {@link MemoryResource} set for the current device. The initial resource is a {@link * CudaMemoryResource}. * * <br/> * * The "current device" is the device specified by {@link Device.activeDeviceId}. * * <br/> * * @note The returned {@link MemoryResource} should only be used with the current CUDA device. * Changing the current device (e.g. calling `Device.activate()`) and then using the returned * resource can result in undefined behavior. The behavior of a {@link MemoryResource} is undefined * if used while the active CUDA device is a different device from the one that was active when the * {@link MemoryResource} was created. * * @return The {@link MemoryResource} for the current device */ export declare function getCurrentDeviceResource(): MemoryResource; /** * @summary Set the memory resource for the current device. * * <br/> * * If `memoryResource` is not `null`, sets the {@link MemoryResource} for the current device to * `memoryResource`. If `memoryResource` is `null` or `undefined`, no action is taken. * * <br/> * * The "current device" is the device specified by {@link Device.activeDeviceId}. * * <br/> * * The `memoryResource` must outlive the last use of the resource, otherwise behavior * is undefined. It is the caller's responsibility to maintain the lifetime of the {@link * MemoryResource `memoryResource`} object. * * <br/> * * @note The supplied `memoryResource` must have been created for the current CUDA device. The * behavior of a {@link MemoryResource} is undefined if used while the active CUDA device is a * different device from the one that was active when the {@link MemoryResource} was created. * * @param memoryResource If not `null`, the new resource to use for the current device. * @return The previous {@link MemoryResource} for the current device */ export declare function setCurrentDeviceResource(memoryResource: MemoryResource): MemoryResource; /** * @summary Get the {@link MemoryResource} for the specified device. * * <br/> * * Returns the {@link MemoryResource} set for the specified device. The initial resource is a {@link * CudaMemoryResource}. * * <br/> * * `deviceId` must be in the range `[0, Device.numDevices)`, otherwise behavior is * undefined. * * @note The returned {@link MemoryResource} should only be used when CUDA device `deviceId` is the * current device (e.g. set using `Device.activate()`). The behavior of a {@link MemoryResource} * is undefined if used while the active CUDA device is a different device from the one that was * active when the {@link MemoryResource} was created. * * @param deviceId The id of the target device * @return The current {@link MemoryResource} for device `deviceId` */ export declare function getPerDeviceResource(deviceId: number): MemoryResource; /** * @summary Set the {@link MemoryResource} for the specified device. * * If `memoryResource` is not `null`, sets the memory resource pointer for the device specified by * `deviceId` to `memoryResource`. If `memoryResource` is `null` or `undefined`, no action is taken. * * <br/> * * `deviceId` must be in the range `[0, Device.numDevices)`, otherwise behavior is * undefined. * * <br/> * * The `memoryResource` must outlive the last use of the resource, otherwise behavior * is undefined. It is the caller's responsibility to maintain the lifetime of the * `memoryResource` object. * * @note The supplied `memoryResource` must have been created for the current CUDA device. The * behavior of a {@link MemoryResource} is undefined if used while the active CUDA device is a * different device from the one that was active when the {@link MemoryResource} was created. * * @param deviceId The id of the target device * @param memoryResource If not `null`, the new {@link MemoryResource} to use for device `deviceId`. * @return The previous {@link MemoryResource} for device `deviceId` */ export declare function setPerDeviceResource(deviceId: number, memoryResource: MemoryResource): MemoryResource; export declare class MemoryResource { constructor(type: MemoryResourceType.CUDA, device?: number); constructor(type: MemoryResourceType.MANAGED); constructor(type: MemoryResourceType.POOL, upstreamMemoryResource: MemoryResource, initialPoolSize?: number, maximumPoolSize?: number); constructor(type: MemoryResourceType.FIXED_SIZE, upstreamMemoryResource: MemoryResource, blockSize?: number, blocksToPreallocate?: number); constructor(type: MemoryResourceType.BINNING, upstreamMemoryResource: MemoryResource, minSizeExponent?: number, maxSizeExponent?: number); constructor(type: MemoryResourceType.LOGGING, upstreamMemoryResource: MemoryResource, logFilePath?: string, autoFlush?: boolean); /** * @summary A boolean indicating whether the resource supports use of non-null CUDA streams for * allocation/deallocation. */ readonly supportsStreams: boolean; /** * @summary A boolean indicating whether the resource supports the getMemInfo() API. */ readonly supportsGetMemInfo: boolean; /** * Queries the amount of free and total memory for the resource. * * @param stream - the stream whose memory manager we want to retrieve * * @returns a tuple which contains `[free memory, total memory]` (in bytes) */ getMemInfo(stream?: number): [number, number]; /** * @summary Compare this resource to another. * * @remarks * Two `CudaMemoryResource` instances always compare equal, because they can each * deallocate memory allocated by the other. * * @param other - The other resource to compare to * @returns true if the two resources are equal, else false */ isEqual(other: MemoryResource): boolean; } /** @ignore */ type FloatArray = Float32Array|Float64Array; /** @ignore */ type IntArray = Int8Array|Int16Array|Int32Array; /** @ignore */ type UintArray = Uint8Array|Uint16Array|Uint32Array|Uint8ClampedArray; /** @ignore */ type BigIntArray = BigInt64Array|BigUint64Array; /** @ignore */ type TypedArray = FloatArray|IntArray|UintArray; /** @ignore */ type DeviceBufferInput = BigIntArray|TypedArray|ArrayBufferLike; /** * @summary Allocates device memory via RMM (the RAPIDS Memory Manager). * <br/><br/> * This class allocates untyped and *uninitialized* device memory using a * {@link MemoryResource}. If not explicitly specified, the memory resource * returned from {@link getCurrentDeviceResource} is used. */ export declare class DeviceBuffer extends ArrayBuffer implements Memory { constructor(byteLength?: number, mr?: MemoryResource, stream?: number); constructor(source?: DeviceBufferInput, mr?: MemoryResource, stream?: number); constructor(sourceOrByteLength?: DeviceBufferInput|number, mr?: MemoryResource, stream?: number); /** * @summary The length in bytes of the {@link DeviceBuffer}. */ readonly byteLength: number; /** * @summary Returns actual size in bytes of the device memory allocation. * * @note The invariant {@link byteLength} <= `capacity` holds. */ readonly capacity: number; /** * @summary A boolean indicating whether the {@link byteLength} is zero. */ readonly isEmpty: boolean; /** @ignore */ readonly ptr: number; /** * @summary The CUDA Device associated with this {@link DeviceBuffer}. */ readonly device: number; /** * @summary The CUDA stream most recently specified for allocation/deallocation. */ readonly stream: number; /** * @summary The {@link MemoryResource} used to allocate and deallocate device memory. */ readonly memoryResource: MemoryResource; /** * Resize the device memory allocation * * If the requested `new_size` is less than or equal to `capacity`, no * action is taken other than updating the value that is returned from * `byteLength`. Specifically, no memory is allocated nor copied. The value * `capacity` remains the actual size of the device memory allocation. * * @note {@link shrinkToFit} may be used to force the deallocation of unused * {@link capacity}. * * If `new_size` is larger than `capacity`, a new allocation is made on * `stream` to satisfy `new_size`, and the contents of the old allocation are * copied on `stream` to the new allocation. The old allocation is then freed. * The bytes from `[old_size, new_size)` are uninitialized. * * The invariant `byteLength <= capacity` holds. * * @param newSize - The requested new size, in bytes * @param stream - The stream to use for allocation and copy */ resize(newSize: number, stream?: number): void; /** * Sets the stream to be used for deallocation * * If no other {@link DeviceBuffer} method that allocates or copies memory is * called after this call with a different stream argument, then `stream` * will be used for deallocation in the `{@link DeviceBuffer} destructor. * Otherwise, if another {@link DeviceBuffer} method with a stream parameter is * called after this, the later stream parameter will be stored and used in * the destructor. */ setStream(stream: number): void; /** * Forces the deallocation of unused memory. * * Reallocates and copies on stream `stream` the contents of the device memory * allocation to reduce `capacity` to `byteLength`. * * If `byteLength == capacity`, no allocations nor copies occur. * * @param stream - The stream on which the allocation and copy are performed */ shrinkToFit(stream: number): void; /** * Copy a slice of the current buffer into a new buffer * * @param start - the offset (in bytes) from which to start copying * @param end - the offset (in bytes) to stop copying, or the end of the * buffer if unspecified */ slice(start: number, end?: number): DeviceBuffer; /** * @summary Explicitly free the device memory associated with this DeviceBuffer. */ dispose(): void; }
0
rapidsai_public_repos/node/modules/rmm
rapidsai_public_repos/node/modules/rmm/src/index.ts
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. export * as addon from './addon'; export { DeviceBuffer, getCurrentDeviceResource, getPerDeviceResource, setCurrentDeviceResource, setPerDeviceResource, } from './addon'; export * from './memory_resource';
0
rapidsai_public_repos/node/modules/rmm
rapidsai_public_repos/node/modules/rmm/src/memory_resource.ts
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {MemoryResource, MemoryResourceType} from './addon'; /** @ignore */ export {MemoryResource, MemoryResourceType}; /** * @summary {@link MemoryResource} that uses cudaMalloc/Free for allocation/deallocation. */ export class CudaMemoryResource extends MemoryResource { /** * @summary Constructs a MemoryResource which allocates distinct chunks of CUDA GPU memory. * @param device The device ordinal on which to allocate memory (optional). */ constructor(device?: number) { super(MemoryResourceType.CUDA, device); } } /** * @summary {@link MemoryResource} that uses cudaMallocManaged/Free for allocation/deallocation. */ export class ManagedMemoryResource extends MemoryResource { /** * @summary Constructs a MemoryResource which allocates distinct chunks of CUDA Managed memory. */ constructor() { super(MemoryResourceType.MANAGED); } } export interface PoolMemoryResource extends MemoryResource { /** * @summary The {@link MemoryResource} from which to allocate blocks for the pool. */ readonly memoryResource: MemoryResource; } /** * @summary A coalescing best-fit suballocator which uses a pool of memory allocated from an * upstream {@link MemoryResource}. */ export class PoolMemoryResource extends MemoryResource { /** * @summary Constructs a coalescing best-fit suballocator which uses a pool of memory allocated * from an upstream MemoryResource. * @param upstreamMemoryResource The MemoryResource from which to allocate blocks for the pool. * @param initialPoolSize Initial pool size in bytes. By default, an implementation-defined pool * size is used. * @param maximumPoolSize Maximum size in bytes, that the pool can grow to. */ constructor(upstreamMemoryResource: MemoryResource, initialPoolSize?: number, maximumPoolSize?: number) { super(MemoryResourceType.POOL, upstreamMemoryResource, initialPoolSize, maximumPoolSize); } } export interface FixedSizeMemoryResource extends MemoryResource { /** * @summary The {@link MemoryResource} from which to allocate blocks for the pool. */ readonly memoryResource: MemoryResource; } /** * @summary A {@link MemoryResource} which allocates memory blocks of a single fixed size using an * upstream {@link MemoryResource}. * * @note Supports only allocations of size smaller than the configured `blockSize`. */ export class FixedSizeMemoryResource extends MemoryResource { /** * @summary Constructs a MemoryResource which allocates memory blocks of a single fixed size using * an upstream {@link MemoryResource}. * @param upstreamMemoryResource The {@link MemoryResource} from which to allocate blocks for the * pool. * @param blockSize The size of blocks to allocate (default is 1MiB). * @param blocksToPreallocate The number of blocks to allocate to initialize the pool. */ constructor(upstreamMemoryResource: MemoryResource, blockSize?: number, blocksToPreallocate?: number) { super(MemoryResourceType.FIXED_SIZE, upstreamMemoryResource, blockSize, blocksToPreallocate); } } export interface BinningMemoryResource extends MemoryResource { /** * The {@link MemoryResource} to use for allocations larger than any of the bins. */ readonly memoryResource: MemoryResource; /** * @summary Adds a bin of the specified maximum allocation size to this MemoryResource. * * @detail If specified, uses binResource for allocation for this bin. If not specified, uses a * FixedSizeMemoryResource for this bin's allocations. * * Allocations smaller than byteLength and larger than the next smaller bin size will use this * fixed-size MemoryResource. * * @param byteLength The maximum allocation size in bytes for the created bin * @param binResource The resource to use for this bin (optional) */ addBin(byteLength: number, binResource?: MemoryResource): void; } /** * @summary Allocates memory from upstream {@link MemoryResource resources} associated with bin * sizes. */ export class BinningMemoryResource extends MemoryResource { /** * @summary Constructs a {@link MemoryResource} which allocates memory from a set of specified * "bin" sizes based on a specified allocation size from an upstream {@link MemoryResource}. * * @detail If minSizeExponent and maxSizeExponent are specified, initializes with one or more * FixedSizeMemoryResource bins in the range [2^minSizeExponent, 2^maxSizeExponent]. * * Call addBin to add additional bin allocators. * * @param upstreamMemoryResource The MemoryResource to use for allocations larger than any of the * bins. * @param minSizeExponent The base-2 exponent of the minimum size FixedSizeMemoryResource bin to * create (optional). * @param maxSizeExponent The base-2 exponent of the maximum size FixedSizeMemoryResource bin to * create (optional). */ constructor(upstreamMemoryResource: MemoryResource, minSizeExponent?: number, maxSizeExponent?: number) { super(MemoryResourceType.BINNING, upstreamMemoryResource, minSizeExponent, maxSizeExponent); } } export interface LoggingResourceAdapter extends MemoryResource { /** * Path to the file to which logs are written. */ readonly logFilePath: string; /** * The MemoryResource to use for allocations larger than any of the bins. */ readonly memoryResource: MemoryResource; /** * @summary Flushes the buffered log contents. */ flush(): void; } /** * @brief Resource that uses an upstream {@link MemoryResource} to allocate memory and logs * information about the requested allocation/deallocations. * <br/><br/> * An instance of this resource can be constructed with an existing, upstream resource in order to * satisfy allocation requests and log allocation/deallocation activity. */ export class LoggingResourceAdapter extends MemoryResource { /** * @summary Constructs a MemoryResource that logs information about allocations/deallocations * performed by an upstream MemoryResource. * @param upstreamMemoryResource The upstream MemoryResource to log. * @param logFilePath Path to the file to which logs are written. If not provided, falls back to * the `RMM_LOG_FILE` environment variable. * @param autoFlush If true, flushes the log for every (de)allocation. Warning, this will degrade * performance. */ constructor(upstreamMemoryResource: MemoryResource, logFilePath?: string, autoFlush?: boolean) { super(MemoryResourceType.LOGGING, upstreamMemoryResource, logFilePath, autoFlush); } }
0
rapidsai_public_repos/node/modules/rmm
rapidsai_public_repos/node/modules/rmm/src/device_buffer.cpp
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "node_rmm/device_buffer.hpp" #include "node_rmm/memory_resource.hpp" #include "node_rmm/utilities/cpp_to_napi.hpp" #include "node_rmm/utilities/napi_to_cpp.hpp" #include <node_cuda/utilities/error.hpp> namespace nv { Napi::Function DeviceBuffer::Init(Napi::Env const& env, Napi::Object exports) { return DefineClass(env, "DeviceBuffer", { InstanceAccessor<&DeviceBuffer::capacity>("capacity"), InstanceAccessor<&DeviceBuffer::byte_length>("byteLength"), InstanceAccessor<&DeviceBuffer::is_empty>("isEmpty"), InstanceAccessor<&DeviceBuffer::ptr>("ptr"), InstanceAccessor<&DeviceBuffer::device>("device"), InstanceAccessor<&DeviceBuffer::stream>("stream"), InstanceAccessor<&DeviceBuffer::get_mr>("memoryResource"), InstanceMethod<&DeviceBuffer::resize>("resize"), InstanceMethod<&DeviceBuffer::set_stream>("setStream"), InstanceMethod<&DeviceBuffer::shrink_to_fit>("shrinkToFit"), InstanceMethod<&DeviceBuffer::slice>("slice"), InstanceMethod<&DeviceBuffer::dispose>("dispose"), }); } DeviceBuffer::wrapper_t DeviceBuffer::New(Napi::Env const& env, std::unique_ptr<rmm::device_buffer> buffer) { return New(env, std::move(buffer), MemoryResource::Current(env)); } DeviceBuffer::wrapper_t DeviceBuffer::New(Napi::Env const& env, std::unique_ptr<rmm::device_buffer> buffer, MemoryResource::wrapper_t const& mr) { auto buf = New(env, mr, buffer->stream()); buf->buffer_ = std::move(buffer); Napi::MemoryManagement::AdjustExternalMemory(env, buf->size()); return buf; } DeviceBuffer::wrapper_t DeviceBuffer::New(Napi::Env const& env, Napi::TypedArrayOf<uint8_t> const& data, MemoryResource::wrapper_t const& mr, rmm::cuda_stream_view stream) { NODE_CUDA_EXPECT(MemoryResource::IsInstance(mr), "DeviceBuffer constructor requires a valid MemoryResource", data.Env()); return EnvLocalObjectWrap<DeviceBuffer>::New(env, data, mr, stream); } DeviceBuffer::wrapper_t DeviceBuffer::New(Napi::Env const& env, Span<char> const& data, MemoryResource::wrapper_t const& mr, rmm::cuda_stream_view stream) { NODE_CUDA_EXPECT(MemoryResource::IsInstance(mr), "DeviceBuffer constructor requires a valid MemoryResource", env); return EnvLocalObjectWrap<DeviceBuffer>::New(env, data, mr, stream); } DeviceBuffer::wrapper_t DeviceBuffer::New(Napi::Env const& env, void* const data, size_t const size, MemoryResource::wrapper_t const& mr, rmm::cuda_stream_view stream) { NODE_CUDA_EXPECT(MemoryResource::IsInstance(mr), "DeviceBuffer constructor requires a valid MemoryResource", env); return EnvLocalObjectWrap<DeviceBuffer>::New(env, Span<char>(data, size), mr, stream); } DeviceBuffer::DeviceBuffer(CallbackArgs const& args) : EnvLocalObjectWrap<DeviceBuffer>(args) { auto env = args.Env(); auto& arg0 = args[0]; auto& arg1 = args[1]; auto& arg2 = args[2]; auto input = arg0.IsObject() ? arg0.operator Span<char>() : arg0.IsNumber() ? Span<char>(arg0.operator size_t()) : Span<char>(0); mr_ = Napi::Persistent<MemoryResource::wrapper_t>( MemoryResource::IsInstance(arg1) ? arg1.ToObject() : MemoryResource::Current(env)); device_id_ = mr_.Value()->device(); rmm::cuda_stream_view stream = arg2.IsNumber() ? arg2 : rmm::cuda_stream_default; switch (args.Length()) { case 0: case 1: case 2: case 3: { if (input.data() == nullptr || input.size() == 0) { Device::call_in_context(env, device().value(), [&] { buffer_ = std::make_unique<rmm::device_buffer>(input.size(), stream, get_mr()); }); } else { Device::call_in_context(env, device().value(), [&] { buffer_ = std::make_unique<rmm::device_buffer>(input, input.size(), stream, get_mr()); if (stream == rmm::cuda_stream_default) { NODE_CUDA_TRY(cudaStreamSynchronize(stream.value()), env); } }); } Napi::MemoryManagement::AdjustExternalMemory(env, size()); break; } default: NODE_CUDA_EXPECT(false, "DeviceBuffer constructor requires a numeric size, and optional " "stream and memory_resource arguments", env); break; } } void DeviceBuffer::Finalize(Napi::Env env) { dispose(env); } void DeviceBuffer::dispose(Napi::Env env) { if (buffer_.get() != nullptr && capacity() > 0) { Napi::MemoryManagement::AdjustExternalMemory(env, -capacity()); Device::call_in_context(env, device().value(), [&] { buffer_.reset(nullptr); }); } } rmm::cuda_device_id DeviceBuffer::device() const noexcept { return device_id_; }; Napi::Value DeviceBuffer::byte_length(Napi::CallbackInfo const& info) { return Napi::Number::New(info.Env(), size()); } Napi::Value DeviceBuffer::capacity(Napi::CallbackInfo const& info) { return Napi::Value::From(info.Env(), capacity()); } Napi::Value DeviceBuffer::is_empty(Napi::CallbackInfo const& info) { return Napi::Value::From(info.Env(), is_empty()); } Napi::Value DeviceBuffer::ptr(Napi::CallbackInfo const& info) { return Napi::Number::New(info.Env(), reinterpret_cast<uintptr_t>(data())); } void DeviceBuffer::resize(std::size_t new_size, rmm::cuda_stream_view stream) { if (buffer_.get() != nullptr) { auto const prev = capacity(); buffer_->resize(std::max(new_size, 0uL), stream); Napi::MemoryManagement::AdjustExternalMemory(Env(), capacity() - prev); } } void DeviceBuffer::resize(Napi::CallbackInfo const& info) { if (info[0].IsNumber()) { resize(info[0].ToNumber().Int64Value(), rmm::cuda_stream_view{reinterpret_cast<cudaStream_t>(info[1].ToNumber().Int64Value())}); } } void DeviceBuffer::set_stream(Napi::CallbackInfo const& info) { if (buffer_.get() != nullptr) { buffer_->set_stream(CallbackArgs{info}[0]); } } void DeviceBuffer::shrink_to_fit(Napi::CallbackInfo const& info) { if (buffer_.get() != nullptr) { buffer_->shrink_to_fit(CallbackArgs{info}[0]); } } Napi::Value DeviceBuffer::get_mr(Napi::CallbackInfo const& info) { return mr_.Value(); } Napi::Value DeviceBuffer::slice(Napi::CallbackInfo const& info) { CallbackArgs const args{info}; size_t const offset = args[0]; size_t length = size() - offset; if (args.Length() > 1 && info[1].IsNumber()) { length = args[1]; length -= offset; } return New(info.Env(), static_cast<char*>(data()) + offset, length, mr_.Value(), stream()); } Napi::Value DeviceBuffer::device(Napi::CallbackInfo const& info) { return Napi::Value::From(info.Env(), device()); } Napi::Value DeviceBuffer::stream(Napi::CallbackInfo const& info) { return Napi::Value::From(info.Env(), stream()); } void DeviceBuffer::dispose(Napi::CallbackInfo const& info) { dispose(info.Env()); } } // namespace nv
0
rapidsai_public_repos/node/modules/rmm
rapidsai_public_repos/node/modules/rmm/src/addon.cpp
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "node_rmm/device_buffer.hpp" #include "node_rmm/memory_resource.hpp" #include <node_cuda/device.hpp> #include <node_cuda/utilities/error.hpp> #include <nv_node/addon.hpp> #include <nv_node/macros.hpp> struct rapidsai_rmm : public nv::EnvLocalAddon, public Napi::Addon<rapidsai_rmm> { rapidsai_rmm(Napi::Env const& env, Napi::Object exports) : EnvLocalAddon(env, exports) { auto const num_devices = nv::Device::get_num_devices(); _per_device_resources = Napi::Persistent(Napi::Array::New(env, num_devices)); _after_init = Napi::Persistent(Napi::Function::New(env, [=](Napi::CallbackInfo const& info) { auto pdmr = _per_device_resources.Value(); for (int32_t id = 0; id < num_devices; ++id) { pdmr.Set(id, nv::MemoryResource::Device(info.Env(), rmm::cuda_device_id{id})); } })); DefineAddon( exports, { InstanceMethod("init", &rapidsai_rmm::InitAddon), InstanceValue("_cpp_exports", _cpp_exports.Value()), InstanceValue("DeviceBuffer", InitClass<nv::DeviceBuffer>(env, exports)), InstanceValue("MemoryResource", InitClass<nv::MemoryResource>(env, exports)), InstanceMethod<&rapidsai_rmm::get_per_device_resource>("getPerDeviceResource"), InstanceMethod<&rapidsai_rmm::set_per_device_resource>("setPerDeviceResource"), InstanceMethod<&rapidsai_rmm::get_current_device_resource>("getCurrentDeviceResource"), InstanceMethod<&rapidsai_rmm::set_current_device_resource>("setCurrentDeviceResource"), }); } private: Napi::Reference<Napi::Array> _per_device_resources; Napi::Value get_per_device_resource(Napi::CallbackInfo const& info) { auto device_id = info[0].ToNumber(); NODE_CUDA_EXPECT(device_id.Int32Value() < nv::Device::get_num_devices(), "getPerDeviceResource requires device_id to be less than Device.numDevices", info.Env()); return _per_device_resources.Value().Get(device_id); } Napi::Value set_per_device_resource(Napi::CallbackInfo const& info) { auto device_id = info[0].ToNumber(); NODE_CUDA_EXPECT(device_id.Int32Value() < nv::Device::get_num_devices(), "setPerDeviceResource requires device_id to be less than Device.numDevices", info.Env()); NODE_CUDA_EXPECT(nv::MemoryResource::IsInstance(info[1]), "setPerDeviceResource requires a MemoryResource instance", info.Env()); auto prev = _per_device_resources.Value().Get(device_id); auto next = nv::MemoryResource::wrapper_t(info[1].ToObject()); _per_device_resources.Value().Set(device_id, next); rmm::mr::set_per_device_resource(rmm::cuda_device_id{device_id}, next->operator rmm::mr::device_memory_resource*()); return prev; } Napi::Value get_current_device_resource(Napi::CallbackInfo const& info) { return _per_device_resources.Value().Get(nv::Device::active_device_id()); } Napi::Value set_current_device_resource(Napi::CallbackInfo const& info) { NODE_CUDA_EXPECT(nv::MemoryResource::IsInstance(info[0]), "setCurrentDeviceResource requires a MemoryResource instance", info.Env()); auto device_id = nv::Device::active_device_id(); auto prev = _per_device_resources.Value().Get(device_id); auto next = nv::MemoryResource::wrapper_t(info[0].ToObject()); _per_device_resources.Value().Set(device_id, next); rmm::mr::set_per_device_resource(rmm::cuda_device_id{device_id}, next->operator rmm::mr::device_memory_resource*()); return prev; } }; NODE_API_ADDON(rapidsai_rmm);
0
rapidsai_public_repos/node/modules/rmm
rapidsai_public_repos/node/modules/rmm/src/memory_resource.cpp
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "node_rmm/memory_resource.hpp" #include "node_rmm/utilities/napi_to_cpp.hpp" #include <node_cuda/device.hpp> #include <thrust/optional.h> namespace nv { Napi::Function MemoryResource::Init(Napi::Env const& env, Napi::Object exports) { return DefineClass( env, "MemoryResource", { InstanceAccessor<&MemoryResource::get_device>("device"), InstanceAccessor<&MemoryResource::supports_streams>("supportsStreams"), InstanceAccessor<&MemoryResource::supports_get_mem_info>("supportsGetMemInfo"), InstanceMethod<&MemoryResource::is_equal>("isEqual"), InstanceMethod<&MemoryResource::get_mem_info>("getMemInfo"), InstanceMethod<&MemoryResource::add_bin>("addBin"), InstanceMethod<&MemoryResource::flush>("flush"), InstanceAccessor<&MemoryResource::get_file_path>("logFilePath"), InstanceAccessor<&MemoryResource::get_upstream_mr>("memoryResource"), }); } MemoryResource::MemoryResource(CallbackArgs const& args) : EnvLocalObjectWrap<MemoryResource>(args) { auto env = args.Env(); auto arg0 = args[0]; auto arg1 = args[1]; auto arg2 = args[2]; auto arg3 = args[3]; NODE_CUDA_EXPECT(arg0.IsNumber(), "MemoryResource constructor expects a numeric MemoryResourceType argument.", args.Env()); type_ = arg0; switch (type_) { case mr_type::cuda: { mr_ = std::make_shared<rmm::mr::cuda_memory_resource>(); break; } case mr_type::managed: { mr_ = std::make_shared<rmm::mr::managed_memory_resource>(); break; } case mr_type::pool: { NODE_CUDA_EXPECT(MemoryResource::IsInstance(arg1.val), "PoolMemoryResource constructor expects an upstream MemoryResource from " "which to allocate blocks for the pool.", env); rmm::mr::device_memory_resource* mr = arg1; size_t const initial_pool_size = arg2.IsNumber() ? arg2 : -1uL; size_t const maximum_pool_size = arg3.IsNumber() ? arg3 : -1uL; upstream_mr_ = Napi::Persistent(arg1.ToObject()); mr_ = std::make_shared<rmm::mr::pool_memory_resource<rmm::mr::device_memory_resource>>( mr, initial_pool_size == -1uL ? thrust::nullopt : thrust::make_optional(initial_pool_size), maximum_pool_size == -1uL ? thrust::nullopt : thrust::make_optional(maximum_pool_size)); break; } case mr_type::fixed_size: { NODE_CUDA_EXPECT(MemoryResource::IsInstance(arg1.val), "FixedSizeMemoryResource constructor expects an upstream MemoryResource " "from which to allocate blocks for the pool.", env); rmm::mr::device_memory_resource* mr = arg1; size_t const block_size = arg2.IsNumber() ? arg2 : 1 << 20; size_t const blocks_to_preallocate = arg3.IsNumber() ? arg3 : 128; upstream_mr_ = Napi::Persistent(arg1.ToObject()); mr_ = std::make_shared<rmm::mr::fixed_size_memory_resource<rmm::mr::device_memory_resource>>( mr, block_size, blocks_to_preallocate); break; } case mr_type::binning: { NODE_CUDA_EXPECT(MemoryResource::IsInstance(arg1.val), "BinningMemoryResource constructor expects an upstream MemoryResource to " "use for allocations larger than any of the bins.", env); rmm::mr::device_memory_resource* mr = arg1; int8_t const min_size_exponent = arg2.IsNumber() ? arg2 : -1; int8_t const max_size_exponent = arg3.IsNumber() ? arg3 : -1; upstream_mr_ = Napi::Persistent(arg1.ToObject()); mr_ = (min_size_exponent <= -1 || max_size_exponent <= -1 ? std::make_shared<rmm::mr::binning_memory_resource<rmm::mr::device_memory_resource>>(mr) : std::make_shared<rmm::mr::binning_memory_resource<rmm::mr::device_memory_resource>>( mr, min_size_exponent, max_size_exponent)); break; } case mr_type::logging_adaptor: { NODE_CUDA_EXPECT(MemoryResource::IsInstance(arg1.val), "LoggingResourceAdapter constructor expects an upstream MemoryResource.", env); rmm::mr::device_memory_resource* mr = arg1; auto log_file_path = arg2.IsString() ? arg2.operator std::string() : ""; bool auto_flush = arg3.IsBoolean() ? arg3 : false; if (log_file_path == "") { log_file_path = env.Global() .Get("process") .ToObject() .Get("env") .ToObject() .Get("RMM_LOG_FILE") .ToString(); } NODE_CUDA_EXPECT(log_file_path != "", "LoggingResourceAdapter constructor expects an RMM log file name string " "argument or RMM_LOG_FILE environment variable", env); upstream_mr_ = Napi::Persistent(arg1.ToObject()); mr_ = std::make_shared<rmm::mr::logging_resource_adaptor<rmm::mr::device_memory_resource>>( mr, log_file_path, auto_flush); break; } default: throw Napi::Error::New( env, std::string{"Unknown MemoryResource type: "} + std::to_string(static_cast<uint8_t>(type_))); } }; void MemoryResource::Finalize(Napi::Env env) { if (mr_ != nullptr) { Device::call_in_context(env, device().value(), [&] { mr_ = nullptr; }); } } std::string MemoryResource::file_path() const { return log_file_path_; }; bool MemoryResource::is_equal(Napi::Env const& env, rmm::mr::device_memory_resource const& other) const { return mr_->is_equal(other); } std::pair<std::size_t, std::size_t> MemoryResource::get_mem_info( Napi::Env const& env, rmm::cuda_stream_view stream) const { return mr_->get_mem_info(stream); } bool MemoryResource::supports_streams(Napi::Env const& env) const { return mr_->supports_streams(); } bool MemoryResource::supports_get_mem_info(Napi::Env const& env) const { return mr_->supports_get_mem_info(); } void MemoryResource::flush() { if (type_ == mr_type::logging_adaptor) { get_log_mr()->flush(); } } void MemoryResource::add_bin(size_t allocation_size) { if (type_ == mr_type::binning) { get_bin_mr()->add_bin(allocation_size); } } void MemoryResource::add_bin(size_t allocation_size, Napi::Object const& bin_resource) { if (type_ == mr_type::binning) { bin_mrs_.push_back(Napi::Persistent(bin_resource)); get_bin_mr()->add_bin(allocation_size, *MemoryResource::Unwrap(bin_resource)); } } void MemoryResource::flush(Napi::CallbackInfo const& info) { if (type_ == mr_type::logging_adaptor) { flush(); } } void MemoryResource::add_bin(Napi::CallbackInfo const& info) { if (type_ == mr_type::binning) { CallbackArgs const args{info}; switch (info.Length()) { case 1: add_bin(args[0].operator size_t()); break; case 2: add_bin(args[0].operator size_t(), args[1]); break; default: NODE_CUDA_EXPECT( false, "add_bin expects numeric allocation_size and optional MemoryResource arguments."); } } } Napi::Value MemoryResource::is_equal(Napi::CallbackInfo const& info) { if (info.Length() != 1 || !IsInstance(info[0])) { // return Napi::Value::From(info.Env(), false); } rmm::mr::device_memory_resource* other = CallbackArgs{info}[0]; return Napi::Value::From(info.Env(), is_equal(info.Env(), *other)); } Napi::Value MemoryResource::get_mem_info(Napi::CallbackInfo const& info) { auto env = info.Env(); std::pair<std::size_t, std::size_t> mem_info{0, 0}; if (supports_get_mem_info(env)) { mem_info = get_mem_info(env, info[0].IsNumber() ? CallbackArgs{info}[0] : rmm::cuda_stream_default); } return Napi::Value::From(info.Env(), mem_info); } Napi::Value MemoryResource::get_file_path(Napi::CallbackInfo const& info) { return Napi::Value::From(info.Env(), file_path()); } Napi::Value MemoryResource::get_upstream_mr(Napi::CallbackInfo const& info) { return upstream_mr_.Value(); } Napi::Value MemoryResource::supports_streams(Napi::CallbackInfo const& info) { return Napi::Value::From(info.Env(), supports_streams(info.Env())); } Napi::Value MemoryResource::supports_get_mem_info(Napi::CallbackInfo const& info) { return Napi::Value::From(info.Env(), supports_get_mem_info(info.Env())); } } // namespace nv
0
rapidsai_public_repos/node/modules/rmm
rapidsai_public_repos/node/modules/rmm/src/addon.ts
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* eslint-disable @typescript-eslint/no-redeclare */ import {addon as CORE} from '@rapidsai/core'; import {addon as CUDA} from '@rapidsai/cuda'; export const { DeviceBuffer, MemoryResource, getPerDeviceResource, setPerDeviceResource, getCurrentDeviceResource, setCurrentDeviceResource, _cpp_exports, per_device_resources } = require('bindings')('rapidsai_rmm.node').init(CORE, CUDA) as typeof import('./node_rmm'); export type DeviceBuffer = import('./node_rmm').DeviceBuffer; export type MemoryResource = import('./node_rmm').MemoryResource; export type setPerDeviceResource = typeof import('./node_rmm').setPerDeviceResource; export const enum MemoryResourceType { /* ALIGNED_ADAPTOR = 0, */ /* ARENA = 1, */ BINNING = 2, /* CUDA_ASYNC = 3, */ CUDA = 4, /* DEVICE = 5, */ FIXED_SIZE = 6, /* LIMITING_ADAPTOR = 7, */ LOGGING = 8, MANAGED = 9, /* POLYMORPHIC_ALLOCATOR = 10, */ POOL = 11, /* STATISTICS_ADAPTOR = 12, */ /* THREAD_SAFE_ADAPTOR = 13, */ /* THRUST_ALLOCATOR_ADAPTOR = 14, */ /* TRACKING_ADAPTOR = 15, */ }
0
rapidsai_public_repos/node/modules/rmm/src
rapidsai_public_repos/node/modules/rmm/src/node_rmm/device_buffer.hpp
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <node_rmm/memory_resource.hpp> #include <node_rmm/utilities/napi_to_cpp.hpp> #include <nv_node/utilities/span.hpp> #include <rmm/cuda_stream_view.hpp> #include <rmm/device_buffer.hpp> #include <napi.h> #include <memory> namespace nv { struct DeviceBuffer : public EnvLocalObjectWrap<DeviceBuffer> { /** * @brief Initialize and export the DeviceBuffer JavaScript constructor and prototype. * * @param env The active JavaScript environment. * @param exports The exports object to decorate. * @return Napi::Function The DeviceBuffer constructor function. */ static Napi::Function Init(Napi::Env const& env, Napi::Object exports); /** * @brief Construct a new DeviceBuffer instance from an rmm::device_buffer. * * @param buffer Pointer the rmm::device_buffer to own. */ static wrapper_t New(Napi::Env const& env, std::unique_ptr<rmm::device_buffer> buffer); /** * @brief Construct a new DeviceBuffer instance from an rmm::device_buffer. * * @param buffer Pointer the rmm::device_buffer to own. * @param mr Memory resource to use for the device memory allocation. */ static wrapper_t New(Napi::Env const& env, std::unique_ptr<rmm::device_buffer> buffer, MemoryResource::wrapper_t const& mr); /** * @brief Construct a new uninitialized DeviceBuffer instance from C++. * * @param mr Memory resource to use for the device memory allocation. * @param stream CUDA stream on which memory may be allocated if the memory * resource supports streams. */ inline static wrapper_t New(Napi::Env const& env, MemoryResource::wrapper_t const& mr, rmm::cuda_stream_view stream = rmm::cuda_stream_default) { return EnvLocalObjectWrap<DeviceBuffer>::New(env, 0, mr, stream); } /** * @brief Construct a new uninitialized DeviceBuffer instance from C++. * * @param stream CUDA stream on which memory may be allocated if the memory * resource supports streams. */ inline static wrapper_t New(Napi::Env const& env, rmm::cuda_stream_view stream = rmm::cuda_stream_default) { return EnvLocalObjectWrap<DeviceBuffer>::New(env, 0, MemoryResource::Cuda(env), stream); } /** * @brief Construct a new DeviceBuffer instance from an Array. * * @param data Array to copy from. * @param mr Memory resource to use for the device memory allocation. * @param stream CUDA stream on which memory may be allocated if the memory * resource supports streams. */ template <typename T = double> inline static wrapper_t New(Napi::Env const& env, Napi::Array const& data, MemoryResource::wrapper_t const& mr, rmm::cuda_stream_view stream = rmm::cuda_stream_default) { std::vector<T> hvec = NapiToCPP{data}; return New(env, Span<char>{hvec.data(), hvec.size()}, mr, stream); } /** * @brief Construct a new DeviceBuffer instance from a Uint8Array. * * @param data Uint8Array of host memory to copy from. * @param stream CUDA stream on which memory may be allocated if the memory * resource supports streams. */ static wrapper_t New(Napi::Env const& env, Napi::Uint8Array const& data, MemoryResource::wrapper_t const& mr, rmm::cuda_stream_view stream = rmm::cuda_stream_default); /** * @brief Construct a new DeviceBuffer instance from C++. * * @param data Pointer to the host or device memory to copy from. * @param stream CUDA stream on which memory may be allocated if the memory * resource supports streams. */ static wrapper_t New(Napi::Env const& env, Span<char> const& data, MemoryResource::wrapper_t const& mr, rmm::cuda_stream_view stream = rmm::cuda_stream_default); /** * @brief Construct a new DeviceBuffer instance from C++. * * @param data Pointer to the host or device memory to copy from. * @param size Size in bytes to copy. * @param stream CUDA stream on which memory may be allocated if the memory * resource supports streams. * @param mr Memory resource to use for the device memory allocation. */ static wrapper_t New(Napi::Env const& env, void* const data, size_t const size, MemoryResource::wrapper_t const& mr, rmm::cuda_stream_view stream = rmm::cuda_stream_default); /** * @brief Construct a new DeviceBuffer instance. * */ DeviceBuffer(CallbackArgs const& info); /** * @brief Destructor called when the JavaScript VM garbage collects this DeviceBuffer * instance. * * @param env The active JavaScript environment. */ void Finalize(Napi::Env env) override; void dispose(Napi::Env env); rmm::cuda_device_id device() const noexcept; inline void* data() noexcept { return buffer_.get() != nullptr ? buffer_->data() : nullptr; } inline const void* data() const noexcept { return buffer_.get() != nullptr ? buffer_->data() : nullptr; } inline size_t size() const noexcept { return buffer_.get() != nullptr ? buffer_->size() : 0; } inline size_t capacity() const noexcept { return buffer_.get() != nullptr ? buffer_->capacity() : 0; } inline bool is_empty() const noexcept { return buffer_.get() != nullptr ? buffer_->is_empty() : true; } inline rmm::cuda_stream_view stream() const noexcept { return buffer_.get() != nullptr ? buffer_->stream() : rmm::cuda_stream_default; } void resize(std::size_t new_size, rmm::cuda_stream_view stream = rmm::cuda_stream_view{}); inline rmm::mr::device_memory_resource* get_mr() const { return *mr_.Value(); } // convert to void* inline operator void*() noexcept { return static_cast<void*>(data()); } // convert to const void* inline operator const void*() const noexcept { return static_cast<const void*>(data()); } // convert to cudf::valid_type* inline operator uint8_t*() noexcept { return static_cast<uint8_t*>(data()); } // convert to const cudf::valid_type* inline operator const uint8_t*() const noexcept { return static_cast<const uint8_t*>(data()); } // convert to cudf::offset_type* inline operator int32_t*() noexcept { return static_cast<int32_t*>(data()); } // convert to const cudf::offset_type* inline operator const int32_t*() const noexcept { return static_cast<const int32_t*>(data()); } // convert to cudf::bitmask_type* inline operator uint32_t*() noexcept { return static_cast<uint32_t*>(data()); } // convert to const cudf::bitmask_type* inline operator const uint32_t*() const noexcept { return static_cast<const uint32_t*>(data()); } private: Napi::Value get_mr(Napi::CallbackInfo const& info); Napi::Value byte_length(Napi::CallbackInfo const& info); Napi::Value capacity(Napi::CallbackInfo const& info); Napi::Value is_empty(Napi::CallbackInfo const& info); Napi::Value ptr(Napi::CallbackInfo const& info); Napi::Value device(Napi::CallbackInfo const& info); Napi::Value stream(Napi::CallbackInfo const& info); void resize(Napi::CallbackInfo const& info); void set_stream(Napi::CallbackInfo const& info); void shrink_to_fit(Napi::CallbackInfo const& info); Napi::Value slice(Napi::CallbackInfo const& info); void dispose(Napi::CallbackInfo const&); std::unique_ptr<rmm::device_buffer> buffer_; ///< Pointer to the underlying rmm::device_buffer Napi::Reference<MemoryResource::wrapper_t> mr_; ///< Reference to the JS MemoryResource used by this device_buffer rmm::cuda_device_id device_id_{Device::active_device_id()}; }; } // namespace nv
0
rapidsai_public_repos/node/modules/rmm/src
rapidsai_public_repos/node/modules/rmm/src/node_rmm/types.hpp
// Copyright (c) 2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <cstdint> namespace nv { enum class mr_type : uint8_t { aligned_adaptor, arena, binning, cuda_async, cuda, device, fixed_size, limiting_adaptor, logging_adaptor, managed, polymorphic_allocator, pool, statistics_adaptor, thread_safe_adaptor, thrust_allocator_adaptor, tracking_adaptor, }; }
0
rapidsai_public_repos/node/modules/rmm/src
rapidsai_public_repos/node/modules/rmm/src/node_rmm/memory_resource.hpp
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "types.hpp" #include "utilities/cpp_to_napi.hpp" #include <node_cuda/device.hpp> #include <nv_node/objectwrap.hpp> #include <nv_node/utilities/args.hpp> #include <rmm/cuda_stream_view.hpp> // #include <rmm/mr/device/aligned_resource_adaptor.hpp> #include <rmm/mr/device/arena_memory_resource.hpp> #include <rmm/mr/device/binning_memory_resource.hpp> #include <rmm/mr/device/cuda_async_memory_resource.hpp> #include <rmm/mr/device/cuda_memory_resource.hpp> #include <rmm/mr/device/device_memory_resource.hpp> #include <rmm/mr/device/fixed_size_memory_resource.hpp> #include <rmm/mr/device/limiting_resource_adaptor.hpp> #include <rmm/mr/device/logging_resource_adaptor.hpp> #include <rmm/mr/device/managed_memory_resource.hpp> #include <rmm/mr/device/owning_wrapper.hpp> #include <rmm/mr/device/per_device_resource.hpp> #include <rmm/mr/device/polymorphic_allocator.hpp> #include <rmm/mr/device/pool_memory_resource.hpp> #include <rmm/mr/device/statistics_resource_adaptor.hpp> #include <rmm/mr/device/thread_safe_resource_adaptor.hpp> #include <rmm/mr/device/thrust_allocator_adaptor.hpp> #include <rmm/mr/device/tracking_resource_adaptor.hpp> #include <napi.h> #include <memory> namespace nv { struct MemoryResource : public EnvLocalObjectWrap<MemoryResource> { /** * @brief Initialize and export the MemoryResource JavaScript constructor and prototype. * * @param env The active JavaScript environment. * @param exports The exports object to decorate. * @return Napi::Function The MemoryResource constructor function. */ static Napi::Function Init(Napi::Env const& env, Napi::Object exports); inline static wrapper_t Current(Napi::Env const& env) { return MemoryResource::Device(env, rmm::cuda_device_id{Device::active_device_id()}); } inline static wrapper_t Device(Napi::Env const& env, rmm::cuda_device_id id) { auto resource = Cuda(env); auto mr = rmm::mr::get_per_device_resource(id); resource->mr_.reset(mr, [](auto* p) {}); resource->device_id_ = rmm::cuda_device_id{id.value()}; resource->type_ = [&](rmm::mr::device_memory_resource* mr) { if (mr == nullptr) { throw Napi::Error::New(env, "MemoryResource is null"); // } else if // (dynamic_cast<rmm::mr::aligned_resource_adaptor<rmm::mr::device_memory_resource>*>( // mr)) { // return mr_type::aligned_adaptor; } else if (dynamic_cast<rmm::mr::arena_memory_resource<rmm::mr::device_memory_resource>*>( mr)) { return mr_type::arena; } else if (dynamic_cast<rmm::mr::binning_memory_resource<rmm::mr::device_memory_resource>*>( mr)) { return mr_type::binning; } else if (dynamic_cast<rmm::mr::cuda_async_memory_resource*>(mr)) { return mr_type::cuda_async; } else if (dynamic_cast<rmm::mr::cuda_memory_resource*>(mr)) { return mr_type::cuda; } else if (dynamic_cast< rmm::mr::fixed_size_memory_resource<rmm::mr::device_memory_resource>*>(mr)) { return mr_type::fixed_size; } else if (dynamic_cast<rmm::mr::limiting_resource_adaptor<rmm::mr::device_memory_resource>*>( mr)) { return mr_type::limiting_adaptor; } else if (dynamic_cast<rmm::mr::logging_resource_adaptor<rmm::mr::device_memory_resource>*>( mr)) { return mr_type::logging_adaptor; } else if (dynamic_cast<rmm::mr::managed_memory_resource*>(mr)) { return mr_type::managed; } else if (dynamic_cast<rmm::mr::polymorphic_allocator<rmm::mr::device_memory_resource>*>( mr)) { return mr_type::polymorphic_allocator; } else if (dynamic_cast<rmm::mr::pool_memory_resource<rmm::mr::device_memory_resource>*>( mr)) { return mr_type::pool; } else if (dynamic_cast< rmm::mr::statistics_resource_adaptor<rmm::mr::device_memory_resource>*>(mr)) { return mr_type::statistics_adaptor; } else if (dynamic_cast< rmm::mr::thread_safe_resource_adaptor<rmm::mr::device_memory_resource>*>(mr)) { return mr_type::thread_safe_adaptor; } else if (dynamic_cast<rmm::mr::tracking_resource_adaptor<rmm::mr::device_memory_resource>*>( mr)) { return mr_type::tracking_adaptor; } else if (dynamic_cast<rmm::mr::device_memory_resource*>(mr)) { return mr_type::device; } throw Napi::Error::New(env, std::string{"Unknown MemoryResource type: "} + typeid(mr).name()); }(mr); return resource; } inline static wrapper_t Cuda(Napi::Env const& env) { return EnvLocalObjectWrap<MemoryResource>::New(env, mr_type::cuda); } inline static wrapper_t Managed(Napi::Env const& env) { return EnvLocalObjectWrap<MemoryResource>::New(env, mr_type::managed); } inline static wrapper_t Pool(Napi::Env const& env, wrapper_t const& upstream_mr, std::size_t initial_pool_size = -1, std::size_t maximum_pool_size = -1) { return EnvLocalObjectWrap<MemoryResource>::New( env, mr_type::pool, upstream_mr, initial_pool_size, maximum_pool_size); } inline static wrapper_t FixedSize(Napi::Env const& env, wrapper_t const& upstream_mr, std::size_t block_size = 1 << 20, std::size_t blocks_to_preallocate = 128) { return EnvLocalObjectWrap<MemoryResource>::New( env, mr_type::fixed_size, upstream_mr, block_size, blocks_to_preallocate); } inline static wrapper_t Binning(Napi::Env const& env, wrapper_t const& upstream_mr, std::size_t min_size_exponent = -1, std::size_t max_size_exponent = -1) { return EnvLocalObjectWrap<MemoryResource>::New( env, mr_type::binning, upstream_mr, min_size_exponent, max_size_exponent); } inline static wrapper_t Logging(Napi::Env const& env, wrapper_t const& upstream_mr, std::string const& log_file_path = "", bool auto_flush = false) { return EnvLocalObjectWrap<MemoryResource>::New( env, mr_type::logging_adaptor, upstream_mr, log_file_path, auto_flush); } /** * @brief Constructs a new MemoryResource instance. * */ MemoryResource(CallbackArgs const& args); /** * @brief Destructor called when the JavaScript VM garbage collects this MemoryResource * instance. * * @param env The active JavaScript environment. */ void Finalize(Napi::Env env) override; inline rmm::cuda_device_id device() const noexcept { return device_id_; } inline operator rmm::mr::device_memory_resource*() const { return mr_.get(); } std::string file_path() const; /** * @copydoc rmm::mr::device_memory_resource::is_equal( * rmm::mr::device_memory_resource const& other) */ bool is_equal(Napi::Env const& env, rmm::mr::device_memory_resource const& other) const; /** * @copydoc rmm::mr::device_memory_resource::get_mem_info( * rmm::cuda_stream_view stream) */ std::pair<std::size_t, std::size_t> get_mem_info(Napi::Env const& env, rmm::cuda_stream_view stream) const; /** * @copydoc rmm::mr::device_memory_resource::supports_streams() */ bool supports_streams(Napi::Env const& env) const; /** * @copydoc rmm::mr::device_memory_resource::supports_get_mem_info() */ bool supports_get_mem_info(Napi::Env const& env) const; /** * @copydoc rmm::mr::logging_resource_adaptor::flush() */ void flush(); /** * @brief Adds a bin of the specified maximum allocation size to this memory resource. If * specified, uses bin_resource for allocation for this bin. If not specified, creates and uses a * FixedSizeMemoryResource for allocation for this bin. * * Allocations smaller than allocation_size and larger than the next smaller bin size will use * this fixed-size memory resource. * * @param allocation_size The maximum allocation size in bytes for the created bin * @param bin_resource The resource to use for this bin (optional) * @return void */ void add_bin(size_t allocation_size); void add_bin(size_t allocation_size, Napi::Object const& bin_resource); private: inline rmm::mr::binning_memory_resource<rmm::mr::device_memory_resource>* get_bin_mr() { return static_cast<rmm::mr::binning_memory_resource<rmm::mr::device_memory_resource>*>( mr_.get()); } inline rmm::mr::logging_resource_adaptor<rmm::mr::device_memory_resource>* get_log_mr() { return static_cast<rmm::mr::logging_resource_adaptor<rmm::mr::device_memory_resource>*>( mr_.get()); } void flush(Napi::CallbackInfo const& info); void add_bin(Napi::CallbackInfo const& info); Napi::Value is_equal(Napi::CallbackInfo const& info); Napi::Value get_device(Napi::CallbackInfo const& info); Napi::Value get_mem_info(Napi::CallbackInfo const& info); Napi::Value get_file_path(Napi::CallbackInfo const& info); Napi::Value get_upstream_mr(Napi::CallbackInfo const& info); Napi::Value supports_streams(Napi::CallbackInfo const& info); Napi::Value supports_get_mem_info(Napi::CallbackInfo const& info); std::string log_file_path_{}; mr_type type_{mr_type::cuda}; Napi::ObjectReference upstream_mr_; std::vector<Napi::ObjectReference> bin_mrs_; std::shared_ptr<rmm::mr::device_memory_resource> mr_; rmm::cuda_device_id device_id_{Device::active_device_id()}; }; } // namespace nv
0
rapidsai_public_repos/node/modules/rmm/src/node_rmm
rapidsai_public_repos/node/modules/rmm/src/node_rmm/utilities/napi_to_cpp.hpp
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <node_rmm/memory_resource.hpp> #include <node_cuda/utilities/napi_to_cpp.hpp> #include <rmm/cuda_stream_view.hpp> #include <rmm/mr/device/device_memory_resource.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace nv { template <> inline NapiToCPP::operator mr_type() const { return static_cast<mr_type>(this->operator uint8_t()); } template <> inline NapiToCPP::operator rmm::mr::device_memory_resource*() const { if (MemoryResource::IsInstance(val)) { return *MemoryResource::Unwrap(val.ToObject()); } if (val.IsNull() or val.IsUndefined()) { return rmm::mr::get_current_device_resource(); } NAPI_THROW(Napi::Error::New(val.Env()), "Expected value to be a MemoryResource instance"); } template <> inline NapiToCPP::operator rmm::cuda_device_id() const { if (this->IsNumber()) { return rmm::cuda_device_id{this->operator int32_t()}; } NAPI_THROW(Napi::Error::New(val.Env()), "Expected value to be a numeric device ordinal"); } template <> inline NapiToCPP::operator rmm::cuda_stream_view() const { if (this->IsNumber()) { return rmm::cuda_stream_view{this->operator cudaStream_t()}; } NAPI_THROW(Napi::Error::New(val.Env()), "Expected value to be a numeric cudaStream_t"); } } // namespace nv
0
rapidsai_public_repos/node/modules/rmm/src/node_rmm
rapidsai_public_repos/node/modules/rmm/src/node_rmm/utilities/cpp_to_napi.hpp
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "../types.hpp" #include <node_cuda/utilities/cpp_to_napi.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace nv { template <> inline Napi::Value CPPToNapi::operator()(mr_type const& type) const { return this->operator()(static_cast<uint8_t>(type)); } template <> inline Napi::Value CPPToNapi::operator()(rmm::cuda_device_id const& device) const { return this->operator()(device.value()); } template <> inline Napi::Value CPPToNapi::operator()(rmm::cuda_stream_view const& stream) const { return this->operator()(stream.value()); } } // namespace nv namespace Napi { template <> inline Value Value::From(napi_env env, nv::mr_type const& type) { return Value::From(env, static_cast<uint8_t>(type)); } template <> inline Value Value::From(napi_env env, rmm::cuda_device_id const& device) { return Value::From(env, static_cast<int32_t>(device.value())); } template <> inline Value Value::From(napi_env env, rmm::cuda_stream_view const& stream) { return Value::From(env, reinterpret_cast<uintptr_t>(stream.value())); } } // namespace Napi
0
rapidsai_public_repos/node/modules/rmm
rapidsai_public_repos/node/modules/rmm/test/utils.ts
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import {test} from '@jest/globals'; // import {Device, devices} from '@rapidsai/cuda'; export const sizes = { '1_MiB': 1 << 20, '2_MiB': 1 << 21, '4_MiB': 1 << 23, '16_MiB': 1 << 24, }; // export const testForEachDevice = (name: string, fn: (() => void)|((d: Device) => void)) => // test.each([...devices])(name, (d: Device) => { // d.callInContext(() => { // d.synchronize(); // fn(d); // d.synchronize(); // }); // }); import { beforeAll, afterAll, beforeEach, afterEach, } from '@jest/globals'; /* eslint-disable @typescript-eslint/no-misused-promises */ /* eslint-disable @typescript-eslint/no-floating-promises */ beforeAll(flushStdout); afterAll(flushStdout); beforeEach(flushStdout); afterEach(flushStdout); function flushStdout() { return new Promise<void>((done) => { if (process.stdout.write('')) { done(); } else { process.stdout.once('drain', () => { done(); }); } }); }
0
rapidsai_public_repos/node/modules/rmm
rapidsai_public_repos/node/modules/rmm/test/device-buffer-tests.ts
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {Float32Buffer, setDefaultAllocator} from '@rapidsai/cuda'; import {DeviceBuffer} from '@rapidsai/rmm'; describe('DeviceBuffer', () => { test(`can create with 0 bytes`, () => { const db = new DeviceBuffer(0); expect(db.byteLength).toBe(0); expect(db.capacity).toBe(0); expect(db.isEmpty).toBe(true); }); test(`can create with 1000 bytes`, () => { const db = new DeviceBuffer(1000); expect(db.byteLength).toBe(1000); expect(db.capacity).toBe(1000); expect(db.isEmpty).toBe(false); }); test(`resize`, () => { const db = new DeviceBuffer(1000); db.resize(1234); expect(db.byteLength).toBe(1234); expect(db.capacity).toBe(1234); expect(db.isEmpty).toBe(false); db.resize(0); expect(db.byteLength).toBe(0); expect(db.capacity).toBe(1234); expect(db.isEmpty).toBe(true); }); test(`can use with setDefaultAllocator`, () => { setDefaultAllocator((n) => new DeviceBuffer(n)); const ary = new Float32Buffer(1024).fill(100); expect(ary.buffer).toBeInstanceOf(DeviceBuffer); expect(ary.toArray()).toEqual(new Float32Array(1024).fill(100)); setDefaultAllocator(null); }); });
0
rapidsai_public_repos/node/modules/rmm
rapidsai_public_repos/node/modules/rmm/test/tsconfig.json
{ "extends": "../tsconfig.json", "include": [ "../src/**/*.ts", "../test/**/*.ts" ], "compilerOptions": { "target": "esnext", "module": "commonjs", "allowJs": true, "importHelpers": false, "noEmitHelpers": false, "noEmitOnError": false, "sourceMap": false, "inlineSources": false, "inlineSourceMap": false, "downlevelIteration": false, "baseUrl": "../", "paths": { "@rapidsai/rmm": ["src/index"], "@rapidsai/rmm/*": ["src/*"] } } }
0
rapidsai_public_repos/node/modules/rmm/test
rapidsai_public_repos/node/modules/rmm/test/memory_resource/utils.ts
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { BinningMemoryResource, CudaMemoryResource, FixedSizeMemoryResource, LoggingResourceAdapter, ManagedMemoryResource, MemoryResource, PoolMemoryResource, } from '@rapidsai/rmm'; import {mkdtempSync} from 'fs'; import * as Path from 'path'; import {sizes} from '../utils'; type TestConfig = { comparable: boolean; supportsStreams: boolean; supportsGetMemInfo: boolean; createMemoryResource(): MemoryResource; }; let logFileDir = '', logFilePath = ''; beforeAll(() => { logFileDir = mkdtempSync(Path.join('/tmp', 'node_rmm')); logFilePath = Path.join(logFileDir, 'log'); }); afterAll(() => { const rimraf = require('rimraf'); return new Promise<void>((resolve, reject) => { // rimraf(logFileDir, (err?: Error|null) => err ? reject(err) : resolve()); }); }); export const memoryResourceTestConfigs = [ [ `CudaMemoryResource`, { comparable: true, supportsStreams: false, supportsGetMemInfo: true, createMemoryResource: () => new CudaMemoryResource(), } ], [ `ManagedMemoryResource`, { comparable: true, supportsStreams: false, supportsGetMemInfo: true, createMemoryResource: () => new ManagedMemoryResource(), } ], [ `PoolMemoryResource`, { comparable: false, supportsStreams: true, supportsGetMemInfo: false, createMemoryResource: () => new PoolMemoryResource(new CudaMemoryResource(), sizes['1_MiB'], sizes['16_MiB']), } ], [ `FixedSizeMemoryResource`, { comparable: false, supportsStreams: true, supportsGetMemInfo: false, createMemoryResource: () => new FixedSizeMemoryResource(new CudaMemoryResource(), sizes['4_MiB'], 1), } ], [ `BinningMemoryResource`, { comparable: false, supportsStreams: true, supportsGetMemInfo: false, createMemoryResource: () => new BinningMemoryResource( new CudaMemoryResource(), Math.log2(sizes['1_MiB']), Math.log2(sizes['1_MiB'])), } ], [ `LoggingResourceAdapter`, { comparable: true, supportsStreams: false, supportsGetMemInfo: true, createMemoryResource: () => new LoggingResourceAdapter(new CudaMemoryResource(), logFilePath, true), } ], ] as [string, TestConfig][];
0
rapidsai_public_repos/node/modules/rmm/test
rapidsai_public_repos/node/modules/rmm/test/memory_resource/current-device-resource-tests.ts
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {expect} from '@jest/globals'; import { DeviceBuffer, getCurrentDeviceResource, MemoryResource, setCurrentDeviceResource } from '@rapidsai/rmm'; import {sizes} from '../utils'; import {memoryResourceTestConfigs} from './utils'; describe.each(memoryResourceTestConfigs)(`%s`, (_, {createMemoryResource}) => { test(`set/get current device resource`, () => { let prev: MemoryResource|null = null; try { const mr = createMemoryResource(); prev = setCurrentDeviceResource(mr); expect(getCurrentDeviceResource()).toBe(mr); new DeviceBuffer(sizes['2_MiB'], mr); } finally { if (prev != null) { setCurrentDeviceResource(prev); } } }); });
0