docs.sheetjs.com/docz/docs/03-demos/42-engines/04-jsc.md

538 lines
14 KiB
Markdown
Raw Permalink Normal View History

2023-02-13 04:07:25 +00:00
---
title: Swift + JavaScriptCore
2023-02-28 11:40:44 +00:00
pagination_prev: demos/bigdata/index
pagination_next: solutions/input
2023-02-13 04:07:25 +00:00
---
2023-04-27 09:12:19 +00:00
import current from '/version.js';
2024-04-25 08:39:55 +00:00
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
2023-05-07 13:58:36 +00:00
import CodeBlock from '@theme/CodeBlock';
2023-04-27 09:12:19 +00:00
2024-04-25 08:39:55 +00:00
[JavaScriptCore](https://developer.apple.com/documentation/javascriptcore) (JSC)
is the JavaScript engine powering the Safari web browser.
[SheetJS](https://sheetjs.com) is a JavaScript library for reading and writing
data from spreadsheets.
This demo uses JSC and SheetJS to read and write spreadsheets. We'll explore how
to load SheetJS in a JSC context and process spreadsheets and structured data
from C++ and Swift programs.
## Integration Details
2023-02-13 04:07:25 +00:00
2023-09-22 06:32:55 +00:00
The [SheetJS Standalone scripts](/docs/getting-started/installation/standalone)
can be parsed and evaluated in a JSC context.
2023-02-13 04:07:25 +00:00
2024-04-25 08:39:55 +00:00
<Tabs groupId="jsclang">
<TabItem value="swift" label="Swift">
2023-02-13 04:07:25 +00:00
2024-04-25 08:39:55 +00:00
Binary strings can be passed back and forth using `String.Encoding.isoLatin1`.
2023-02-13 04:07:25 +00:00
2024-04-25 08:39:55 +00:00
The SheetJS `read` method[^1], with the `"binary"` type, can parse binary strings.
2023-02-13 04:07:25 +00:00
2024-04-25 08:39:55 +00:00
The `write` method[^2], with the `"binary"` type, can create binary strings.
2023-02-13 04:07:25 +00:00
2024-04-25 08:39:55 +00:00
</TabItem>
<TabItem value="cpp" label="C++">
2023-02-13 04:07:25 +00:00
2024-04-25 08:39:55 +00:00
JSC provides a few special methods for working with `Uint8Array` objects:
2023-02-13 04:07:25 +00:00
2024-04-25 08:39:55 +00:00
- `JSObjectMakeTypedArrayWithBytesNoCopy`[^3] creates a typed array from a
pointer and size. It uses the memory address directly (no copy).
- `JSObjectGetTypedArrayLength`[^4] and `JSObjectGetTypedArrayBytesPtr`[^5] can
return a pointer and size pair from a `Uint8Array` in the JSC engine.
The SheetJS `read` method[^6] can process `Uint8Array` objects.
The `write` method[^7], with the `"buffer"` type, creates `Uint8Array` data.
</TabItem>
</Tabs>
### Initialize JSC
<Tabs groupId="jsclang">
<TabItem value="swift" label="Swift">
A JSC context can be created with the `JSContext` function:
2023-02-13 04:07:25 +00:00
```swift
var context: JSContext!
do {
context = JSContext();
context.exceptionHandler = { _, X in if let e = X { print(e.toString()!); }; };
2024-04-25 08:39:55 +00:00
} catch { print(error.localizedDescription); }
```
</TabItem>
<TabItem value="cpp" label="C++">
A JSC context can be created with the `JSGlobalContextCreate` function:
```cpp
JSGlobalContextRef ctx = JSGlobalContextCreate(NULL);
```
</TabItem>
</Tabs>
JSC does not provide a `global` variable. It can be created in one line:
<Tabs groupId="jsclang">
<TabItem value="swift" label="Swift">
```swift
do {
2023-02-13 04:07:25 +00:00
// highlight-next-line
context.evaluateScript("var global = (function(){ return this; }).call(null);");
} catch { print(error.localizedDescription); }
```
2024-04-25 08:39:55 +00:00
</TabItem>
<TabItem value="cpp" label="C++">
```cpp
#define DOIT(cmd) \
JSStringRef script = JSStringCreateWithUTF8CString(cmd); \
JSValueRef result = JSEvaluateScript(ctx, script, NULL, NULL, 0, NULL); \
JSStringRelease(script);
{ DOIT("var global = (function(){ return this; }).call(null);") }
```
</TabItem>
</Tabs>
### Load SheetJS Scripts
2023-02-13 04:07:25 +00:00
The main library can be loaded by reading the scripts from the file system and
evaluating in the JSC context:
2024-04-25 08:39:55 +00:00
<Tabs groupId="jsclang">
<TabItem value="swift" label="Swift">
2023-02-13 04:07:25 +00:00
```swift
let src = try String(contentsOfFile: "xlsx.full.min.js");
context.evaluateScript(src);
```
2024-04-25 08:39:55 +00:00
</TabItem>
<TabItem value="cpp" label="C++">
```cpp
/* load library */
{
size_t sz = 0; char *file = read_file("xlsx.full.min.js", &sz);
DOIT(file);
}
```
</TabItem>
</Tabs>
2023-02-13 04:07:25 +00:00
To confirm the library is loaded, `XLSX.version` can be inspected:
2024-04-25 08:39:55 +00:00
<Tabs groupId="jsclang">
<TabItem value="swift" label="Swift">
2023-02-13 04:07:25 +00:00
```swift
let XLSX: JSValue! = context.objectForKeyedSubscript("XLSX");
if let ver = XLSX.objectForKeyedSubscript("version") { print(ver.toString()); }
```
2024-04-25 08:39:55 +00:00
</TabItem>
<TabItem value="cpp" label="C++">
```cpp
#define JS_STR_TO_C \
JSStringRef str = JSValueToStringCopy(ctx, result, NULL); \
size_t sz = JSStringGetMaximumUTF8CStringSize(str); \
char *buf = (char *)malloc(sz); \
JSStringGetUTF8CString(str, buf, sz); \
/* get version string */
{
DOIT("XLSX.version")
JS_STR_TO_C
printf("SheetJS library version %s\n", buf);
}
```
</TabItem>
</Tabs>
2023-02-13 04:07:25 +00:00
### Reading Files
2024-04-25 08:39:55 +00:00
<Tabs groupId="jsclang">
<TabItem value="swift" label="Swift">
2023-02-13 04:07:25 +00:00
`String(contentsOf:encoding:)` reads from a path and returns an encoded string:
```swift
/* read sheetjs.xls as Base64 string */
let file_path = shared_dir.appendingPathComponent("sheetjs.xls");
let data: String! = try String(contentsOf: file_path, encoding: String.Encoding.isoLatin1);
```
This string can be loaded into the JS engine and processed:
```swift
/* load data in JSC */
context.setObject(data, forKeyedSubscript: "payload" as (NSCopying & NSObjectProtocol));
/* `payload` (the "forKeyedSubscript" parameter) is a binary string */
context.evaluateScript("var wb = XLSX.read(payload, {type:'binary'});");
```
<details>
<summary><b>Direct Read</b> (click to show)</summary>
2023-05-25 01:36:15 +00:00
`Uint8Array` data can be passed directly, skipping string encoding and decoding:
```swift
let url = URL(fileURLWithPath: file)
var data: Data! = try Data(contentsOf: url);
let count = data.count;
/* Note: the operations must be performed in the closure! */
let wb: JSValue! = data.withUnsafeMutableBytes { (dataPtr: UnsafeMutableRawBufferPointer) in
// highlight-next-line
let ab: JSValue! = JSValue(jsValueRef: JSObjectMakeTypedArrayWithBytesNoCopy(context.jsGlobalContextRef, kJSTypedArrayTypeUint8Array, dataPtr.baseAddress, count, nil, nil, nil), in: context)
/* prepare options argument */
context.evaluateScript(String(format: "var readopts = {type:'array', dense:true}"));
let readopts: JSValue = context.objectForKeyedSubscript("readopts");
/* call XLSX.read */
let XLSX: JSValue! = context.objectForKeyedSubscript("XLSX");
let readfunc: JSValue = XLSX.objectForKeyedSubscript("read");
return readfunc.call(withArguments: [ab, readopts]);
}
```
For broad compatibility with Swift versions, the demo uses the String method.
</details>
2024-04-25 08:39:55 +00:00
</TabItem>
<TabItem value="cpp" label="C++">
There are a few steps for loading data into the JSC engine:
A) The file must be read into a `char*` buffer (using standard C methods)
```cpp
size_t sz; char *file = read_file(argv[1], &sz);
```
B) The typed array must be created with `JSObjectMakeTypedArrayWithBytesNoCopy`
```cpp
JSValueRef u8 = JSObjectMakeTypedArrayWithBytesNoCopy(ctx, kJSTypedArrayTypeUint8Array, file, sz, NULL, NULL, NULL);
```
C) The typed array must be bound to a variable in the global scope:
```cpp
/* assign to `global.buf` */
JSObjectRef global = JSContextGetGlobalObject(ctx);
JSStringRef key = JSStringCreateWithUTF8CString("buf");
JSObjectSetProperty(ctx, global, key, u8, 0, NULL);
JSStringRelease(key);
```
</TabItem>
</Tabs>
2023-02-13 04:07:25 +00:00
### Writing Files
2024-04-25 08:39:55 +00:00
<Tabs groupId="jsclang">
<TabItem value="swift" label="Swift">
2023-02-13 04:07:25 +00:00
When writing to binary string in JavaScriptCore, the result should be stored in
a variable and converted to string in Swift:
```swift
/* write to binary string */
context.evaluateScript("var out = XLSX.write(wb, {type:'binary', bookType:'xlsx'})");
/* `out` from the script is a binary string that can be stringified in Swift */
let outvalue: JSValue! = context.objectForKeyedSubscript("out");
var out: String! = outvalue.toString();
```
`String#write(to:atomically:encoding)` writes the string to the specified path:
```swift
/* write to sheetjsw.xlsx */
let out_path = shared_dir.appendingPathComponent("sheetjsw.xlsx");
try? out.write(to: out_path, atomically: false, encoding: String.Encoding.isoLatin1);
```
2024-04-25 08:39:55 +00:00
</TabItem>
<TabItem value="cpp" label="C++">
The SheetJS `write` method with type `"buffer"` will return a `Uint8Array` object:
```cpp
DOIT("XLSX.write(wb, {type:'buffer', bookType:'xlsb'});")
JSObjectRef u8 = JSValueToObject(ctx, result, NULL);
```
Given the result object, `JSObjectGetTypedArrayLength` pulls the length into C:
```cpp
size_t sz = JSObjectGetTypedArrayLength(ctx, u8, NULL);
```
`JSObjectGetTypedArrayBytesPtr` returns a pointer to the result buffer:
```cpp
char *buf = (char *)JSObjectGetTypedArrayBytesPtr(ctx, u8, NULL);
```
The data can be written to file using standard C methods:
```cpp
FILE *f = fopen("sheetjsw.xlsb", "wb"); fwrite(buf, 1, sz, f); fclose(f);
```
</TabItem>
</Tabs>
2023-02-13 04:07:25 +00:00
## Complete Example
2024-04-25 08:39:55 +00:00
### Swift
2024-03-12 06:47:52 +00:00
:::note pass
2023-02-13 04:07:25 +00:00
2023-06-05 20:12:53 +00:00
This demo was tested in the following environments:
2023-02-13 04:07:25 +00:00
2023-06-05 20:12:53 +00:00
| Architecture | Swift | Date |
|:-------------|:--------|:-----------|
2024-04-05 02:07:37 +00:00
| `darwin-x64` | `5.10` | 2024-04-04 |
2024-03-12 06:47:52 +00:00
| `darwin-arm` | `5.9.2` | 2024-02-21 |
2023-02-13 04:07:25 +00:00
:::
The demo includes a sample `SheetJSCore` Wrapper class to simplify operations.
:::caution This demo only runs on MacOS
This example requires MacOS + Swift and will not work on Windows or Linux!
:::
2023-10-27 01:49:35 +00:00
0) Ensure Swift is installed by running the following command in the terminal:
```bash
swiftc --version
```
If the command is not found, install Xcode.
1) Create a folder for the project:
2023-02-13 04:07:25 +00:00
```bash
mkdir sheetjswift
cd sheetjswift
```
2023-10-27 01:49:35 +00:00
2) Download the SheetJS Standalone script and the test file. Save both files in
2023-09-22 06:32:55 +00:00
the project directory:
2023-02-13 04:07:25 +00:00
<ul>
2023-04-27 09:12:19 +00:00
<li><a href={`https://cdn.sheetjs.com/xlsx-${current}/package/dist/xlsx.full.min.js`}>xlsx.full.min.js</a></li>
2024-04-26 04:16:13 +00:00
<li><a href="https://docs.sheetjs.com/pres.numbers">pres.numbers</a></li>
2023-02-13 04:07:25 +00:00
</ul>
2023-05-07 13:58:36 +00:00
<CodeBlock language="bash">{`\
2023-04-27 09:12:19 +00:00
curl -LO https://cdn.sheetjs.com/xlsx-${current}/package/dist/xlsx.full.min.js
2024-04-26 04:16:13 +00:00
curl -LO https://docs.sheetjs.com/pres.numbers`}
2023-05-07 13:58:36 +00:00
</CodeBlock>
2023-02-13 04:07:25 +00:00
2023-10-27 01:49:35 +00:00
3) Download the Swift scripts for the demo
2023-02-13 04:07:25 +00:00
- [`SheetJSCore.swift`](pathname:///swift/SheetJSCore.swift) Wrapper library
- [`main.swift`](pathname:///swift/main.swift) Command-line script
```bash
curl -LO https://docs.sheetjs.com/swift/SheetJSCore.swift
curl -LO https://docs.sheetjs.com/swift/main.swift
```
2023-10-27 01:49:35 +00:00
4) Build the `SheetJSwift` program:
2023-02-13 04:07:25 +00:00
```bash
swiftc SheetJSCore.swift main.swift -o SheetJSwift
```
2023-10-27 01:49:35 +00:00
5) Test the program:
2023-02-13 04:07:25 +00:00
```bash
./SheetJSwift pres.numbers
```
If successful, a CSV will be printed to console. The script also tries to write
to `SheetJSwift.xlsx`. That file can be verified by opening in Excel / Numbers.
2024-04-25 08:39:55 +00:00
### C++
:::note pass
This demo was tested in the following environments:
| Architecture | Version | Date |
|:-------------|:-----------------|:-----------|
| `darwin-x64` | `7618.1.15.14.7` | 2024-04-24 |
| `linux-x64` | `7618.1.15.14.7` | 2024-04-24 |
:::
0) Install dependencies
<details>
<summary><b>Installation Notes</b> (click to show)</summary>
On the Steam Deck, a few dependencies must be installed before building JSC:
```bash
sudo pacman -Syu base-devel cmake ruby icu glibc linux-api-headers
```
</details>
1) Create a project folder:
```bash
mkdir sheetjs-jsc
cd sheetjs-jsc
```
2) Download and extract the WebKit snapshot:
```bash
curl -LO https://codeload.github.com/WebKit/WebKit/zip/refs/tags/WebKit-7618.1.15.14.7
mv WebKit-7618.1.15.14.7 WebKit.zip
unzip WebKit.zip
```
3) Build JavaScriptCore:
<Tabs groupId="triple">
<TabItem value="darwin-x64" label="MacOS">
```bash
cd WebKit-WebKit-7618.1.15.14.7
Tools/Scripts/build-webkit --jsc-only --cmakeargs="-DENABLE_STATIC_JSC=ON"
cd ..
```
:::caution pass
When this demo was tested on macOS, the build failed with the error message
```
Source/WTF/wtf/text/ASCIILiteral.h:65:34: error: use of undeclared identifier 'NSString'
WTF_EXPORT_PRIVATE RetainPtr<NSString> createNSString() const;
^
1 error generated.
```
The referenced header file must be patched to declare `NSString`:
```objc title="Source/WTF/wtf/text/ASCIILiteral.h (add highlighted lines)"
#include <wtf/text/SuperFastHash.h>
// highlight-start
#ifdef __OBJC__
@class NSString;
#endif
// highlight-end
namespace WTF {
```
:::
</TabItem>
<TabItem value="linux-x64" label="Linux">
```bash
cd WebKit-WebKit-7618.1.15.14.7
env CFLAGS="-Wno-error=dangling-reference -Wno-dangling-reference" CXXFLAGS="-Wno-error=dangling-reference -Wno-dangling-reference" Tools/Scripts/build-webkit --jsc-only --cmakeargs="-Wno-error -DENABLE_STATIC_JSC=ON -DUSE_THIN_ARCHIVES=OFF -DCMAKE_C_FLAGS="-Wno-error -Wno-dangling-reference" -DCMAKE_CXX_FLAGS=-Wno-error -Wno-dangling-reference" --make-args="-j1 -Wno-error -Wno-error=dangling-reference" -j1
cd ..
```
:::danger pass
When this was last tested on the Steam Deck, the build ran for 24 minutes!
:::
</TabItem>
</Tabs>
4) Create a symbolic link to the `Release` folder in the source tree:
```bash
ln -s WebKit-WebKit-7618.1.15.14.7/WebKitBuild/JSCOnly/Release/ .
```
5) Download [`sheetjs-jsc.c`](pathname:///jsc/sheetjs-jsc.c):
```bash
curl -LO https://docs.sheetjs.com/jsc/sheetjs-jsc.c
```
6) Compile the program:
<Tabs groupId="triple">
<TabItem value="darwin-x64" label="MacOS">
```bash
g++ -o sheetjs-jsc sheetjs-jsc.c -IRelease/JavaScriptCore/Headers -LRelease/lib -lbmalloc -licucore -lWTF -lJavaScriptCore -IRelease/JavaScriptCore/Headers
```
</TabItem>
<TabItem value="linux-x64" label="Linux">
```bash
g++ -o sheetjs-jsc sheetjs-jsc.c -IRelease/JavaScriptCore/Headers -LRelease/lib -lJavaScriptCore -lWTF -lbmalloc -licui18n -licuuc -latomic -IRelease/JavaScriptCore/Headers
```
</TabItem>
</Tabs>
7) Download the SheetJS Standalone script and the test file. Save both files in
the project directory:
<ul>
<li><a href={`https://cdn.sheetjs.com/xlsx-${current}/package/dist/xlsx.full.min.js`}>xlsx.full.min.js</a></li>
2024-04-26 04:16:13 +00:00
<li><a href="https://docs.sheetjs.com/pres.numbers">pres.numbers</a></li>
2024-04-25 08:39:55 +00:00
</ul>
<CodeBlock language="bash">{`\
curl -LO https://cdn.sheetjs.com/xlsx-${current}/package/dist/xlsx.full.min.js
2024-04-26 04:16:13 +00:00
curl -LO https://docs.sheetjs.com/pres.numbers`}
2024-04-25 08:39:55 +00:00
</CodeBlock>
8) Run the program:
```bash
./sheetjs-jsc pres.numbers
```
If successful, a CSV will be printed to console. The script also tries to write
to `sheetjsw.xlsb`, which can be opened in a spreadsheet editor.
[^1]: See [`read` in "Reading Files"](/docs/api/parse-options)
[^2]: See [`writeFile` in "Writing Files"](/docs/api/write-options)
[^3]: See [`JSObjectMakeTypedArrayWithBytesNoCopy`](https://developer.apple.com/documentation/javascriptcore/jsobjectmaketypedarraywithbytesnocopy(_:_:_:_:_:_:_:)/) in the JavaScriptCore documentation.
[^4]: See [`JSObjectGetTypedArrayLength`](https://developer.apple.com/documentation/javascriptcore/jsobjectgettypedarraylength(_:_:_:)/) in the JavaScriptCore documentation.
[^5]: See [`JSObjectGetTypedArrayBytesPtr`](
https://developer.apple.com/documentation/javascriptcore/jsobjectgettypedarraybytesptr(_:_:_:)/) in the JavaScriptCore documentation.
[^6]: See [`read` in "Reading Files"](/docs/api/parse-options)
[^7]: See [`writeFile` in "Writing Files"](/docs/api/write-options)