两个版本的插件

This commit is contained in:
onvia
2023-07-20 19:00:23 +08:00
parent 44bce05250
commit 68895155e5
2385 changed files with 1826008 additions and 0 deletions

600
ccc-tnt-psd2ui-v2.4.x/node_modules/canvas/Readme.md generated vendored Normal file
View File

@@ -0,0 +1,600 @@
# node-canvas
![Test](https://github.com/Automattic/node-canvas/workflows/Test/badge.svg)
[![NPM version](https://badge.fury.io/js/canvas.svg)](http://badge.fury.io/js/canvas)
node-canvas is a [Cairo](http://cairographics.org/)-backed Canvas implementation for [Node.js](http://nodejs.org).
## Installation
```bash
$ npm install canvas
```
By default, binaries for macOS, Linux and Windows will be downloaded. If you want to build from source, use `npm install --build-from-source` and see the **Compiling** section below.
The minimum version of Node.js required is **6.0.0**.
### Compiling
If you don't have a supported OS or processor architecture, or you use `--build-from-source`, the module will be compiled on your system. This requires several dependencies, including Cairo and Pango.
For detailed installation information, see the [wiki](https://github.com/Automattic/node-canvas/wiki/_pages). One-line installation instructions for common OSes are below. Note that libgif/giflib, librsvg and libjpeg are optional and only required if you need GIF, SVG and JPEG support, respectively. Cairo v1.10.0 or later is required.
OS | Command
----- | -----
OS X | Using [Homebrew](https://brew.sh/):<br/>`brew install pkg-config cairo pango libpng jpeg giflib librsvg pixman`
Ubuntu | `sudo apt-get install build-essential libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev`
Fedora | `sudo yum install gcc-c++ cairo-devel pango-devel libjpeg-turbo-devel giflib-devel`
Solaris | `pkgin install cairo pango pkg-config xproto renderproto kbproto xextproto`
OpenBSD | `doas pkg_add cairo pango png jpeg giflib`
Windows | See the [wiki](https://github.com/Automattic/node-canvas/wiki/Installation:-Windows)
Others | See the [wiki](https://github.com/Automattic/node-canvas/wiki)
**Mac OS X v10.11+:** If you have recently updated to Mac OS X v10.11+ and are experiencing trouble when compiling, run the following command: `xcode-select --install`. Read more about the problem [on Stack Overflow](http://stackoverflow.com/a/32929012/148072).
If you have xcode 10.0 or higher installed, in order to build from source you need NPM 6.4.1 or higher.
## Quick Example
```javascript
const { createCanvas, loadImage } = require('canvas')
const canvas = createCanvas(200, 200)
const ctx = canvas.getContext('2d')
// Write "Awesome!"
ctx.font = '30px Impact'
ctx.rotate(0.1)
ctx.fillText('Awesome!', 50, 100)
// Draw line under text
var text = ctx.measureText('Awesome!')
ctx.strokeStyle = 'rgba(0,0,0,0.5)'
ctx.beginPath()
ctx.lineTo(50, 102)
ctx.lineTo(50 + text.width, 102)
ctx.stroke()
// Draw cat with lime helmet
loadImage('examples/images/lime-cat.jpg').then((image) => {
ctx.drawImage(image, 50, 0, 70, 70)
console.log('<img src="' + canvas.toDataURL() + '" />')
})
```
## Upgrading from 1.x to 2.x
See the [changelog](https://github.com/Automattic/node-canvas/blob/master/CHANGELOG.md) for a guide to upgrading from 1.x to 2.x.
For version 1.x documentation, see [the v1.x branch](https://github.com/Automattic/node-canvas/tree/v1.x).
## Documentation
This project is an implementation of the Web Canvas API and implements that API as closely as possible. For API documentation, please visit [Mozilla Web Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API). (See [Compatibility Status](https://github.com/Automattic/node-canvas/wiki/Compatibility-Status) for the current API compliance.) All utility methods and non-standard APIs are documented below.
### Utility methods
* [createCanvas()](#createcanvas)
* [createImageData()](#createimagedata)
* [loadImage()](#loadimage)
* [registerFont()](#registerfont)
### Non-standard APIs
* [Image#src](#imagesrc)
* [Image#dataMode](#imagedatamode)
* [Canvas#toBuffer()](#canvastobuffer)
* [Canvas#createPNGStream()](#canvascreatepngstream)
* [Canvas#createJPEGStream()](#canvascreatejpegstream)
* [Canvas#createPDFStream()](#canvascreatepdfstream)
* [Canvas#toDataURL()](#canvastodataurl)
* [CanvasRenderingContext2D#patternQuality](#canvasrenderingcontext2dpatternquality)
* [CanvasRenderingContext2D#quality](#canvasrenderingcontext2dquality)
* [CanvasRenderingContext2D#textDrawingMode](#canvasrenderingcontext2dtextdrawingmode)
* [CanvasRenderingContext2D#globalCompositeOperation = 'saturate'](#canvasrenderingcontext2dglobalcompositeoperation--saturate)
* [CanvasRenderingContext2D#antialias](#canvasrenderingcontext2dantialias)
### createCanvas()
> ```ts
> createCanvas(width: number, height: number, type?: 'PDF'|'SVG') => Canvas
> ```
Creates a Canvas instance. This method works in both Node.js and Web browsers, where there is no Canvas constructor. (See `browser.js` for the implementation that runs in browsers.)
```js
const { createCanvas } = require('canvas')
const mycanvas = createCanvas(200, 200)
const myPDFcanvas = createCanvas(600, 800, 'pdf') // see "PDF Support" section
```
### createImageData()
> ```ts
> createImageData(width: number, height: number) => ImageData
> createImageData(data: Uint8ClampedArray, width: number, height?: number) => ImageData
> // for alternative pixel formats:
> createImageData(data: Uint16Array, width: number, height?: number) => ImageData
> ```
Creates an ImageData instance. This method works in both Node.js and Web browsers.
```js
const { createImageData } = require('canvas')
const width = 20, height = 20
const arraySize = width * height * 4
const mydata = createImageData(new Uint8ClampedArray(arraySize), width)
```
### loadImage()
> ```ts
> loadImage() => Promise<Image>
> ```
Convenience method for loading images. This method works in both Node.js and Web browsers.
```js
const { loadImage } = require('canvas')
const myimg = loadImage('http://server.com/image.png')
myimg.then(() => {
// do something with image
}).catch(err => {
console.log('oh no!', err)
})
// or with async/await:
const myimg = await loadImage('http://server.com/image.png')
// do something with image
```
### registerFont()
> ```ts
> registerFont(path: string, { family: string, weight?: string, style?: string }) => void
> ```
To use a font file that is not installed as a system font, use `registerFont()` to register the font with Canvas. *This must be done before the Canvas is created.*
```js
const { registerFont, createCanvas } = require('canvas')
registerFont('comicsans.ttf', { family: 'Comic Sans' })
const canvas = createCanvas(500, 500)
const ctx = canvas.getContext('2d')
ctx.font = '12px "Comic Sans"'
ctx.fillText('Everyone hates this font :(', 250, 10)
```
The second argument is an object with properties that resemble the CSS properties that are specified in `@font-face` rules. You must specify at least `family`. `weight`, and `style` are optional and default to `'normal'`.
### Image#src
> ```ts
> img.src: string|Buffer
> ```
As in browsers, `img.src` can be set to a `data:` URI or a remote URL. In addition, node-canvas allows setting `src` to a local file path or `Buffer` instance.
```javascript
const { Image } = require('canvas')
// From a buffer:
fs.readFile('images/squid.png', (err, squid) => {
if (err) throw err
const img = new Image()
img.onload = () => ctx.drawImage(img, 0, 0)
img.onerror = err => { throw err }
img.src = squid
})
// From a local file path:
const img = new Image()
img.onload = () => ctx.drawImage(img, 0, 0)
img.onerror = err => { throw err }
img.src = 'images/squid.png'
// From a remote URL:
img.src = 'http://picsum.photos/200/300'
// ... as above
// From a `data:` URI:
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
// ... as above
```
*Note: In some cases, `img.src=` is currently synchronous. However, you should always use `img.onload` and `img.onerror`, as we intend to make `img.src=` always asynchronous as it is in browsers. See https://github.com/Automattic/node-canvas/issues/1007.*
### Image#dataMode
> ```ts
> img.dataMode: number
> ```
Applies to JPEG images drawn to PDF canvases only.
Setting `img.dataMode = Image.MODE_MIME` or `Image.MODE_MIME|Image.MODE_IMAGE` enables MIME data tracking of images. When MIME data is tracked, PDF canvases can embed JPEGs directly into the output, rather than re-encoding into PNG. This can drastically reduce filesize and speed up rendering.
```javascript
const { Image, createCanvas } = require('canvas')
const canvas = createCanvas(w, h, 'pdf')
const img = new Image()
img.dataMode = Image.MODE_IMAGE // Only image data tracked
img.dataMode = Image.MODE_MIME // Only mime data tracked
img.dataMode = Image.MODE_MIME | Image.MODE_IMAGE // Both are tracked
```
If working with a non-PDF canvas, image data *must* be tracked; otherwise the output will be junk.
Enabling mime data tracking has no benefits (only a slow down) unless you are generating a PDF.
### Canvas#toBuffer()
> ```ts
> canvas.toBuffer((err: Error|null, result: Buffer) => void, mimeType?: string, config?: any) => void
> canvas.toBuffer(mimeType?: string, config?: any) => Buffer
> ```
Creates a [`Buffer`](https://nodejs.org/api/buffer.html) object representing the image contained in the canvas.
* **callback** If provided, the buffer will be provided in the callback instead of being returned by the function. Invoked with an error as the first argument if encoding failed, or the resulting buffer as the second argument if it succeeded. Not supported for mimeType `raw` or for PDF or SVG canvases.
* **mimeType** A string indicating the image format. Valid options are `image/png`, `image/jpeg` (if node-canvas was built with JPEG support), `raw` (unencoded data in BGRA order on little-endian (most) systems, ARGB on big-endian systems; top-to-bottom), `application/pdf` (for PDF canvases) and `image/svg+xml` (for SVG canvases). Defaults to `image/png` for image canvases, or the corresponding type for PDF or SVG canvas.
* **config**
* For `image/jpeg`, an object specifying the quality (0 to 1), if progressive compression should be used and/or if chroma subsampling should be used: `{quality: 0.75, progressive: false, chromaSubsampling: true}`. All properties are optional.
* For `image/png`, an object specifying the ZLIB compression level (between 0 and 9), the compression filter(s), the palette (indexed PNGs only), the the background palette index (indexed PNGs only) and/or the resolution (ppi): `{compressionLevel: 6, filters: canvas.PNG_ALL_FILTERS, palette: undefined, backgroundIndex: 0, resolution: undefined}`. All properties are optional.
Note that the PNG format encodes the resolution in pixels per meter, so if you specify `96`, the file will encode 3780 ppm (~96.01 ppi). The resolution is undefined by default to match common browser behavior.
* For `application/pdf`, an object specifying optional document metadata: `{title: string, author: string, subject: string, keywords: string, creator: string, creationDate: Date, modDate: Date}`. All properties are optional and default to `undefined`, except for `creationDate`, which defaults to the current date. *Adding metadata requires Cairo 1.16.0 or later.*
For a description of these properties, see page 550 of [PDF 32000-1:2008](https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf).
Note that there is no standard separator for `keywords`. A space is recommended because it is in common use by other applications, and Cairo will enclose the list of keywords in quotes if a comma or semicolon is used.
**Return value**
If no callback is provided, a [`Buffer`](https://nodejs.org/api/buffer.html). If a callback is provided, none.
#### Examples
```js
// Default: buf contains a PNG-encoded image
const buf = canvas.toBuffer()
// PNG-encoded, zlib compression level 3 for faster compression but bigger files, no filtering
const buf2 = canvas.toBuffer('image/png', { compressionLevel: 3, filters: canvas.PNG_FILTER_NONE })
// JPEG-encoded, 50% quality
const buf3 = canvas.toBuffer('image/jpeg', { quality: 0.5 })
// Asynchronous PNG
canvas.toBuffer((err, buf) => {
if (err) throw err // encoding failed
// buf is PNG-encoded image
})
canvas.toBuffer((err, buf) => {
if (err) throw err // encoding failed
// buf is JPEG-encoded image at 95% quality
}, 'image/jpeg', { quality: 0.95 })
// BGRA pixel values, native-endian
const buf4 = canvas.toBuffer('raw')
const { stride, width } = canvas
// In memory, this is `canvas.height * canvas.stride` bytes long.
// The top row of pixels, in BGRA order on little-endian hardware,
// left-to-right, is:
const topPixelsBGRALeftToRight = buf4.slice(0, width * 4)
// And the third row is:
const row3 = buf4.slice(2 * stride, 2 * stride + width * 4)
// SVG and PDF canvases
const myCanvas = createCanvas(w, h, 'pdf')
myCanvas.toBuffer() // returns a buffer containing a PDF-encoded canvas
// With optional metadata:
myCanvas.toBuffer('application/pdf', {
title: 'my picture',
keywords: 'node.js demo cairo',
creationDate: new Date()
})
```
### Canvas#createPNGStream()
> ```ts
> canvas.createPNGStream(config?: any) => ReadableStream
> ```
Creates a [`ReadableStream`](https://nodejs.org/api/stream.html#stream_class_stream_readable) that emits PNG-encoded data.
* `config` An object specifying the ZLIB compression level (between 0 and 9), the compression filter(s), the palette (indexed PNGs only) and/or the background palette index (indexed PNGs only): `{compressionLevel: 6, filters: canvas.PNG_ALL_FILTERS, palette: undefined, backgroundIndex: 0, resolution: undefined}`. All properties are optional.
#### Examples
```javascript
const fs = require('fs')
const out = fs.createWriteStream(__dirname + '/test.png')
const stream = canvas.createPNGStream()
stream.pipe(out)
out.on('finish', () => console.log('The PNG file was created.'))
```
To encode indexed PNGs from canvases with `pixelFormat: 'A8'` or `'A1'`, provide an options object:
```js
const palette = new Uint8ClampedArray([
//r g b a
0, 50, 50, 255, // index 1
10, 90, 90, 255, // index 2
127, 127, 255, 255
// ...
])
canvas.createPNGStream({
palette: palette,
backgroundIndex: 0 // optional, defaults to 0
})
```
### Canvas#createJPEGStream()
> ```ts
> canvas.createJPEGStream(config?: any) => ReadableStream
> ```
Creates a [`ReadableStream`](https://nodejs.org/api/stream.html#stream_class_stream_readable) that emits JPEG-encoded data.
*Note: At the moment, `createJPEGStream()` is synchronous under the hood. That is, it runs in the main thread, not in the libuv threadpool.*
* `config` an object specifying the quality (0 to 1), if progressive compression should be used and/or if chroma subsampling should be used: `{quality: 0.75, progressive: false, chromaSubsampling: true}`. All properties are optional.
#### Examples
```javascript
const fs = require('fs')
const out = fs.createWriteStream(__dirname + '/test.jpeg')
const stream = canvas.createJPEGStream()
stream.pipe(out)
out.on('finish', () => console.log('The JPEG file was created.'))
// Disable 2x2 chromaSubsampling for deeper colors and use a higher quality
const stream = canvas.createJPEGStream({
quality: 0.95,
chromaSubsampling: false
})
```
### Canvas#createPDFStream()
> ```ts
> canvas.createPDFStream(config?: any) => ReadableStream
> ```
* `config` an object specifying optional document metadata: `{title: string, author: string, subject: string, keywords: string, creator: string, creationDate: Date, modDate: Date}`. See `toBuffer()` for more information. *Adding metadata requires Cairo 1.16.0 or later.*
Applies to PDF canvases only. Creates a [`ReadableStream`](https://nodejs.org/api/stream.html#stream_class_stream_readable) that emits the encoded PDF. `canvas.toBuffer()` also produces an encoded PDF, but `createPDFStream()` can be used to reduce memory usage.
### Canvas#toDataURL()
This is a standard API, but several non-standard calls are supported. The full list of supported calls is:
```js
dataUrl = canvas.toDataURL() // defaults to PNG
dataUrl = canvas.toDataURL('image/png')
dataUrl = canvas.toDataURL('image/jpeg')
dataUrl = canvas.toDataURL('image/jpeg', quality) // quality from 0 to 1
canvas.toDataURL((err, png) => { }) // defaults to PNG
canvas.toDataURL('image/png', (err, png) => { })
canvas.toDataURL('image/jpeg', (err, jpeg) => { }) // sync JPEG is not supported
canvas.toDataURL('image/jpeg', {...opts}, (err, jpeg) => { }) // see Canvas#createJPEGStream for valid options
canvas.toDataURL('image/jpeg', quality, (err, jpeg) => { }) // spec-following; quality from 0 to 1
```
### CanvasRenderingContext2D#patternQuality
> ```ts
> context.patternQuality: 'fast'|'good'|'best'|'nearest'|'bilinear'
> ```
Defaults to `'good'`. Affects pattern (gradient, image, etc.) rendering quality.
### CanvasRenderingContext2D#quality
> ```ts
> context.quality: 'fast'|'good'|'best'|'nearest'|'bilinear'
> ```
Defaults to `'good'`. Like `patternQuality`, but applies to transformations affecting more than just patterns.
### CanvasRenderingContext2D#textDrawingMode
> ```ts
> context.textDrawingMode: 'path'|'glyph'
> ```
Defaults to `'path'`. The effect depends on the canvas type:
* **Standard (image)** `glyph` and `path` both result in rasterized text. Glyph mode is faster than `path`, but may result in lower-quality text, especially when rotated or translated.
* **PDF** `glyph` will embed text instead of paths into the PDF. This is faster to encode, faster to open with PDF viewers, yields a smaller file size and makes the text selectable. The subset of the font needed to render the glyphs will be embedded in the PDF. This is usually the mode you want to use with PDF canvases.
* **SVG** `glyph` does *not* cause `<text>` elements to be produced as one might expect ([cairo bug](https://gitlab.freedesktop.org/cairo/cairo/issues/253)). Rather, `glyph` will create a `<defs>` section with a `<symbol>` for each glyph, then those glyphs be reused via `<use>` elements. `path` mode creates a `<path>` element for each text string. `glyph` mode is faster and yields a smaller file size.
In `glyph` mode, `ctx.strokeText()` and `ctx.fillText()` behave the same (aside from using the stroke and fill style, respectively).
This property is tracked as part of the canvas state in save/restore.
### CanvasRenderingContext2D#globalCompositeOperation = 'saturate'
In addition to all of the standard global composite operations defined by the Canvas specification, the ['saturate'](https://www.cairographics.org/operators/#saturate) operation is also available.
### CanvasRenderingContext2D#antialias
> ```ts
> context.antialias: 'default'|'none'|'gray'|'subpixel'
> ```
Sets the anti-aliasing mode.
## PDF Output Support
node-canvas can create PDF documents instead of images. The canvas type must be set when creating the canvas as follows:
```js
const canvas = createCanvas(200, 500, 'pdf')
```
An additional method `.addPage()` is then available to create multiple page PDFs:
```js
// On first page
ctx.font = '22px Helvetica'
ctx.fillText('Hello World', 50, 80)
ctx.addPage()
// Now on second page
ctx.font = '22px Helvetica'
ctx.fillText('Hello World 2', 50, 80)
canvas.toBuffer() // returns a PDF file
canvas.createPDFStream() // returns a ReadableStream that emits a PDF
// With optional document metadata (requires Cairo 1.16.0):
canvas.toBuffer('application/pdf', {
title: 'my picture',
keywords: 'node.js demo cairo',
creationDate: new Date()
})
```
It is also possible to create pages with different sizes by passing `width` and `height` to the `.addPage()` method:
```js
ctx.font = '22px Helvetica'
ctx.fillText('Hello World', 50, 80)
ctx.addPage(400, 800)
ctx.fillText('Hello World 2', 50, 80)
```
See also:
* [Image#dataMode](#imagedatamode) for embedding JPEGs in PDFs
* [Canvas#createPDFStream()](#canvascreatepdfstream) for creating PDF streams
* [CanvasRenderingContext2D#textDrawingMode](#canvasrenderingcontext2dtextdrawingmode)
for embedding text instead of paths
## SVG Output Support
node-canvas can create SVG documents instead of images. The canvas type must be set when creating the canvas as follows:
```js
const canvas = createCanvas(200, 500, 'svg')
// Use the normal primitives.
fs.writeFileSync('out.svg', canvas.toBuffer())
```
## SVG Image Support
If librsvg is available when node-canvas is installed, node-canvas can render SVG images to your canvas context. This currently works by rasterizing the SVG image (i.e. drawing an SVG image to an SVG canvas will not preserve the SVG data).
```js
const img = new Image()
img.onload = () => ctx.drawImage(img, 0, 0)
img.onerror = err => { throw err }
img.src = './example.svg'
```
## Image pixel formats (experimental)
node-canvas has experimental support for additional pixel formats, roughly following the [Canvas color space proposal](https://github.com/WICG/canvas-color-space/blob/master/CanvasColorSpaceProposal.md).
```js
const canvas = createCanvas(200, 200)
const ctx = canvas.getContext('2d', { pixelFormat: 'A8' })
```
By default, canvases are created in the `RGBA32` format, which corresponds to the native HTML Canvas behavior. Each pixel is 32 bits. The JavaScript APIs that involve pixel data (`getImageData`, `putImageData`) store the colors in the order {red, green, blue, alpha} without alpha pre-multiplication. (The C++ API stores the colors in the order {alpha, red, green, blue} in native-[endian](https://en.wikipedia.org/wiki/Endianness) ordering, with alpha pre-multiplication.)
These additional pixel formats have experimental support:
* `RGB24` Like `RGBA32`, but the 8 alpha bits are always opaque. This format is always used if the `alpha` context attribute is set to false (i.e. `canvas.getContext('2d', {alpha: false})`). This format can be faster than `RGBA32` because transparency does not need to be calculated.
* `A8` Each pixel is 8 bits. This format can either be used for creating grayscale images (treating each byte as an alpha value), or for creating indexed PNGs (treating each byte as a palette index) (see [the example using alpha values with `fillStyle`](examples/indexed-png-alpha.js) and [the example using `imageData`](examples/indexed-png-image-data.js)).
* `RGB16_565` Each pixel is 16 bits, with red in the upper 5 bits, green in the middle 6 bits, and blue in the lower 5 bits, in native platform endianness. Some hardware devices and frame buffers use this format. Note that PNG does not support this format; when creating a PNG, the image will be converted to 24-bit RGB. This format is thus suboptimal for generating PNGs. `ImageData` instances for this mode use a `Uint16Array` instead of a `Uint8ClampedArray`.
* `A1` Each pixel is 1 bit, and pixels are packed together into 32-bit quantities. The ordering of the bits matches the endianness of the
platform: on a little-endian machine, the first pixel is the least-significant bit. This format can be used for creating single-color images. *Support for this format is incomplete, see note below.*
* `RGB30` Each pixel is 30 bits, with red in the upper 10, green in the middle 10, and blue in the lower 10. (Requires Cairo 1.12 or later.) *Support for this format is incomplete, see note below.*
Notes and caveats:
* Using a non-default format can affect the behavior of APIs that involve pixel data:
* `context2d.createImageData` The size of the array returned depends on the number of bit per pixel for the underlying image data format, per the above descriptions.
* `context2d.getImageData` The format of the array returned depends on the underlying image mode, per the above descriptions. Be aware of platform endianness, which can be determined using node.js's [`os.endianness()`](https://nodejs.org/api/os.html#os_os_endianness)
function.
* `context2d.putImageData` As above.
* `A1` and `RGB30` do not yet support `getImageData` or `putImageData`. Have a use case and/or opinion on working with these formats? Open an issue and let us know! (See #935.)
* `A1`, `A8`, `RGB30` and `RGB16_565` with shadow blurs may crash or not render properly.
* The `ImageData(width, height)` and `ImageData(Uint8ClampedArray, width)` constructors assume 4 bytes per pixel. To create an `ImageData` instance with a different number of bytes per pixel, use `new ImageData(new Uint8ClampedArray(size), width, height)` or `new ImageData(new Uint16ClampedArray(size), width, height)`.
## Testing
First make sure you've built the latest version. Get all the deps you need (see [compiling](#compiling) above), and run:
```
npm install --build-from-source
```
For visual tests: `npm run test-server` and point your browser to http://localhost:4000.
For unit tests: `npm run test`.
## Benchmarks
Benchmarks live in the `benchmarks` directory.
## Examples
Examples line in the `examples` directory. Most produce a png image of the same name, and others such as *live-clock.js* launch an HTTP server to be viewed in the browser.
## Original Authors
- TJ Holowaychuk ([tj](http://github.com/tj))
- Nathan Rajlich ([TooTallNate](http://github.com/TooTallNate))
- Rod Vagg ([rvagg](http://github.com/rvagg))
- Juriy Zaytsev ([kangax](http://github.com/kangax))
## License
### node-canvas
(The MIT License)
Copyright (c) 2010 LearnBoost, and contributors &lt;dev@learnboost.com&gt;
Copyright (c) 2014 Automattic, Inc and contributors &lt;dev@automattic.com&gt;
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the 'Software'), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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 AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
### BMP parser
See [license](src/bmp/LICENSE.md)

230
ccc-tnt-psd2ui-v2.4.x/node_modules/canvas/binding.gyp generated vendored Normal file
View File

@@ -0,0 +1,230 @@
{
'conditions': [
['OS=="win"', {
'variables': {
'GTK_Root%': 'C:/GTK', # Set the location of GTK all-in-one bundle
'with_jpeg%': 'false',
'with_gif%': 'false',
'with_rsvg%': 'false',
'variables': { # Nest jpeg_root to evaluate it before with_jpeg
'jpeg_root%': '<!(node ./util/win_jpeg_lookup)'
},
'jpeg_root%': '<(jpeg_root)', # Take value of nested variable
'conditions': [
['jpeg_root==""', {
'with_jpeg%': 'false'
}, {
'with_jpeg%': 'true'
}]
]
}
}, { # 'OS!="win"'
'variables': {
'with_jpeg%': '<!(node ./util/has_lib.js jpeg)',
'with_gif%': '<!(node ./util/has_lib.js gif)',
'with_rsvg%': '<!(node ./util/has_lib.js rsvg)'
}
}]
],
'targets': [
{
'target_name': 'canvas-postbuild',
'dependencies': ['canvas'],
'conditions': [
['OS=="win"', {
'copies': [{
'destination': '<(PRODUCT_DIR)',
'files': [
'<(GTK_Root)/bin/zlib1.dll',
'<(GTK_Root)/bin/libintl-8.dll',
'<(GTK_Root)/bin/libpng14-14.dll',
'<(GTK_Root)/bin/libpangocairo-1.0-0.dll',
'<(GTK_Root)/bin/libpango-1.0-0.dll',
'<(GTK_Root)/bin/libpangoft2-1.0-0.dll',
'<(GTK_Root)/bin/libpangowin32-1.0-0.dll',
'<(GTK_Root)/bin/libcairo-2.dll',
'<(GTK_Root)/bin/libfontconfig-1.dll',
'<(GTK_Root)/bin/libfreetype-6.dll',
'<(GTK_Root)/bin/libglib-2.0-0.dll',
'<(GTK_Root)/bin/libgobject-2.0-0.dll',
'<(GTK_Root)/bin/libgmodule-2.0-0.dll',
'<(GTK_Root)/bin/libgthread-2.0-0.dll',
'<(GTK_Root)/bin/libexpat-1.dll'
]
}]
}]
]
},
{
'target_name': 'canvas',
'include_dirs': ["<!(node -e \"require('nan')\")"],
'sources': [
'src/backend/Backend.cc',
'src/backend/ImageBackend.cc',
'src/backend/PdfBackend.cc',
'src/backend/SvgBackend.cc',
'src/bmp/BMPParser.cc',
'src/Backends.cc',
'src/Canvas.cc',
'src/CanvasGradient.cc',
'src/CanvasPattern.cc',
'src/CanvasRenderingContext2d.cc',
'src/closure.cc',
'src/color.cc',
'src/Image.cc',
'src/ImageData.cc',
'src/init.cc',
'src/register_font.cc'
],
'conditions': [
['OS=="win"', {
'libraries': [
'-l<(GTK_Root)/lib/cairo.lib',
'-l<(GTK_Root)/lib/libpng.lib',
'-l<(GTK_Root)/lib/pangocairo-1.0.lib',
'-l<(GTK_Root)/lib/pango-1.0.lib',
'-l<(GTK_Root)/lib/freetype.lib',
'-l<(GTK_Root)/lib/glib-2.0.lib',
'-l<(GTK_Root)/lib/gobject-2.0.lib'
],
'include_dirs': [
'<(GTK_Root)/include',
'<(GTK_Root)/include/cairo',
'<(GTK_Root)/include/pango-1.0',
'<(GTK_Root)/include/glib-2.0',
'<(GTK_Root)/include/freetype2',
'<(GTK_Root)/lib/glib-2.0/include'
],
'defines': [
'_USE_MATH_DEFINES', # for M_PI
'NOMINMAX' # allow std::min/max to work
],
'configurations': {
'Debug': {
'msvs_settings': {
'VCCLCompilerTool': {
'WarningLevel': 4,
'ExceptionHandling': 1,
'DisableSpecificWarnings': [
4100, 4611
]
}
}
},
'Release': {
'msvs_settings': {
'VCCLCompilerTool': {
'WarningLevel': 4,
'ExceptionHandling': 1,
'DisableSpecificWarnings': [
4100, 4611
]
}
}
}
}
}, { # 'OS!="win"'
'libraries': [
'<!@(pkg-config pixman-1 --libs)',
'<!@(pkg-config cairo --libs)',
'<!@(pkg-config libpng --libs)',
'<!@(pkg-config pangocairo --libs)',
'<!@(pkg-config freetype2 --libs)'
],
'include_dirs': [
'<!@(pkg-config cairo --cflags-only-I | sed s/-I//g)',
'<!@(pkg-config libpng --cflags-only-I | sed s/-I//g)',
'<!@(pkg-config pangocairo --cflags-only-I | sed s/-I//g)',
'<!@(pkg-config freetype2 --cflags-only-I | sed s/-I//g)'
],
'cflags': ['-Wno-cast-function-type'],
'cflags!': ['-fno-exceptions'],
'cflags_cc!': ['-fno-exceptions']
}],
['OS=="mac"', {
'xcode_settings': {
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES'
}
}],
['with_jpeg=="true"', {
'defines': [
'HAVE_JPEG'
],
'conditions': [
['OS=="win"', {
'copies': [{
'destination': '<(PRODUCT_DIR)',
'files': [
'<(jpeg_root)/bin/jpeg62.dll',
]
}],
'include_dirs': [
'<(jpeg_root)/include'
],
'libraries': [
'-l<(jpeg_root)/lib/jpeg.lib',
]
}, {
'include_dirs': [
'<!@(pkg-config libjpeg --cflags-only-I | sed s/-I//g)'
],
'libraries': [
'<!@(pkg-config libjpeg --libs)'
]
}]
]
}],
['with_gif=="true"', {
'defines': [
'HAVE_GIF'
],
'conditions': [
['OS=="win"', {
'libraries': [
'-l<(GTK_Root)/lib/gif.lib'
]
}, {
'include_dirs': [
'/opt/homebrew/include'
],
'libraries': [
'-L/opt/homebrew/lib',
'-lgif'
]
}]
]
}],
['with_rsvg=="true"', {
'defines': [
'HAVE_RSVG'
],
'conditions': [
['OS=="win"', {
'copies': [{
'destination': '<(PRODUCT_DIR)',
'files': [
'<(GTK_Root)/bin/librsvg-2-2.dll',
'<(GTK_Root)/bin/libgdk_pixbuf-2.0-0.dll',
'<(GTK_Root)/bin/libgio-2.0-0.dll',
'<(GTK_Root)/bin/libcroco-0.6-3.dll',
'<(GTK_Root)/bin/libgsf-1-114.dll',
'<(GTK_Root)/bin/libxml2-2.dll'
]
}],
'libraries': [
'-l<(GTK_Root)/lib/librsvg-2-2.lib'
]
}, {
'include_dirs': [
'<!@(pkg-config librsvg-2.0 --cflags-only-I | sed s/-I//g)'
],
'libraries': [
'<!@(pkg-config librsvg-2.0 --libs)'
]
}]
]
}]
]
}
]
}

35
ccc-tnt-psd2ui-v2.4.x/node_modules/canvas/browser.js generated vendored Normal file
View File

@@ -0,0 +1,35 @@
/* globals document, ImageData */
const parseFont = require('./lib/parse-font')
exports.parseFont = parseFont
exports.createCanvas = function (width, height) {
return Object.assign(document.createElement('canvas'), { width: width, height: height })
}
exports.createImageData = function (array, width, height) {
// Browser implementation of ImageData looks at the number of arguments passed
switch (arguments.length) {
case 0: return new ImageData()
case 1: return new ImageData(array)
case 2: return new ImageData(array, width)
default: return new ImageData(array, width, height)
}
}
exports.loadImage = function (src, options) {
return new Promise(function (resolve, reject) {
const image = Object.assign(document.createElement('img'), options)
function cleanup () {
image.onload = null
image.onerror = null
}
image.onload = function () { cleanup(); resolve(image) }
image.onerror = function () { cleanup(); reject(new Error('Failed to load the image "' + src + '"')) }
image.src = src
})
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<Project>
<ProjectOutputs>
<ProjectOutput>
<FullPath>D:\a\node-canvas\node-canvas\build\Release\canvas.node</FullPath>
</ProjectOutput>
</ProjectOutputs>
<ContentFiles />
<SatelliteDlls />
<NonRecipeFileRefs />
</Project>

View File

@@ -0,0 +1,2 @@
PlatformToolSet=v142:VCToolArchitecture=Native64Bit:VCToolsVersion=14.29.30133:VCServicingVersionMFC=14.29.30136:TargetPlatformVersion=10.0.20348.0:
Release|x64|D:\a\node-canvas\node-canvas\build\|

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

94
ccc-tnt-psd2ui-v2.4.x/node_modules/canvas/index.js generated vendored Normal file
View File

@@ -0,0 +1,94 @@
const Canvas = require('./lib/canvas')
const Image = require('./lib/image')
const CanvasRenderingContext2D = require('./lib/context2d')
const CanvasPattern = require('./lib/pattern')
const parseFont = require('./lib/parse-font')
const packageJson = require('./package.json')
const bindings = require('./lib/bindings')
const fs = require('fs')
const PNGStream = require('./lib/pngstream')
const PDFStream = require('./lib/pdfstream')
const JPEGStream = require('./lib/jpegstream')
const { DOMPoint, DOMMatrix } = require('./lib/DOMMatrix')
function createCanvas (width, height, type) {
return new Canvas(width, height, type)
}
function createImageData (array, width, height) {
return new bindings.ImageData(array, width, height)
}
function loadImage (src) {
return new Promise((resolve, reject) => {
const image = new Image()
function cleanup () {
image.onload = null
image.onerror = null
}
image.onload = () => { cleanup(); resolve(image) }
image.onerror = (err) => { cleanup(); reject(err) }
image.src = src
})
}
/**
* Resolve paths for registerFont. Must be called *before* creating a Canvas
* instance.
* @param src {string} Path to font file.
* @param fontFace {{family: string, weight?: string, style?: string}} Object
* specifying font information. `weight` and `style` default to `"normal"`.
*/
function registerFont (src, fontFace) {
// TODO this doesn't need to be on Canvas; it should just be a static method
// of `bindings`.
return Canvas._registerFont(fs.realpathSync(src), fontFace)
}
/**
* Unload all fonts from pango to free up memory
*/
function deregisterAllFonts () {
return Canvas._deregisterAllFonts()
}
exports.Canvas = Canvas
exports.Context2d = CanvasRenderingContext2D // Legacy/compat export
exports.CanvasRenderingContext2D = CanvasRenderingContext2D
exports.CanvasGradient = bindings.CanvasGradient
exports.CanvasPattern = CanvasPattern
exports.Image = Image
exports.ImageData = bindings.ImageData
exports.PNGStream = PNGStream
exports.PDFStream = PDFStream
exports.JPEGStream = JPEGStream
exports.DOMMatrix = DOMMatrix
exports.DOMPoint = DOMPoint
exports.registerFont = registerFont
exports.deregisterAllFonts = deregisterAllFonts
exports.parseFont = parseFont
exports.createCanvas = createCanvas
exports.createImageData = createImageData
exports.loadImage = loadImage
exports.backends = bindings.Backends
/** Library version. */
exports.version = packageJson.version
/** Cairo version. */
exports.cairoVersion = bindings.cairoVersion
/** jpeglib version. */
exports.jpegVersion = bindings.jpegVersion
/** gif_lib version. */
exports.gifVersion = bindings.gifVersion ? bindings.gifVersion.replace(/[^.\d]/g, '') : undefined
/** freetype version. */
exports.freetypeVersion = bindings.freetypeVersion
/** rsvg version. */
exports.rsvgVersion = bindings.rsvgVersion
/** pango version. */
exports.pangoVersion = bindings.pangoVersion

View File

@@ -0,0 +1,620 @@
'use strict'
const util = require('util')
// DOMMatrix per https://drafts.fxtf.org/geometry/#DOMMatrix
class DOMPoint {
constructor (x, y, z, w) {
if (typeof x === 'object' && x !== null) {
w = x.w
z = x.z
y = x.y
x = x.x
}
this.x = typeof x === 'number' ? x : 0
this.y = typeof y === 'number' ? y : 0
this.z = typeof z === 'number' ? z : 0
this.w = typeof w === 'number' ? w : 1
}
}
// Constants to index into _values (col-major)
const M11 = 0; const M12 = 1; const M13 = 2; const M14 = 3
const M21 = 4; const M22 = 5; const M23 = 6; const M24 = 7
const M31 = 8; const M32 = 9; const M33 = 10; const M34 = 11
const M41 = 12; const M42 = 13; const M43 = 14; const M44 = 15
const DEGREE_PER_RAD = 180 / Math.PI
const RAD_PER_DEGREE = Math.PI / 180
function parseMatrix (init) {
let parsed = init.replace('matrix(', '')
parsed = parsed.split(',', 7) // 6 + 1 to handle too many params
if (parsed.length !== 6) throw new Error(`Failed to parse ${init}`)
parsed = parsed.map(parseFloat)
return [
parsed[0], parsed[1], 0, 0,
parsed[2], parsed[3], 0, 0,
0, 0, 1, 0,
parsed[4], parsed[5], 0, 1
]
}
function parseMatrix3d (init) {
let parsed = init.replace('matrix3d(', '')
parsed = parsed.split(',', 17) // 16 + 1 to handle too many params
if (parsed.length !== 16) throw new Error(`Failed to parse ${init}`)
return parsed.map(parseFloat)
}
function parseTransform (tform) {
const type = tform.split('(', 1)[0]
switch (type) {
case 'matrix':
return parseMatrix(tform)
case 'matrix3d':
return parseMatrix3d(tform)
// TODO This is supposed to support any CSS transform value.
default:
throw new Error(`${type} parsing not implemented`)
}
}
class DOMMatrix {
constructor (init) {
this._is2D = true
this._values = new Float64Array([
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
])
let i
if (typeof init === 'string') { // parse CSS transformList
if (init === '') return // default identity matrix
const tforms = init.split(/\)\s+/, 20).map(parseTransform)
if (tforms.length === 0) return
init = tforms[0]
for (i = 1; i < tforms.length; i++) init = multiply(tforms[i], init)
}
i = 0
if (init && init.length === 6) {
setNumber2D(this, M11, init[i++])
setNumber2D(this, M12, init[i++])
setNumber2D(this, M21, init[i++])
setNumber2D(this, M22, init[i++])
setNumber2D(this, M41, init[i++])
setNumber2D(this, M42, init[i++])
} else if (init && init.length === 16) {
setNumber2D(this, M11, init[i++])
setNumber2D(this, M12, init[i++])
setNumber3D(this, M13, init[i++])
setNumber3D(this, M14, init[i++])
setNumber2D(this, M21, init[i++])
setNumber2D(this, M22, init[i++])
setNumber3D(this, M23, init[i++])
setNumber3D(this, M24, init[i++])
setNumber3D(this, M31, init[i++])
setNumber3D(this, M32, init[i++])
setNumber3D(this, M33, init[i++])
setNumber3D(this, M34, init[i++])
setNumber2D(this, M41, init[i++])
setNumber2D(this, M42, init[i++])
setNumber3D(this, M43, init[i++])
setNumber3D(this, M44, init[i])
} else if (init !== undefined) {
throw new TypeError('Expected string or array.')
}
}
toString () {
return this.is2D
? `matrix(${this.a}, ${this.b}, ${this.c}, ${this.d}, ${this.e}, ${this.f})`
: `matrix3d(${this._values.join(', ')})`
}
multiply (other) {
return newInstance(this._values).multiplySelf(other)
}
multiplySelf (other) {
this._values = multiply(other._values, this._values)
if (!other.is2D) this._is2D = false
return this
}
preMultiplySelf (other) {
this._values = multiply(this._values, other._values)
if (!other.is2D) this._is2D = false
return this
}
translate (tx, ty, tz) {
return newInstance(this._values).translateSelf(tx, ty, tz)
}
translateSelf (tx, ty, tz) {
if (typeof tx !== 'number') tx = 0
if (typeof ty !== 'number') ty = 0
if (typeof tz !== 'number') tz = 0
this._values = multiply([
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
tx, ty, tz, 1
], this._values)
if (tz !== 0) this._is2D = false
return this
}
scale (scaleX, scaleY, scaleZ, originX, originY, originZ) {
return newInstance(this._values).scaleSelf(scaleX, scaleY, scaleZ, originX, originY, originZ)
}
scale3d (scale, originX, originY, originZ) {
return newInstance(this._values).scale3dSelf(scale, originX, originY, originZ)
}
scale3dSelf (scale, originX, originY, originZ) {
return this.scaleSelf(scale, scale, scale, originX, originY, originZ)
}
scaleSelf (scaleX, scaleY, scaleZ, originX, originY, originZ) {
// Not redundant with translate's checks because we need to negate the values later.
if (typeof originX !== 'number') originX = 0
if (typeof originY !== 'number') originY = 0
if (typeof originZ !== 'number') originZ = 0
this.translateSelf(originX, originY, originZ)
if (typeof scaleX !== 'number') scaleX = 1
if (typeof scaleY !== 'number') scaleY = scaleX
if (typeof scaleZ !== 'number') scaleZ = 1
this._values = multiply([
scaleX, 0, 0, 0,
0, scaleY, 0, 0,
0, 0, scaleZ, 0,
0, 0, 0, 1
], this._values)
this.translateSelf(-originX, -originY, -originZ)
if (scaleZ !== 1 || originZ !== 0) this._is2D = false
return this
}
rotateFromVector (x, y) {
return newInstance(this._values).rotateFromVectorSelf(x, y)
}
rotateFromVectorSelf (x, y) {
if (typeof x !== 'number') x = 0
if (typeof y !== 'number') y = 0
const theta = (x === 0 && y === 0) ? 0 : Math.atan2(y, x) * DEGREE_PER_RAD
return this.rotateSelf(theta)
}
rotate (rotX, rotY, rotZ) {
return newInstance(this._values).rotateSelf(rotX, rotY, rotZ)
}
rotateSelf (rotX, rotY, rotZ) {
if (rotY === undefined && rotZ === undefined) {
rotZ = rotX
rotX = rotY = 0
}
if (typeof rotY !== 'number') rotY = 0
if (typeof rotZ !== 'number') rotZ = 0
if (rotX !== 0 || rotY !== 0) this._is2D = false
rotX *= RAD_PER_DEGREE
rotY *= RAD_PER_DEGREE
rotZ *= RAD_PER_DEGREE
let c, s
c = Math.cos(rotZ)
s = Math.sin(rotZ)
this._values = multiply([
c, s, 0, 0,
-s, c, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
], this._values)
c = Math.cos(rotY)
s = Math.sin(rotY)
this._values = multiply([
c, 0, -s, 0,
0, 1, 0, 0,
s, 0, c, 0,
0, 0, 0, 1
], this._values)
c = Math.cos(rotX)
s = Math.sin(rotX)
this._values = multiply([
1, 0, 0, 0,
0, c, s, 0,
0, -s, c, 0,
0, 0, 0, 1
], this._values)
return this
}
rotateAxisAngle (x, y, z, angle) {
return newInstance(this._values).rotateAxisAngleSelf(x, y, z, angle)
}
rotateAxisAngleSelf (x, y, z, angle) {
if (typeof x !== 'number') x = 0
if (typeof y !== 'number') y = 0
if (typeof z !== 'number') z = 0
// Normalize axis
const length = Math.sqrt(x * x + y * y + z * z)
if (length === 0) return this
if (length !== 1) {
x /= length
y /= length
z /= length
}
angle *= RAD_PER_DEGREE
const c = Math.cos(angle)
const s = Math.sin(angle)
const t = 1 - c
const tx = t * x
const ty = t * y
// NB: This is the generic transform. If the axis is a major axis, there are
// faster transforms.
this._values = multiply([
tx * x + c, tx * y + s * z, tx * z - s * y, 0,
tx * y - s * z, ty * y + c, ty * z + s * x, 0,
tx * z + s * y, ty * z - s * x, t * z * z + c, 0,
0, 0, 0, 1
], this._values)
if (x !== 0 || y !== 0) this._is2D = false
return this
}
skewX (sx) {
return newInstance(this._values).skewXSelf(sx)
}
skewXSelf (sx) {
if (typeof sx !== 'number') return this
const t = Math.tan(sx * RAD_PER_DEGREE)
this._values = multiply([
1, 0, 0, 0,
t, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
], this._values)
return this
}
skewY (sy) {
return newInstance(this._values).skewYSelf(sy)
}
skewYSelf (sy) {
if (typeof sy !== 'number') return this
const t = Math.tan(sy * RAD_PER_DEGREE)
this._values = multiply([
1, t, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
], this._values)
return this
}
flipX () {
return newInstance(multiply([
-1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
], this._values))
}
flipY () {
return newInstance(multiply([
1, 0, 0, 0,
0, -1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
], this._values))
}
inverse () {
return newInstance(this._values).invertSelf()
}
invertSelf () {
const m = this._values
const inv = m.map(v => 0)
inv[0] = m[5] * m[10] * m[15] -
m[5] * m[11] * m[14] -
m[9] * m[6] * m[15] +
m[9] * m[7] * m[14] +
m[13] * m[6] * m[11] -
m[13] * m[7] * m[10]
inv[4] = -m[4] * m[10] * m[15] +
m[4] * m[11] * m[14] +
m[8] * m[6] * m[15] -
m[8] * m[7] * m[14] -
m[12] * m[6] * m[11] +
m[12] * m[7] * m[10]
inv[8] = m[4] * m[9] * m[15] -
m[4] * m[11] * m[13] -
m[8] * m[5] * m[15] +
m[8] * m[7] * m[13] +
m[12] * m[5] * m[11] -
m[12] * m[7] * m[9]
inv[12] = -m[4] * m[9] * m[14] +
m[4] * m[10] * m[13] +
m[8] * m[5] * m[14] -
m[8] * m[6] * m[13] -
m[12] * m[5] * m[10] +
m[12] * m[6] * m[9]
// If the determinant is zero, this matrix cannot be inverted, and all
// values should be set to NaN, with the is2D flag set to false.
const det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12]
if (det === 0) {
this._values = m.map(v => NaN)
this._is2D = false
return this
}
inv[1] = -m[1] * m[10] * m[15] +
m[1] * m[11] * m[14] +
m[9] * m[2] * m[15] -
m[9] * m[3] * m[14] -
m[13] * m[2] * m[11] +
m[13] * m[3] * m[10]
inv[5] = m[0] * m[10] * m[15] -
m[0] * m[11] * m[14] -
m[8] * m[2] * m[15] +
m[8] * m[3] * m[14] +
m[12] * m[2] * m[11] -
m[12] * m[3] * m[10]
inv[9] = -m[0] * m[9] * m[15] +
m[0] * m[11] * m[13] +
m[8] * m[1] * m[15] -
m[8] * m[3] * m[13] -
m[12] * m[1] * m[11] +
m[12] * m[3] * m[9]
inv[13] = m[0] * m[9] * m[14] -
m[0] * m[10] * m[13] -
m[8] * m[1] * m[14] +
m[8] * m[2] * m[13] +
m[12] * m[1] * m[10] -
m[12] * m[2] * m[9]
inv[2] = m[1] * m[6] * m[15] -
m[1] * m[7] * m[14] -
m[5] * m[2] * m[15] +
m[5] * m[3] * m[14] +
m[13] * m[2] * m[7] -
m[13] * m[3] * m[6]
inv[6] = -m[0] * m[6] * m[15] +
m[0] * m[7] * m[14] +
m[4] * m[2] * m[15] -
m[4] * m[3] * m[14] -
m[12] * m[2] * m[7] +
m[12] * m[3] * m[6]
inv[10] = m[0] * m[5] * m[15] -
m[0] * m[7] * m[13] -
m[4] * m[1] * m[15] +
m[4] * m[3] * m[13] +
m[12] * m[1] * m[7] -
m[12] * m[3] * m[5]
inv[14] = -m[0] * m[5] * m[14] +
m[0] * m[6] * m[13] +
m[4] * m[1] * m[14] -
m[4] * m[2] * m[13] -
m[12] * m[1] * m[6] +
m[12] * m[2] * m[5]
inv[3] = -m[1] * m[6] * m[11] +
m[1] * m[7] * m[10] +
m[5] * m[2] * m[11] -
m[5] * m[3] * m[10] -
m[9] * m[2] * m[7] +
m[9] * m[3] * m[6]
inv[7] = m[0] * m[6] * m[11] -
m[0] * m[7] * m[10] -
m[4] * m[2] * m[11] +
m[4] * m[3] * m[10] +
m[8] * m[2] * m[7] -
m[8] * m[3] * m[6]
inv[11] = -m[0] * m[5] * m[11] +
m[0] * m[7] * m[9] +
m[4] * m[1] * m[11] -
m[4] * m[3] * m[9] -
m[8] * m[1] * m[7] +
m[8] * m[3] * m[5]
inv[15] = m[0] * m[5] * m[10] -
m[0] * m[6] * m[9] -
m[4] * m[1] * m[10] +
m[4] * m[2] * m[9] +
m[8] * m[1] * m[6] -
m[8] * m[2] * m[5]
inv.forEach((v, i) => { inv[i] = v / det })
this._values = inv
return this
}
setMatrixValue (transformList) {
const temp = new DOMMatrix(transformList)
this._values = temp._values
this._is2D = temp._is2D
return this
}
transformPoint (point) {
point = new DOMPoint(point)
const x = point.x
const y = point.y
const z = point.z
const w = point.w
const values = this._values
const nx = values[M11] * x + values[M21] * y + values[M31] * z + values[M41] * w
const ny = values[M12] * x + values[M22] * y + values[M32] * z + values[M42] * w
const nz = values[M13] * x + values[M23] * y + values[M33] * z + values[M43] * w
const nw = values[M14] * x + values[M24] * y + values[M34] * z + values[M44] * w
return new DOMPoint(nx, ny, nz, nw)
}
toFloat32Array () {
return Float32Array.from(this._values)
}
toFloat64Array () {
return this._values.slice(0)
}
static fromMatrix (init) {
if (!(init instanceof DOMMatrix)) throw new TypeError('Expected DOMMatrix')
return new DOMMatrix(init._values)
}
static fromFloat32Array (init) {
if (!(init instanceof Float32Array)) throw new TypeError('Expected Float32Array')
return new DOMMatrix(init)
}
static fromFloat64Array (init) {
if (!(init instanceof Float64Array)) throw new TypeError('Expected Float64Array')
return new DOMMatrix(init)
}
[util.inspect.custom || 'inspect'] (depth, options) {
if (depth < 0) return '[DOMMatrix]'
return `DOMMatrix [
a: ${this.a}
b: ${this.b}
c: ${this.c}
d: ${this.d}
e: ${this.e}
f: ${this.f}
m11: ${this.m11}
m12: ${this.m12}
m13: ${this.m13}
m14: ${this.m14}
m21: ${this.m21}
m22: ${this.m22}
m23: ${this.m23}
m23: ${this.m23}
m31: ${this.m31}
m32: ${this.m32}
m33: ${this.m33}
m34: ${this.m34}
m41: ${this.m41}
m42: ${this.m42}
m43: ${this.m43}
m44: ${this.m44}
is2D: ${this.is2D}
isIdentity: ${this.isIdentity} ]`
}
}
/**
* Checks that `value` is a number and sets the value.
*/
function setNumber2D (receiver, index, value) {
if (typeof value !== 'number') throw new TypeError('Expected number')
return (receiver._values[index] = value)
}
/**
* Checks that `value` is a number, sets `_is2D = false` if necessary and sets
* the value.
*/
function setNumber3D (receiver, index, value) {
if (typeof value !== 'number') throw new TypeError('Expected number')
if (index === M33 || index === M44) {
if (value !== 1) receiver._is2D = false
} else if (value !== 0) receiver._is2D = false
return (receiver._values[index] = value)
}
Object.defineProperties(DOMMatrix.prototype, {
m11: { get () { return this._values[M11] }, set (v) { return setNumber2D(this, M11, v) } },
m12: { get () { return this._values[M12] }, set (v) { return setNumber2D(this, M12, v) } },
m13: { get () { return this._values[M13] }, set (v) { return setNumber3D(this, M13, v) } },
m14: { get () { return this._values[M14] }, set (v) { return setNumber3D(this, M14, v) } },
m21: { get () { return this._values[M21] }, set (v) { return setNumber2D(this, M21, v) } },
m22: { get () { return this._values[M22] }, set (v) { return setNumber2D(this, M22, v) } },
m23: { get () { return this._values[M23] }, set (v) { return setNumber3D(this, M23, v) } },
m24: { get () { return this._values[M24] }, set (v) { return setNumber3D(this, M24, v) } },
m31: { get () { return this._values[M31] }, set (v) { return setNumber3D(this, M31, v) } },
m32: { get () { return this._values[M32] }, set (v) { return setNumber3D(this, M32, v) } },
m33: { get () { return this._values[M33] }, set (v) { return setNumber3D(this, M33, v) } },
m34: { get () { return this._values[M34] }, set (v) { return setNumber3D(this, M34, v) } },
m41: { get () { return this._values[M41] }, set (v) { return setNumber2D(this, M41, v) } },
m42: { get () { return this._values[M42] }, set (v) { return setNumber2D(this, M42, v) } },
m43: { get () { return this._values[M43] }, set (v) { return setNumber3D(this, M43, v) } },
m44: { get () { return this._values[M44] }, set (v) { return setNumber3D(this, M44, v) } },
a: { get () { return this.m11 }, set (v) { return (this.m11 = v) } },
b: { get () { return this.m12 }, set (v) { return (this.m12 = v) } },
c: { get () { return this.m21 }, set (v) { return (this.m21 = v) } },
d: { get () { return this.m22 }, set (v) { return (this.m22 = v) } },
e: { get () { return this.m41 }, set (v) { return (this.m41 = v) } },
f: { get () { return this.m42 }, set (v) { return (this.m42 = v) } },
is2D: { get () { return this._is2D } }, // read-only
isIdentity: {
get () {
const values = this._values
return (values[M11] === 1 && values[M12] === 0 && values[M13] === 0 && values[M14] === 0 &&
values[M21] === 0 && values[M22] === 1 && values[M23] === 0 && values[M24] === 0 &&
values[M31] === 0 && values[M32] === 0 && values[M33] === 1 && values[M34] === 0 &&
values[M41] === 0 && values[M42] === 0 && values[M43] === 0 && values[M44] === 1)
}
}
})
/**
* Instantiates a DOMMatrix, bypassing the constructor.
* @param {Float64Array} values Value to assign to `_values`. This is assigned
* without copying (okay because all usages are followed by a multiply).
*/
function newInstance (values) {
const instance = Object.create(DOMMatrix.prototype)
instance.constructor = DOMMatrix
instance._is2D = true
instance._values = values
return instance
}
function multiply (A, B) {
const dest = new Float64Array(16)
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
let sum = 0
for (let k = 0; k < 4; k++) {
sum += A[i * 4 + k] * B[k * 4 + j]
}
dest[i * 4 + j] = sum
}
}
return dest
}
module.exports = { DOMMatrix, DOMPoint }

View File

@@ -0,0 +1,13 @@
'use strict'
const bindings = require('../build/Release/canvas.node')
module.exports = bindings
bindings.ImageData.prototype.toString = function () {
return '[object ImageData]'
}
bindings.CanvasGradient.prototype.toString = function () {
return '[object CanvasGradient]'
}

113
ccc-tnt-psd2ui-v2.4.x/node_modules/canvas/lib/canvas.js generated vendored Normal file
View File

@@ -0,0 +1,113 @@
'use strict'
/*!
* Canvas
* Copyright (c) 2010 LearnBoost <tj@learnboost.com>
* MIT Licensed
*/
const bindings = require('./bindings')
const Canvas = module.exports = bindings.Canvas
const Context2d = require('./context2d')
const PNGStream = require('./pngstream')
const PDFStream = require('./pdfstream')
const JPEGStream = require('./jpegstream')
const FORMATS = ['image/png', 'image/jpeg']
const util = require('util')
// TODO || is for Node.js pre-v6.6.0
Canvas.prototype[util.inspect.custom || 'inspect'] = function () {
return `[Canvas ${this.width}x${this.height}]`
}
Canvas.prototype.getContext = function (contextType, contextAttributes) {
if (contextType == '2d') {
const ctx = this._context2d || (this._context2d = new Context2d(this, contextAttributes))
this.context = ctx
ctx.canvas = this
return ctx
}
}
Canvas.prototype.pngStream =
Canvas.prototype.createPNGStream = function (options) {
return new PNGStream(this, options)
}
Canvas.prototype.pdfStream =
Canvas.prototype.createPDFStream = function (options) {
return new PDFStream(this, options)
}
Canvas.prototype.jpegStream =
Canvas.prototype.createJPEGStream = function (options) {
return new JPEGStream(this, options)
}
Canvas.prototype.toDataURL = function (a1, a2, a3) {
// valid arg patterns (args -> [type, opts, fn]):
// [] -> ['image/png', null, null]
// [qual] -> ['image/png', null, null]
// [undefined] -> ['image/png', null, null]
// ['image/png'] -> ['image/png', null, null]
// ['image/png', qual] -> ['image/png', null, null]
// [fn] -> ['image/png', null, fn]
// [type, fn] -> [type, null, fn]
// [undefined, fn] -> ['image/png', null, fn]
// ['image/png', qual, fn] -> ['image/png', null, fn]
// ['image/jpeg', fn] -> ['image/jpeg', null, fn]
// ['image/jpeg', opts, fn] -> ['image/jpeg', opts, fn]
// ['image/jpeg', qual, fn] -> ['image/jpeg', {quality: qual}, fn]
// ['image/jpeg', undefined, fn] -> ['image/jpeg', null, fn]
// ['image/jpeg'] -> ['image/jpeg', null, fn]
// ['image/jpeg', opts] -> ['image/jpeg', opts, fn]
// ['image/jpeg', qual] -> ['image/jpeg', {quality: qual}, fn]
let type = 'image/png'
let opts = {}
let fn
if (typeof a1 === 'function') {
fn = a1
} else {
if (typeof a1 === 'string' && FORMATS.includes(a1.toLowerCase())) {
type = a1.toLowerCase()
}
if (typeof a2 === 'function') {
fn = a2
} else {
if (typeof a2 === 'object') {
opts = a2
} else if (typeof a2 === 'number') {
opts = { quality: Math.max(0, Math.min(1, a2)) }
}
if (typeof a3 === 'function') {
fn = a3
} else if (undefined !== a3) {
throw new TypeError(`${typeof a3} is not a function`)
}
}
}
if (this.width === 0 || this.height === 0) {
// Per spec, if the bitmap has no pixels, return this string:
const str = 'data:,'
if (fn) {
setTimeout(() => fn(null, str))
return
} else {
return str
}
}
if (fn) {
this.toBuffer((err, buf) => {
if (err) return fn(err)
fn(null, `data:${type};base64,${buf.toString('base64')}`)
}, type, opts)
} else {
return `data:${type};base64,${this.toBuffer(type, opts).toString('base64')}`
}
}

View File

@@ -0,0 +1,14 @@
'use strict'
/*!
* Canvas - Context2d
* Copyright (c) 2010 LearnBoost <tj@learnboost.com>
* MIT Licensed
*/
const bindings = require('./bindings')
const parseFont = require('./parse-font')
const { DOMMatrix } = require('./DOMMatrix')
bindings.CanvasRenderingContext2dInit(DOMMatrix, parseFont)
module.exports = bindings.CanvasRenderingContext2d

96
ccc-tnt-psd2ui-v2.4.x/node_modules/canvas/lib/image.js generated vendored Normal file
View File

@@ -0,0 +1,96 @@
'use strict'
/*!
* Canvas - Image
* Copyright (c) 2010 LearnBoost <tj@learnboost.com>
* MIT Licensed
*/
/**
* Module dependencies.
*/
const bindings = require('./bindings')
const Image = module.exports = bindings.Image
const util = require('util')
// Lazily loaded simple-get
let get
const { GetSource, SetSource } = bindings
Object.defineProperty(Image.prototype, 'src', {
/**
* src setter. Valid values:
* * `data:` URI
* * Local file path
* * HTTP or HTTPS URL
* * Buffer containing image data (i.e. not a `data:` URI stored in a Buffer)
*
* @param {String|Buffer} val filename, buffer, data URI, URL
* @api public
*/
set (val) {
if (typeof val === 'string') {
if (/^\s*data:/.test(val)) { // data: URI
const commaI = val.indexOf(',')
// 'base64' must come before the comma
const isBase64 = val.lastIndexOf('base64', commaI) !== -1
const content = val.slice(commaI + 1)
setSource(this, Buffer.from(content, isBase64 ? 'base64' : 'utf8'), val)
} else if (/^\s*https?:\/\//.test(val)) { // remote URL
const onerror = err => {
if (typeof this.onerror === 'function') {
this.onerror(err)
} else {
throw err
}
}
if (!get) get = require('simple-get')
get.concat({
url: val,
headers: { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36' }
}, (err, res, data) => {
if (err) return onerror(err)
if (res.statusCode < 200 || res.statusCode >= 300) {
return onerror(new Error(`Server responded with ${res.statusCode}`))
}
setSource(this, data)
})
} else { // local file path assumed
setSource(this, val)
}
} else if (Buffer.isBuffer(val)) {
setSource(this, val)
}
},
get () {
// TODO https://github.com/Automattic/node-canvas/issues/118
return getSource(this)
},
configurable: true
})
// TODO || is for Node.js pre-v6.6.0
Image.prototype[util.inspect.custom || 'inspect'] = function () {
return '[Image' +
(this.complete ? ':' + this.width + 'x' + this.height : '') +
(this.src ? ' ' + this.src : '') +
(this.complete ? ' complete' : '') +
']'
}
function getSource (img) {
return img._originalSource || GetSource.call(img)
}
function setSource (img, src, origSrc) {
SetSource.call(img, src)
img._originalSource = origSrc
}

View File

@@ -0,0 +1,41 @@
'use strict'
/*!
* Canvas - JPEGStream
* Copyright (c) 2010 LearnBoost <tj@learnboost.com>
* MIT Licensed
*/
const { Readable } = require('stream')
function noop () {}
class JPEGStream extends Readable {
constructor (canvas, options) {
super()
if (canvas.streamJPEGSync === undefined) {
throw new Error('node-canvas was built without JPEG support.')
}
this.options = options
this.canvas = canvas
}
_read () {
// For now we're not controlling the c++ code's data emission, so we only
// call canvas.streamJPEGSync once and let it emit data at will.
this._read = noop
this.canvas.streamJPEGSync(this.options, (err, chunk) => {
if (err) {
this.emit('error', err)
} else if (chunk) {
this.push(chunk)
} else {
this.push(null)
}
})
}
};
module.exports = JPEGStream

View File

@@ -0,0 +1,101 @@
'use strict'
/**
* Font RegExp helpers.
*/
const weights = 'bold|bolder|lighter|[1-9]00'
const styles = 'italic|oblique'
const variants = 'small-caps'
const stretches = 'ultra-condensed|extra-condensed|condensed|semi-condensed|semi-expanded|expanded|extra-expanded|ultra-expanded'
const units = 'px|pt|pc|in|cm|mm|%|em|ex|ch|rem|q'
const string = '\'([^\']+)\'|"([^"]+)"|[\\w\\s-]+'
// [ [ <font-style> || <font-variant-css21> || <font-weight> || <font-stretch> ]?
// <font-size> [ / <line-height> ]? <font-family> ]
// https://drafts.csswg.org/css-fonts-3/#font-prop
const weightRe = new RegExp(`(${weights}) +`, 'i')
const styleRe = new RegExp(`(${styles}) +`, 'i')
const variantRe = new RegExp(`(${variants}) +`, 'i')
const stretchRe = new RegExp(`(${stretches}) +`, 'i')
const sizeFamilyRe = new RegExp(
`([\\d\\.]+)(${units}) *((?:${string})( *, *(?:${string}))*)`)
/**
* Cache font parsing.
*/
const cache = {}
const defaultHeight = 16 // pt, common browser default
/**
* Parse font `str`.
*
* @param {String} str
* @return {Object} Parsed font. `size` is in device units. `unit` is the unit
* appearing in the input string.
* @api private
*/
module.exports = str => {
// Cached
if (cache[str]) return cache[str]
// Try for required properties first.
const sizeFamily = sizeFamilyRe.exec(str)
if (!sizeFamily) return // invalid
// Default values and required properties
const font = {
weight: 'normal',
style: 'normal',
stretch: 'normal',
variant: 'normal',
size: parseFloat(sizeFamily[1]),
unit: sizeFamily[2],
family: sizeFamily[3].replace(/["']/g, '').replace(/ *, */g, ',')
}
// Optional, unordered properties.
let weight, style, variant, stretch
// Stop search at `sizeFamily.index`
const substr = str.substring(0, sizeFamily.index)
if ((weight = weightRe.exec(substr))) font.weight = weight[1]
if ((style = styleRe.exec(substr))) font.style = style[1]
if ((variant = variantRe.exec(substr))) font.variant = variant[1]
if ((stretch = stretchRe.exec(substr))) font.stretch = stretch[1]
// Convert to device units. (`font.unit` is the original unit)
// TODO: ch, ex
switch (font.unit) {
case 'pt':
font.size /= 0.75
break
case 'pc':
font.size *= 16
break
case 'in':
font.size *= 96
break
case 'cm':
font.size *= 96.0 / 2.54
break
case 'mm':
font.size *= 96.0 / 25.4
break
case '%':
// TODO disabled because existing unit tests assume 100
// font.size *= defaultHeight / 100 / 0.75
break
case 'em':
case 'rem':
font.size *= defaultHeight / 0.75
break
case 'q':
font.size *= 96 / 25.4 / 4
break
}
return (cache[str] = font)
}

View File

@@ -0,0 +1,17 @@
'use strict'
/*!
* Canvas - CanvasPattern
* Copyright (c) 2010 LearnBoost <tj@learnboost.com>
* MIT Licensed
*/
const bindings = require('./bindings')
const { DOMMatrix } = require('./DOMMatrix')
bindings.CanvasPatternInit(DOMMatrix)
module.exports = bindings.CanvasPattern
bindings.CanvasPattern.prototype.toString = function () {
return '[object CanvasPattern]'
}

View File

@@ -0,0 +1,35 @@
'use strict'
/*!
* Canvas - PDFStream
*/
const { Readable } = require('stream')
function noop () {}
class PDFStream extends Readable {
constructor (canvas, options) {
super()
this.canvas = canvas
this.options = options
}
_read () {
// For now we're not controlling the c++ code's data emission, so we only
// call canvas.streamPDFSync once and let it emit data at will.
this._read = noop
this.canvas.streamPDFSync((err, chunk, len) => {
if (err) {
this.emit('error', err)
} else if (len) {
this.push(chunk)
} else {
this.push(null)
}
}, this.options)
}
}
module.exports = PDFStream

View File

@@ -0,0 +1,42 @@
'use strict'
/*!
* Canvas - PNGStream
* Copyright (c) 2010 LearnBoost <tj@learnboost.com>
* MIT Licensed
*/
const { Readable } = require('stream')
function noop () {}
class PNGStream extends Readable {
constructor (canvas, options) {
super()
if (options &&
options.palette instanceof Uint8ClampedArray &&
options.palette.length % 4 !== 0) {
throw new Error('Palette length must be a multiple of 4.')
}
this.canvas = canvas
this.options = options || {}
}
_read () {
// For now we're not controlling the c++ code's data emission, so we only
// call canvas.streamPNGSync once and let it emit data at will.
this._read = noop
this.canvas.streamPNGSync((err, chunk, len) => {
if (err) {
this.emit('error', err)
} else if (len) {
this.push(chunk)
} else {
this.push(null)
}
}, this.options)
}
}
module.exports = PNGStream

72
ccc-tnt-psd2ui-v2.4.x/node_modules/canvas/package.json generated vendored Normal file
View File

@@ -0,0 +1,72 @@
{
"name": "canvas",
"description": "Canvas graphics API backed by Cairo",
"version": "2.10.2",
"author": "TJ Holowaychuk <tj@learnboost.com>",
"main": "index.js",
"browser": "browser.js",
"contributors": [
"Nathan Rajlich <nathan@tootallnate.net>",
"Rod Vagg <r@va.gg>",
"Juriy Zaytsev <kangax@gmail.com>"
],
"keywords": [
"canvas",
"graphic",
"graphics",
"pixman",
"cairo",
"image",
"images",
"pdf"
],
"homepage": "https://github.com/Automattic/node-canvas",
"repository": "git://github.com/Automattic/node-canvas.git",
"scripts": {
"prebenchmark": "node-gyp build",
"benchmark": "node benchmarks/run.js",
"lint": "standard examples/*.js test/server.js test/public/*.js benchmarks/run.js lib/context2d.js util/has_lib.js browser.js index.js",
"test": "mocha test/*.test.js",
"pretest-server": "node-gyp build",
"test-server": "node test/server.js",
"generate-wpt": "node ./test/wpt/generate.js",
"test-wpt": "mocha test/wpt/generated/*.js",
"install": "node-pre-gyp install --fallback-to-build --update-binary",
"dtslint": "dtslint types"
},
"binary": {
"module_name": "canvas",
"module_path": "build/Release",
"host": "https://github.com/Automattic/node-canvas/releases/download/",
"remote_path": "v{version}",
"package_name": "{module_name}-v{version}-{node_abi}-{platform}-{libc}-{arch}.tar.gz"
},
"files": [
"binding.gyp",
"lib/",
"src/",
"util/",
"types/index.d.ts"
],
"types": "types/index.d.ts",
"dependencies": {
"@mapbox/node-pre-gyp": "^1.0.0",
"nan": "^2.17.0",
"simple-get": "^3.0.3"
},
"devDependencies": {
"@types/node": "^10.12.18",
"assert-rejects": "^1.0.0",
"dtslint": "^4.0.7",
"express": "^4.16.3",
"js-yaml": "^4.1.0",
"mocha": "^5.2.0",
"pixelmatch": "^4.0.2",
"standard": "^12.0.1",
"typescript": "^4.2.2"
},
"engines": {
"node": ">=6"
},
"license": "MIT"
}

View File

@@ -0,0 +1,18 @@
#include "Backends.h"
#include "backend/ImageBackend.h"
#include "backend/PdfBackend.h"
#include "backend/SvgBackend.h"
using namespace v8;
void Backends::Initialize(Local<Object> target) {
Nan::HandleScope scope;
Local<Object> obj = Nan::New<Object>();
ImageBackend::Initialize(obj);
PdfBackend::Initialize(obj);
SvgBackend::Initialize(obj);
Nan::Set(target, Nan::New<String>("Backends").ToLocalChecked(), obj).Check();
}

View File

@@ -0,0 +1,10 @@
#pragma once
#include "backend/Backend.h"
#include <nan.h>
#include <v8.h>
class Backends : public Nan::ObjectWrap {
public:
static void Initialize(v8::Local<v8::Object> target);
};

965
ccc-tnt-psd2ui-v2.4.x/node_modules/canvas/src/Canvas.cc generated vendored Normal file
View File

@@ -0,0 +1,965 @@
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
#include "Canvas.h"
#include <algorithm> // std::min
#include <assert.h>
#include <cairo-pdf.h>
#include <cairo-svg.h>
#include "CanvasRenderingContext2d.h"
#include "closure.h"
#include <cstring>
#include <cctype>
#include <ctime>
#include <glib.h>
#include "PNG.h"
#include "register_font.h"
#include <sstream>
#include <stdlib.h>
#include <string>
#include <unordered_set>
#include "Util.h"
#include <vector>
#include "node_buffer.h"
#ifdef HAVE_JPEG
#include "JPEGStream.h"
#endif
#include "backend/ImageBackend.h"
#include "backend/PdfBackend.h"
#include "backend/SvgBackend.h"
#define GENERIC_FACE_ERROR \
"The second argument to registerFont is required, and should be an object " \
"with at least a family (string) and optionally weight (string/number) " \
"and style (string)."
#define CHECK_RECEIVER(prop) \
if (!Canvas::constructor.Get(info.GetIsolate())->HasInstance(info.This())) { \
Nan::ThrowTypeError("Method " #prop " called on incompatible receiver"); \
return; \
}
using namespace v8;
using namespace std;
Nan::Persistent<FunctionTemplate> Canvas::constructor;
std::vector<FontFace> font_face_list;
/*
* Initialize Canvas.
*/
void
Canvas::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {
Nan::HandleScope scope;
// Constructor
Local<FunctionTemplate> ctor = Nan::New<FunctionTemplate>(Canvas::New);
constructor.Reset(ctor);
ctor->InstanceTemplate()->SetInternalFieldCount(1);
ctor->SetClassName(Nan::New("Canvas").ToLocalChecked());
// Prototype
Local<ObjectTemplate> proto = ctor->PrototypeTemplate();
Nan::SetPrototypeMethod(ctor, "toBuffer", ToBuffer);
Nan::SetPrototypeMethod(ctor, "streamPNGSync", StreamPNGSync);
Nan::SetPrototypeMethod(ctor, "streamPDFSync", StreamPDFSync);
#ifdef HAVE_JPEG
Nan::SetPrototypeMethod(ctor, "streamJPEGSync", StreamJPEGSync);
#endif
Nan::SetAccessor(proto, Nan::New("type").ToLocalChecked(), GetType);
Nan::SetAccessor(proto, Nan::New("stride").ToLocalChecked(), GetStride);
Nan::SetAccessor(proto, Nan::New("width").ToLocalChecked(), GetWidth, SetWidth);
Nan::SetAccessor(proto, Nan::New("height").ToLocalChecked(), GetHeight, SetHeight);
Nan::SetTemplate(proto, "PNG_NO_FILTERS", Nan::New<Uint32>(PNG_NO_FILTERS));
Nan::SetTemplate(proto, "PNG_FILTER_NONE", Nan::New<Uint32>(PNG_FILTER_NONE));
Nan::SetTemplate(proto, "PNG_FILTER_SUB", Nan::New<Uint32>(PNG_FILTER_SUB));
Nan::SetTemplate(proto, "PNG_FILTER_UP", Nan::New<Uint32>(PNG_FILTER_UP));
Nan::SetTemplate(proto, "PNG_FILTER_AVG", Nan::New<Uint32>(PNG_FILTER_AVG));
Nan::SetTemplate(proto, "PNG_FILTER_PAETH", Nan::New<Uint32>(PNG_FILTER_PAETH));
Nan::SetTemplate(proto, "PNG_ALL_FILTERS", Nan::New<Uint32>(PNG_ALL_FILTERS));
// Class methods
Nan::SetMethod(ctor, "_registerFont", RegisterFont);
Nan::SetMethod(ctor, "_deregisterAllFonts", DeregisterAllFonts);
Local<Context> ctx = Nan::GetCurrentContext();
Nan::Set(target,
Nan::New("Canvas").ToLocalChecked(),
ctor->GetFunction(ctx).ToLocalChecked());
}
/*
* Initialize a Canvas with the given width and height.
*/
NAN_METHOD(Canvas::New) {
if (!info.IsConstructCall()) {
return Nan::ThrowTypeError("Class constructors cannot be invoked without 'new'");
}
Backend* backend = NULL;
if (info[0]->IsNumber()) {
int width = Nan::To<uint32_t>(info[0]).FromMaybe(0), height = 0;
if (info[1]->IsNumber()) height = Nan::To<uint32_t>(info[1]).FromMaybe(0);
if (info[2]->IsString()) {
if (0 == strcmp("pdf", *Nan::Utf8String(info[2])))
backend = new PdfBackend(width, height);
else if (0 == strcmp("svg", *Nan::Utf8String(info[2])))
backend = new SvgBackend(width, height);
else
backend = new ImageBackend(width, height);
}
else
backend = new ImageBackend(width, height);
}
else if (info[0]->IsObject()) {
if (Nan::New(ImageBackend::constructor)->HasInstance(info[0]) ||
Nan::New(PdfBackend::constructor)->HasInstance(info[0]) ||
Nan::New(SvgBackend::constructor)->HasInstance(info[0])) {
backend = Nan::ObjectWrap::Unwrap<Backend>(Nan::To<Object>(info[0]).ToLocalChecked());
}else{
return Nan::ThrowTypeError("Invalid arguments");
}
}
else {
backend = new ImageBackend(0, 0);
}
if (!backend->isSurfaceValid()) {
delete backend;
return Nan::ThrowError(backend->getError());
}
Canvas* canvas = new Canvas(backend);
canvas->Wrap(info.This());
backend->setCanvas(canvas);
info.GetReturnValue().Set(info.This());
}
/*
* Get type string.
*/
NAN_GETTER(Canvas::GetType) {
CHECK_RECEIVER(Canvas.GetType);
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.This());
info.GetReturnValue().Set(Nan::New<String>(canvas->backend()->getName()).ToLocalChecked());
}
/*
* Get stride.
*/
NAN_GETTER(Canvas::GetStride) {
CHECK_RECEIVER(Canvas.GetStride);
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.This());
info.GetReturnValue().Set(Nan::New<Number>(canvas->stride()));
}
/*
* Get width.
*/
NAN_GETTER(Canvas::GetWidth) {
CHECK_RECEIVER(Canvas.GetWidth);
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.This());
info.GetReturnValue().Set(Nan::New<Number>(canvas->getWidth()));
}
/*
* Set width.
*/
NAN_SETTER(Canvas::SetWidth) {
CHECK_RECEIVER(Canvas.SetWidth);
if (value->IsNumber()) {
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.This());
canvas->backend()->setWidth(Nan::To<uint32_t>(value).FromMaybe(0));
canvas->resurface(info.This());
}
}
/*
* Get height.
*/
NAN_GETTER(Canvas::GetHeight) {
CHECK_RECEIVER(Canvas.GetHeight);
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.This());
info.GetReturnValue().Set(Nan::New<Number>(canvas->getHeight()));
}
/*
* Set height.
*/
NAN_SETTER(Canvas::SetHeight) {
CHECK_RECEIVER(Canvas.SetHeight);
if (value->IsNumber()) {
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.This());
canvas->backend()->setHeight(Nan::To<uint32_t>(value).FromMaybe(0));
canvas->resurface(info.This());
}
}
/*
* EIO toBuffer callback.
*/
void
Canvas::ToPngBufferAsync(uv_work_t *req) {
PngClosure* closure = static_cast<PngClosure*>(req->data);
closure->status = canvas_write_to_png_stream(
closure->canvas->surface(),
PngClosure::writeVec,
closure);
}
#ifdef HAVE_JPEG
void
Canvas::ToJpegBufferAsync(uv_work_t *req) {
JpegClosure* closure = static_cast<JpegClosure*>(req->data);
write_to_jpeg_buffer(closure->canvas->surface(), closure);
}
#endif
/*
* EIO after toBuffer callback.
*/
void
Canvas::ToBufferAsyncAfter(uv_work_t *req) {
Nan::HandleScope scope;
Nan::AsyncResource async("canvas:ToBufferAsyncAfter");
Closure* closure = static_cast<Closure*>(req->data);
delete req;
if (closure->status) {
Local<Value> argv[1] = { Canvas::Error(closure->status) };
closure->cb.Call(1, argv, &async);
} else {
Local<Object> buf = Nan::CopyBuffer((char*)&closure->vec[0], closure->vec.size()).ToLocalChecked();
Local<Value> argv[2] = { Nan::Null(), buf };
closure->cb.Call(sizeof argv / sizeof *argv, argv, &async);
}
closure->canvas->Unref();
delete closure;
}
static void parsePNGArgs(Local<Value> arg, PngClosure& pngargs) {
if (arg->IsObject()) {
Local<Object> obj = Nan::To<Object>(arg).ToLocalChecked();
Local<Value> cLevel = Nan::Get(obj, Nan::New("compressionLevel").ToLocalChecked()).ToLocalChecked();
if (cLevel->IsUint32()) {
uint32_t val = Nan::To<uint32_t>(cLevel).FromMaybe(0);
// See quote below from spec section 4.12.5.5.
if (val <= 9) pngargs.compressionLevel = val;
}
Local<Value> rez = Nan::Get(obj, Nan::New("resolution").ToLocalChecked()).ToLocalChecked();
if (rez->IsUint32()) {
uint32_t val = Nan::To<uint32_t>(rez).FromMaybe(0);
if (val > 0) pngargs.resolution = val;
}
Local<Value> filters = Nan::Get(obj, Nan::New("filters").ToLocalChecked()).ToLocalChecked();
if (filters->IsUint32()) pngargs.filters = Nan::To<uint32_t>(filters).FromMaybe(0);
Local<Value> palette = Nan::Get(obj, Nan::New("palette").ToLocalChecked()).ToLocalChecked();
if (palette->IsUint8ClampedArray()) {
Local<Uint8ClampedArray> palette_ta = palette.As<Uint8ClampedArray>();
pngargs.nPaletteColors = palette_ta->Length();
if (pngargs.nPaletteColors % 4 != 0) {
throw "Palette length must be a multiple of 4.";
}
pngargs.nPaletteColors /= 4;
Nan::TypedArrayContents<uint8_t> _paletteColors(palette_ta);
pngargs.palette = *_paletteColors;
// Optional background color index:
Local<Value> backgroundIndexVal = Nan::Get(obj, Nan::New("backgroundIndex").ToLocalChecked()).ToLocalChecked();
if (backgroundIndexVal->IsUint32()) {
pngargs.backgroundIndex = static_cast<uint8_t>(Nan::To<uint32_t>(backgroundIndexVal).FromMaybe(0));
}
}
}
}
#ifdef HAVE_JPEG
static void parseJPEGArgs(Local<Value> arg, JpegClosure& jpegargs) {
// "If Type(quality) is not Number, or if quality is outside that range, the
// user agent must use its default quality value, as if the quality argument
// had not been given." - 4.12.5.5
if (arg->IsObject()) {
Local<Object> obj = Nan::To<Object>(arg).ToLocalChecked();
Local<Value> qual = Nan::Get(obj, Nan::New("quality").ToLocalChecked()).ToLocalChecked();
if (qual->IsNumber()) {
double quality = Nan::To<double>(qual).FromMaybe(0);
if (quality >= 0.0 && quality <= 1.0) {
jpegargs.quality = static_cast<uint32_t>(100.0 * quality);
}
}
Local<Value> chroma = Nan::Get(obj, Nan::New("chromaSubsampling").ToLocalChecked()).ToLocalChecked();
if (chroma->IsBoolean()) {
bool subsample = Nan::To<bool>(chroma).FromMaybe(0);
jpegargs.chromaSubsampling = subsample ? 2 : 1;
} else if (chroma->IsNumber()) {
jpegargs.chromaSubsampling = Nan::To<uint32_t>(chroma).FromMaybe(0);
}
Local<Value> progressive = Nan::Get(obj, Nan::New("progressive").ToLocalChecked()).ToLocalChecked();
if (!progressive->IsUndefined()) {
jpegargs.progressive = Nan::To<bool>(progressive).FromMaybe(0);
}
}
}
#endif
#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 16, 0)
static inline void setPdfMetaStr(cairo_surface_t* surf, Local<Object> opts,
cairo_pdf_metadata_t t, const char* pName) {
auto propName = Nan::New(pName).ToLocalChecked();
auto propValue = Nan::Get(opts, propName).ToLocalChecked();
if (propValue->IsString()) {
// (copies char data)
cairo_pdf_surface_set_metadata(surf, t, *Nan::Utf8String(propValue));
}
}
static inline void setPdfMetaDate(cairo_surface_t* surf, Local<Object> opts,
cairo_pdf_metadata_t t, const char* pName) {
auto propName = Nan::New(pName).ToLocalChecked();
auto propValue = Nan::Get(opts, propName).ToLocalChecked();
if (propValue->IsDate()) {
auto date = static_cast<time_t>(propValue.As<v8::Date>()->ValueOf() / 1000); // ms -> s
char buf[sizeof "2011-10-08T07:07:09Z"];
strftime(buf, sizeof buf, "%FT%TZ", gmtime(&date));
cairo_pdf_surface_set_metadata(surf, t, buf);
}
}
static void setPdfMetadata(Canvas* canvas, Local<Object> opts) {
cairo_surface_t* surf = canvas->surface();
setPdfMetaStr(surf, opts, CAIRO_PDF_METADATA_TITLE, "title");
setPdfMetaStr(surf, opts, CAIRO_PDF_METADATA_AUTHOR, "author");
setPdfMetaStr(surf, opts, CAIRO_PDF_METADATA_SUBJECT, "subject");
setPdfMetaStr(surf, opts, CAIRO_PDF_METADATA_KEYWORDS, "keywords");
setPdfMetaStr(surf, opts, CAIRO_PDF_METADATA_CREATOR, "creator");
setPdfMetaDate(surf, opts, CAIRO_PDF_METADATA_CREATE_DATE, "creationDate");
setPdfMetaDate(surf, opts, CAIRO_PDF_METADATA_MOD_DATE, "modDate");
}
#endif // CAIRO 16+
/*
* Converts/encodes data to a Buffer. Async when a callback function is passed.
* PDF canvases:
(any) => Buffer
("application/pdf", config) => Buffer
* SVG canvases:
(any) => Buffer
* ARGB data:
("raw") => Buffer
* PNG-encoded
() => Buffer
(undefined|"image/png", {compressionLevel?: number, filter?: number}) => Buffer
((err: null|Error, buffer) => any)
((err: null|Error, buffer) => any, undefined|"image/png", {compressionLevel?: number, filter?: number})
* JPEG-encoded
("image/jpeg") => Buffer
("image/jpeg", {quality?: number, progressive?: Boolean, chromaSubsampling?: Boolean|number}) => Buffer
((err: null|Error, buffer) => any, "image/jpeg")
((err: null|Error, buffer) => any, "image/jpeg", {quality?: number, progressive?: Boolean, chromaSubsampling?: Boolean|number})
*/
NAN_METHOD(Canvas::ToBuffer) {
cairo_status_t status;
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.This());
// Vector canvases, sync only
const std::string name = canvas->backend()->getName();
if (name == "pdf" || name == "svg") {
// mime type may be present, but it's not checked
PdfSvgClosure* closure;
if (name == "pdf") {
closure = static_cast<PdfBackend*>(canvas->backend())->closure();
#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 16, 0)
if (info[1]->IsObject()) { // toBuffer("application/pdf", config)
setPdfMetadata(canvas, Nan::To<Object>(info[1]).ToLocalChecked());
}
#endif // CAIRO 16+
} else {
closure = static_cast<SvgBackend*>(canvas->backend())->closure();
}
cairo_surface_finish(canvas->surface());
Local<Object> buf = Nan::CopyBuffer((char*)&closure->vec[0], closure->vec.size()).ToLocalChecked();
info.GetReturnValue().Set(buf);
return;
}
// Raw ARGB data -- just a memcpy()
if (info[0]->StrictEquals(Nan::New<String>("raw").ToLocalChecked())) {
cairo_surface_t *surface = canvas->surface();
cairo_surface_flush(surface);
if (canvas->nBytes() > node::Buffer::kMaxLength) {
Nan::ThrowError("Data exceeds maximum buffer length.");
return;
}
const unsigned char *data = cairo_image_surface_get_data(surface);
Isolate* iso = Nan::GetCurrentContext()->GetIsolate();
Local<Object> buf = node::Buffer::Copy(iso, reinterpret_cast<const char*>(data), canvas->nBytes()).ToLocalChecked();
info.GetReturnValue().Set(buf);
return;
}
// Sync PNG, default
if (info[0]->IsUndefined() || info[0]->StrictEquals(Nan::New<String>("image/png").ToLocalChecked())) {
try {
PngClosure closure(canvas);
parsePNGArgs(info[1], closure);
if (closure.nPaletteColors == 0xFFFFFFFF) {
Nan::ThrowError("Palette length must be a multiple of 4.");
return;
}
Nan::TryCatch try_catch;
status = canvas_write_to_png_stream(canvas->surface(), PngClosure::writeVec, &closure);
if (try_catch.HasCaught()) {
try_catch.ReThrow();
} else if (status) {
throw status;
} else {
// TODO it's possible to avoid this copy
Local<Object> buf = Nan::CopyBuffer((char *)&closure.vec[0], closure.vec.size()).ToLocalChecked();
info.GetReturnValue().Set(buf);
}
} catch (cairo_status_t ex) {
Nan::ThrowError(Canvas::Error(ex));
} catch (const char* ex) {
Nan::ThrowError(ex);
}
return;
}
// Async PNG
if (info[0]->IsFunction() &&
(info[1]->IsUndefined() || info[1]->StrictEquals(Nan::New<String>("image/png").ToLocalChecked()))) {
PngClosure* closure;
try {
closure = new PngClosure(canvas);
parsePNGArgs(info[2], *closure);
} catch (cairo_status_t ex) {
Nan::ThrowError(Canvas::Error(ex));
return;
} catch (const char* ex) {
Nan::ThrowError(ex);
return;
}
canvas->Ref();
closure->cb.Reset(info[0].As<Function>());
uv_work_t* req = new uv_work_t;
req->data = closure;
// Make sure the surface exists since we won't have an isolate context in the async block:
canvas->surface();
uv_queue_work(uv_default_loop(), req, ToPngBufferAsync, (uv_after_work_cb)ToBufferAsyncAfter);
return;
}
#ifdef HAVE_JPEG
// Sync JPEG
Local<Value> jpegStr = Nan::New<String>("image/jpeg").ToLocalChecked();
if (info[0]->StrictEquals(jpegStr)) {
try {
JpegClosure closure(canvas);
parseJPEGArgs(info[1], closure);
Nan::TryCatch try_catch;
write_to_jpeg_buffer(canvas->surface(), &closure);
if (try_catch.HasCaught()) {
try_catch.ReThrow();
} else {
// TODO it's possible to avoid this copy.
Local<Object> buf = Nan::CopyBuffer((char *)&closure.vec[0], closure.vec.size()).ToLocalChecked();
info.GetReturnValue().Set(buf);
}
} catch (cairo_status_t ex) {
Nan::ThrowError(Canvas::Error(ex));
}
return;
}
// Async JPEG
if (info[0]->IsFunction() && info[1]->StrictEquals(jpegStr)) {
JpegClosure* closure = new JpegClosure(canvas);
parseJPEGArgs(info[2], *closure);
canvas->Ref();
closure->cb.Reset(info[0].As<Function>());
uv_work_t* req = new uv_work_t;
req->data = closure;
// Make sure the surface exists since we won't have an isolate context in the async block:
canvas->surface();
uv_queue_work(uv_default_loop(), req, ToJpegBufferAsync, (uv_after_work_cb)ToBufferAsyncAfter);
return;
}
#endif
}
/*
* Canvas::StreamPNG callback.
*/
static cairo_status_t
streamPNG(void *c, const uint8_t *data, unsigned len) {
Nan::HandleScope scope;
Nan::AsyncResource async("canvas:StreamPNG");
PngClosure* closure = (PngClosure*) c;
Local<Object> buf = Nan::CopyBuffer((char *)data, len).ToLocalChecked();
Local<Value> argv[3] = {
Nan::Null()
, buf
, Nan::New<Number>(len) };
closure->cb.Call(sizeof argv / sizeof *argv, argv, &async);
return CAIRO_STATUS_SUCCESS;
}
/*
* Stream PNG data synchronously. TODO async
* StreamPngSync(this, options: {palette?: Uint8ClampedArray, backgroundIndex?: uint32, compressionLevel: uint32, filters: uint32})
*/
NAN_METHOD(Canvas::StreamPNGSync) {
if (!info[0]->IsFunction())
return Nan::ThrowTypeError("callback function required");
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.This());
PngClosure closure(canvas);
parsePNGArgs(info[1], closure);
closure.cb.Reset(Local<Function>::Cast(info[0]));
Nan::TryCatch try_catch;
cairo_status_t status = canvas_write_to_png_stream(canvas->surface(), streamPNG, &closure);
if (try_catch.HasCaught()) {
try_catch.ReThrow();
return;
} else if (status) {
Local<Value> argv[1] = { Canvas::Error(status) };
Nan::Call(closure.cb, Nan::GetCurrentContext()->Global(), sizeof argv / sizeof *argv, argv);
} else {
Local<Value> argv[3] = {
Nan::Null()
, Nan::Null()
, Nan::New<Uint32>(0) };
Nan::Call(closure.cb, Nan::GetCurrentContext()->Global(), sizeof argv / sizeof *argv, argv);
}
return;
}
struct PdfStreamInfo {
Local<Function> fn;
uint32_t len;
uint8_t* data;
};
/*
* Canvas::StreamPDF FreeCallback
*/
void stream_pdf_free(char *, void *) {}
/*
* Canvas::StreamPDF callback.
*/
static cairo_status_t
streamPDF(void *c, const uint8_t *data, unsigned len) {
Nan::HandleScope scope;
Nan::AsyncResource async("canvas:StreamPDF");
PdfStreamInfo* streaminfo = static_cast<PdfStreamInfo*>(c);
// TODO this is technically wrong, we're returning a pointer to the data in a
// vector in a class with automatic storage duration. If the canvas goes out
// of scope while we're in the handler, a use-after-free could happen.
Local<Object> buf = Nan::NewBuffer(const_cast<char *>(reinterpret_cast<const char *>(data)), len, stream_pdf_free, 0).ToLocalChecked();
Local<Value> argv[3] = {
Nan::Null()
, buf
, Nan::New<Number>(len) };
async.runInAsyncScope(Nan::GetCurrentContext()->Global(), streaminfo->fn, sizeof argv / sizeof *argv, argv);
return CAIRO_STATUS_SUCCESS;
}
cairo_status_t canvas_write_to_pdf_stream(cairo_surface_t *surface, cairo_write_func_t write_func, PdfStreamInfo* streaminfo) {
size_t whole_chunks = streaminfo->len / PAGE_SIZE;
size_t remainder = streaminfo->len - whole_chunks * PAGE_SIZE;
for (size_t i = 0; i < whole_chunks; ++i) {
write_func(streaminfo, &streaminfo->data[i * PAGE_SIZE], PAGE_SIZE);
}
if (remainder) {
write_func(streaminfo, &streaminfo->data[whole_chunks * PAGE_SIZE], remainder);
}
return CAIRO_STATUS_SUCCESS;
}
/*
* Stream PDF data synchronously.
*/
NAN_METHOD(Canvas::StreamPDFSync) {
if (!info[0]->IsFunction())
return Nan::ThrowTypeError("callback function required");
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.Holder());
if (canvas->backend()->getName() != "pdf")
return Nan::ThrowTypeError("wrong canvas type");
#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 16, 0)
if (info[1]->IsObject()) {
setPdfMetadata(canvas, Nan::To<Object>(info[1]).ToLocalChecked());
}
#endif
cairo_surface_finish(canvas->surface());
PdfSvgClosure* closure = static_cast<PdfBackend*>(canvas->backend())->closure();
Local<Function> fn = info[0].As<Function>();
PdfStreamInfo streaminfo;
streaminfo.fn = fn;
streaminfo.data = &closure->vec[0];
streaminfo.len = closure->vec.size();
Nan::TryCatch try_catch;
cairo_status_t status = canvas_write_to_pdf_stream(canvas->surface(), streamPDF, &streaminfo);
if (try_catch.HasCaught()) {
try_catch.ReThrow();
} else if (status) {
Local<Value> error = Canvas::Error(status);
Nan::Call(fn, Nan::GetCurrentContext()->Global(), 1, &error);
} else {
Local<Value> argv[3] = {
Nan::Null()
, Nan::Null()
, Nan::New<Uint32>(0) };
Nan::Call(fn, Nan::GetCurrentContext()->Global(), sizeof argv / sizeof *argv, argv);
}
}
/*
* Stream JPEG data synchronously.
*/
#ifdef HAVE_JPEG
static uint32_t getSafeBufSize(Canvas* canvas) {
// Don't allow the buffer size to exceed the size of the canvas (#674)
// TODO not sure if this is really correct, but it fixed #674
return (std::min)(canvas->getWidth() * canvas->getHeight() * 4, static_cast<int>(PAGE_SIZE));
}
NAN_METHOD(Canvas::StreamJPEGSync) {
if (!info[1]->IsFunction())
return Nan::ThrowTypeError("callback function required");
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(info.This());
JpegClosure closure(canvas);
parseJPEGArgs(info[0], closure);
closure.cb.Reset(Local<Function>::Cast(info[1]));
Nan::TryCatch try_catch;
uint32_t bufsize = getSafeBufSize(canvas);
write_to_jpeg_stream(canvas->surface(), bufsize, &closure);
if (try_catch.HasCaught()) {
try_catch.ReThrow();
}
return;
}
#endif
char *
str_value(Local<Value> val, const char *fallback, bool can_be_number) {
if (val->IsString() || (can_be_number && val->IsNumber())) {
return strdup(*Nan::Utf8String(val));
} else if (fallback) {
return strdup(fallback);
} else {
return NULL;
}
}
NAN_METHOD(Canvas::RegisterFont) {
if (!info[0]->IsString()) {
return Nan::ThrowError("Wrong argument type");
} else if (!info[1]->IsObject()) {
return Nan::ThrowError(GENERIC_FACE_ERROR);
}
Nan::Utf8String filePath(info[0]);
PangoFontDescription *sys_desc = get_pango_font_description((unsigned char *) *filePath);
if (!sys_desc) return Nan::ThrowError("Could not parse font file");
PangoFontDescription *user_desc = pango_font_description_new();
// now check the attrs, there are many ways to be wrong
Local<Object> js_user_desc = Nan::To<Object>(info[1]).ToLocalChecked();
Local<String> family_prop = Nan::New<String>("family").ToLocalChecked();
Local<String> weight_prop = Nan::New<String>("weight").ToLocalChecked();
Local<String> style_prop = Nan::New<String>("style").ToLocalChecked();
char *family = str_value(Nan::Get(js_user_desc, family_prop).ToLocalChecked(), NULL, false);
char *weight = str_value(Nan::Get(js_user_desc, weight_prop).ToLocalChecked(), "normal", true);
char *style = str_value(Nan::Get(js_user_desc, style_prop).ToLocalChecked(), "normal", false);
if (family && weight && style) {
pango_font_description_set_weight(user_desc, Canvas::GetWeightFromCSSString(weight));
pango_font_description_set_style(user_desc, Canvas::GetStyleFromCSSString(style));
pango_font_description_set_family(user_desc, family);
auto found = std::find_if(font_face_list.begin(), font_face_list.end(), [&](FontFace& f) {
return pango_font_description_equal(f.sys_desc, sys_desc);
});
if (found != font_face_list.end()) {
pango_font_description_free(found->user_desc);
found->user_desc = user_desc;
} else if (register_font((unsigned char *) *filePath)) {
FontFace face;
face.user_desc = user_desc;
face.sys_desc = sys_desc;
strncpy((char *)face.file_path, (char *) *filePath, 1023);
font_face_list.push_back(face);
} else {
pango_font_description_free(user_desc);
Nan::ThrowError("Could not load font to the system's font host");
}
} else {
pango_font_description_free(user_desc);
Nan::ThrowError(GENERIC_FACE_ERROR);
}
free(family);
free(weight);
free(style);
}
NAN_METHOD(Canvas::DeregisterAllFonts) {
// Unload all fonts from pango to free up memory
bool success = true;
std::for_each(font_face_list.begin(), font_face_list.end(), [&](FontFace& f) {
if (!deregister_font( (unsigned char *)f.file_path )) success = false;
pango_font_description_free(f.user_desc);
pango_font_description_free(f.sys_desc);
});
font_face_list.clear();
if (!success) Nan::ThrowError("Could not deregister one or more fonts");
}
/*
* Initialize cairo surface.
*/
Canvas::Canvas(Backend* backend) : ObjectWrap() {
_backend = backend;
}
/*
* Destroy cairo surface.
*/
Canvas::~Canvas() {
if (_backend != NULL) {
delete _backend;
}
}
/*
* Get a PangoStyle from a CSS string (like "italic")
*/
PangoStyle
Canvas::GetStyleFromCSSString(const char *style) {
PangoStyle s = PANGO_STYLE_NORMAL;
if (strlen(style) > 0) {
if (0 == strcmp("italic", style)) {
s = PANGO_STYLE_ITALIC;
} else if (0 == strcmp("oblique", style)) {
s = PANGO_STYLE_OBLIQUE;
}
}
return s;
}
/*
* Get a PangoWeight from a CSS string ("bold", "100", etc)
*/
PangoWeight
Canvas::GetWeightFromCSSString(const char *weight) {
PangoWeight w = PANGO_WEIGHT_NORMAL;
if (strlen(weight) > 0) {
if (0 == strcmp("bold", weight)) {
w = PANGO_WEIGHT_BOLD;
} else if (0 == strcmp("100", weight)) {
w = PANGO_WEIGHT_THIN;
} else if (0 == strcmp("200", weight)) {
w = PANGO_WEIGHT_ULTRALIGHT;
} else if (0 == strcmp("300", weight)) {
w = PANGO_WEIGHT_LIGHT;
} else if (0 == strcmp("400", weight)) {
w = PANGO_WEIGHT_NORMAL;
} else if (0 == strcmp("500", weight)) {
w = PANGO_WEIGHT_MEDIUM;
} else if (0 == strcmp("600", weight)) {
w = PANGO_WEIGHT_SEMIBOLD;
} else if (0 == strcmp("700", weight)) {
w = PANGO_WEIGHT_BOLD;
} else if (0 == strcmp("800", weight)) {
w = PANGO_WEIGHT_ULTRABOLD;
} else if (0 == strcmp("900", weight)) {
w = PANGO_WEIGHT_HEAVY;
}
}
return w;
}
/*
* Given a user description, return a description that will select the
* font either from the system or @font-face
*/
PangoFontDescription *
Canvas::ResolveFontDescription(const PangoFontDescription *desc) {
// One of the user-specified families could map to multiple SFNT family names
// if someone registered two different fonts under the same family name.
// https://drafts.csswg.org/css-fonts-3/#font-style-matching
FontFace best;
istringstream families(pango_font_description_get_family(desc));
unordered_set<string> seen_families;
string resolved_families;
bool first = true;
for (string family; getline(families, family, ','); ) {
string renamed_families;
for (auto& ff : font_face_list) {
string pangofamily = string(pango_font_description_get_family(ff.user_desc));
if (streq_casein(family, pangofamily)) {
const char* sys_desc_family_name = pango_font_description_get_family(ff.sys_desc);
bool unseen = seen_families.find(sys_desc_family_name) == seen_families.end();
bool better = best.user_desc == nullptr || pango_font_description_better_match(desc, best.user_desc, ff.user_desc);
// Avoid sending duplicate SFNT font names due to a bug in Pango for macOS:
// https://bugzilla.gnome.org/show_bug.cgi?id=762873
if (unseen) {
seen_families.insert(sys_desc_family_name);
if (better) {
renamed_families = string(sys_desc_family_name) + (renamed_families.size() ? "," : "") + renamed_families;
} else {
renamed_families = renamed_families + (renamed_families.size() ? "," : "") + sys_desc_family_name;
}
}
if (first && better) best = ff;
}
}
if (resolved_families.size()) resolved_families += ',';
resolved_families += renamed_families.size() ? renamed_families : family;
first = false;
}
PangoFontDescription* ret = pango_font_description_copy(best.sys_desc ? best.sys_desc : desc);
pango_font_description_set_family(ret, resolved_families.c_str());
return ret;
}
/*
* Re-alloc the surface, destroying the previous.
*/
void
Canvas::resurface(Local<Object> canvas) {
Nan::HandleScope scope;
Local<Value> context;
backend()->recreateSurface();
// Reset context
context = Nan::Get(canvas, Nan::New<String>("context").ToLocalChecked()).ToLocalChecked();
if (!context->IsUndefined()) {
Context2d *context2d = ObjectWrap::Unwrap<Context2d>(Nan::To<Object>(context).ToLocalChecked());
cairo_t *prev = context2d->context();
context2d->setContext(createCairoContext());
context2d->resetState();
cairo_destroy(prev);
}
}
/**
* Wrapper around cairo_create()
* (do not call cairo_create directly, call this instead)
*/
cairo_t*
Canvas::createCairoContext() {
cairo_t* ret = cairo_create(surface());
cairo_set_line_width(ret, 1); // Cairo defaults to 2
return ret;
}
/*
* Construct an Error from the given cairo status.
*/
Local<Value>
Canvas::Error(cairo_status_t status) {
return Exception::Error(Nan::New<String>(cairo_status_to_string(status)).ToLocalChecked());
}
#undef CHECK_RECEIVER

96
ccc-tnt-psd2ui-v2.4.x/node_modules/canvas/src/Canvas.h generated vendored Normal file
View File

@@ -0,0 +1,96 @@
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
#pragma once
#include "backend/Backend.h"
#include <cairo.h>
#include "dll_visibility.h"
#include <nan.h>
#include <pango/pangocairo.h>
#include <v8.h>
#include <vector>
#include <cstddef>
/*
* FontFace describes a font file in terms of one PangoFontDescription that
* will resolve to it and one that the user describes it as (like @font-face)
*/
class FontFace {
public:
PangoFontDescription *sys_desc = nullptr;
PangoFontDescription *user_desc = nullptr;
unsigned char file_path[1024];
};
enum text_baseline_t : uint8_t {
TEXT_BASELINE_ALPHABETIC = 0,
TEXT_BASELINE_TOP = 1,
TEXT_BASELINE_BOTTOM = 2,
TEXT_BASELINE_MIDDLE = 3,
TEXT_BASELINE_IDEOGRAPHIC = 4,
TEXT_BASELINE_HANGING = 5
};
enum text_align_t : int8_t {
TEXT_ALIGNMENT_LEFT = -1,
TEXT_ALIGNMENT_CENTER = 0,
TEXT_ALIGNMENT_RIGHT = 1,
// Currently same as LEFT and RIGHT without RTL support:
TEXT_ALIGNMENT_START = -2,
TEXT_ALIGNMENT_END = 2
};
enum canvas_draw_mode_t : uint8_t {
TEXT_DRAW_PATHS,
TEXT_DRAW_GLYPHS
};
/*
* Canvas.
*/
class Canvas: public Nan::ObjectWrap {
public:
static Nan::Persistent<v8::FunctionTemplate> constructor;
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
static NAN_METHOD(New);
static NAN_METHOD(ToBuffer);
static NAN_GETTER(GetType);
static NAN_GETTER(GetStride);
static NAN_GETTER(GetWidth);
static NAN_GETTER(GetHeight);
static NAN_SETTER(SetWidth);
static NAN_SETTER(SetHeight);
static NAN_METHOD(StreamPNGSync);
static NAN_METHOD(StreamPDFSync);
static NAN_METHOD(StreamJPEGSync);
static NAN_METHOD(RegisterFont);
static NAN_METHOD(DeregisterAllFonts);
static v8::Local<v8::Value> Error(cairo_status_t status);
static void ToPngBufferAsync(uv_work_t *req);
static void ToJpegBufferAsync(uv_work_t *req);
static void ToBufferAsyncAfter(uv_work_t *req);
static PangoWeight GetWeightFromCSSString(const char *weight);
static PangoStyle GetStyleFromCSSString(const char *style);
static PangoFontDescription *ResolveFontDescription(const PangoFontDescription *desc);
DLL_PUBLIC inline Backend* backend() { return _backend; }
DLL_PUBLIC inline cairo_surface_t* surface(){ return backend()->getSurface(); }
cairo_t* createCairoContext();
DLL_PUBLIC inline uint8_t *data(){ return cairo_image_surface_get_data(surface()); }
DLL_PUBLIC inline int stride(){ return cairo_image_surface_get_stride(surface()); }
DLL_PUBLIC inline std::size_t nBytes(){
return static_cast<std::size_t>(getHeight()) * stride();
}
DLL_PUBLIC inline int getWidth() { return backend()->getWidth(); }
DLL_PUBLIC inline int getHeight() { return backend()->getHeight(); }
Canvas(Backend* backend);
void resurface(v8::Local<v8::Object> canvas);
private:
~Canvas();
Backend* _backend;
};

View File

@@ -0,0 +1,23 @@
#pragma once
#include <string>
class CanvasError {
public:
std::string message;
std::string syscall;
std::string path;
int cerrno = 0;
void set(const char* iMessage = NULL, const char* iSyscall = NULL, int iErrno = 0, const char* iPath = NULL) {
if (iMessage) message.assign(iMessage);
if (iSyscall) syscall.assign(iSyscall);
cerrno = iErrno;
if (iPath) path.assign(iPath);
}
void reset() {
message.clear();
syscall.clear();
path.clear();
cerrno = 0;
}
};

View File

@@ -0,0 +1,123 @@
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
#include "CanvasGradient.h"
#include "Canvas.h"
#include "color.h"
using namespace v8;
Nan::Persistent<FunctionTemplate> Gradient::constructor;
/*
* Initialize CanvasGradient.
*/
void
Gradient::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {
Nan::HandleScope scope;
// Constructor
Local<FunctionTemplate> ctor = Nan::New<FunctionTemplate>(Gradient::New);
constructor.Reset(ctor);
ctor->InstanceTemplate()->SetInternalFieldCount(1);
ctor->SetClassName(Nan::New("CanvasGradient").ToLocalChecked());
// Prototype
Nan::SetPrototypeMethod(ctor, "addColorStop", AddColorStop);
Local<Context> ctx = Nan::GetCurrentContext();
Nan::Set(target,
Nan::New("CanvasGradient").ToLocalChecked(),
ctor->GetFunction(ctx).ToLocalChecked());
}
/*
* Initialize a new CanvasGradient.
*/
NAN_METHOD(Gradient::New) {
if (!info.IsConstructCall()) {
return Nan::ThrowTypeError("Class constructors cannot be invoked without 'new'");
}
// Linear
if (4 == info.Length()) {
Gradient *grad = new Gradient(
Nan::To<double>(info[0]).FromMaybe(0)
, Nan::To<double>(info[1]).FromMaybe(0)
, Nan::To<double>(info[2]).FromMaybe(0)
, Nan::To<double>(info[3]).FromMaybe(0));
grad->Wrap(info.This());
info.GetReturnValue().Set(info.This());
return;
}
// Radial
if (6 == info.Length()) {
Gradient *grad = new Gradient(
Nan::To<double>(info[0]).FromMaybe(0)
, Nan::To<double>(info[1]).FromMaybe(0)
, Nan::To<double>(info[2]).FromMaybe(0)
, Nan::To<double>(info[3]).FromMaybe(0)
, Nan::To<double>(info[4]).FromMaybe(0)
, Nan::To<double>(info[5]).FromMaybe(0));
grad->Wrap(info.This());
info.GetReturnValue().Set(info.This());
return;
}
return Nan::ThrowTypeError("invalid arguments");
}
/*
* Add color stop.
*/
NAN_METHOD(Gradient::AddColorStop) {
if (!info[0]->IsNumber())
return Nan::ThrowTypeError("offset required");
if (!info[1]->IsString())
return Nan::ThrowTypeError("color string required");
Gradient *grad = Nan::ObjectWrap::Unwrap<Gradient>(info.This());
short ok;
Nan::Utf8String str(info[1]);
uint32_t rgba = rgba_from_string(*str, &ok);
if (ok) {
rgba_t color = rgba_create(rgba);
cairo_pattern_add_color_stop_rgba(
grad->pattern()
, Nan::To<double>(info[0]).FromMaybe(0)
, color.r
, color.g
, color.b
, color.a);
} else {
return Nan::ThrowTypeError("parse color failed");
}
}
/*
* Initialize linear gradient.
*/
Gradient::Gradient(double x0, double y0, double x1, double y1) {
_pattern = cairo_pattern_create_linear(x0, y0, x1, y1);
}
/*
* Initialize radial gradient.
*/
Gradient::Gradient(double x0, double y0, double r0, double x1, double y1, double r1) {
_pattern = cairo_pattern_create_radial(x0, y0, r0, x1, y1, r1);
}
/*
* Destroy the pattern.
*/
Gradient::~Gradient() {
cairo_pattern_destroy(_pattern);
}

View File

@@ -0,0 +1,22 @@
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
#pragma once
#include <nan.h>
#include <v8.h>
#include <cairo.h>
class Gradient: public Nan::ObjectWrap {
public:
static Nan::Persistent<v8::FunctionTemplate> constructor;
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
static NAN_METHOD(New);
static NAN_METHOD(AddColorStop);
Gradient(double x0, double y0, double x1, double y1);
Gradient(double x0, double y0, double r0, double x1, double y1, double r1);
inline cairo_pattern_t *pattern(){ return _pattern; }
private:
~Gradient();
cairo_pattern_t *_pattern;
};

View File

@@ -0,0 +1,136 @@
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
#include "CanvasPattern.h"
#include "Canvas.h"
#include "Image.h"
using namespace v8;
const cairo_user_data_key_t *pattern_repeat_key;
Nan::Persistent<FunctionTemplate> Pattern::constructor;
Nan::Persistent<Function> Pattern::_DOMMatrix;
/*
* Initialize CanvasPattern.
*/
void
Pattern::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {
Nan::HandleScope scope;
// Constructor
Local<FunctionTemplate> ctor = Nan::New<FunctionTemplate>(Pattern::New);
constructor.Reset(ctor);
ctor->InstanceTemplate()->SetInternalFieldCount(1);
ctor->SetClassName(Nan::New("CanvasPattern").ToLocalChecked());
Nan::SetPrototypeMethod(ctor, "setTransform", SetTransform);
// Prototype
Local<Context> ctx = Nan::GetCurrentContext();
Nan::Set(target, Nan::New("CanvasPattern").ToLocalChecked(), ctor->GetFunction(ctx).ToLocalChecked());
Nan::Set(target, Nan::New("CanvasPatternInit").ToLocalChecked(), Nan::New<Function>(SaveExternalModules));
}
/*
* Save some external modules as private references.
*/
NAN_METHOD(Pattern::SaveExternalModules) {
_DOMMatrix.Reset(Nan::To<Function>(info[0]).ToLocalChecked());
}
/*
* Initialize a new CanvasPattern.
*/
NAN_METHOD(Pattern::New) {
if (!info.IsConstructCall()) {
return Nan::ThrowTypeError("Class constructors cannot be invoked without 'new'");
}
cairo_surface_t *surface;
Local<Object> obj = Nan::To<Object>(info[0]).ToLocalChecked();
// Image
if (Nan::New(Image::constructor)->HasInstance(obj)) {
Image *img = Nan::ObjectWrap::Unwrap<Image>(obj);
if (!img->isComplete()) {
return Nan::ThrowError("Image given has not completed loading");
}
surface = img->surface();
// Canvas
} else if (Nan::New(Canvas::constructor)->HasInstance(obj)) {
Canvas *canvas = Nan::ObjectWrap::Unwrap<Canvas>(obj);
surface = canvas->surface();
// Invalid
} else {
return Nan::ThrowTypeError("Image or Canvas expected");
}
repeat_type_t repeat = REPEAT;
if (0 == strcmp("no-repeat", *Nan::Utf8String(info[1]))) {
repeat = NO_REPEAT;
} else if (0 == strcmp("repeat-x", *Nan::Utf8String(info[1]))) {
repeat = REPEAT_X;
} else if (0 == strcmp("repeat-y", *Nan::Utf8String(info[1]))) {
repeat = REPEAT_Y;
}
Pattern *pattern = new Pattern(surface, repeat);
pattern->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
/*
* Set the pattern-space to user-space transform.
*/
NAN_METHOD(Pattern::SetTransform) {
Pattern *pattern = Nan::ObjectWrap::Unwrap<Pattern>(info.This());
Local<Context> ctx = Nan::GetCurrentContext();
Local<Object> mat = Nan::To<Object>(info[0]).ToLocalChecked();
#if NODE_MAJOR_VERSION >= 8
if (!mat->InstanceOf(ctx, _DOMMatrix.Get(Isolate::GetCurrent())).ToChecked()) {
return Nan::ThrowTypeError("Expected DOMMatrix");
}
#endif
cairo_matrix_t matrix;
cairo_matrix_init(&matrix,
Nan::To<double>(Nan::Get(mat, Nan::New("a").ToLocalChecked()).ToLocalChecked()).FromMaybe(1),
Nan::To<double>(Nan::Get(mat, Nan::New("b").ToLocalChecked()).ToLocalChecked()).FromMaybe(0),
Nan::To<double>(Nan::Get(mat, Nan::New("c").ToLocalChecked()).ToLocalChecked()).FromMaybe(0),
Nan::To<double>(Nan::Get(mat, Nan::New("d").ToLocalChecked()).ToLocalChecked()).FromMaybe(1),
Nan::To<double>(Nan::Get(mat, Nan::New("e").ToLocalChecked()).ToLocalChecked()).FromMaybe(0),
Nan::To<double>(Nan::Get(mat, Nan::New("f").ToLocalChecked()).ToLocalChecked()).FromMaybe(0)
);
cairo_matrix_invert(&matrix);
cairo_pattern_set_matrix(pattern->_pattern, &matrix);
}
/*
* Initialize pattern.
*/
Pattern::Pattern(cairo_surface_t *surface, repeat_type_t repeat) {
_pattern = cairo_pattern_create_for_surface(surface);
_repeat = repeat;
cairo_pattern_set_user_data(_pattern, pattern_repeat_key, &_repeat, NULL);
}
repeat_type_t Pattern::get_repeat_type_for_cairo_pattern(cairo_pattern_t *pattern) {
void *ud = cairo_pattern_get_user_data(pattern, pattern_repeat_key);
return *reinterpret_cast<repeat_type_t*>(ud);
}
/*
* Destroy the pattern.
*/
Pattern::~Pattern() {
cairo_pattern_destroy(_pattern);
}

View File

@@ -0,0 +1,37 @@
// Copyright (c) 2011 LearnBoost <tj@learnboost.com>
#pragma once
#include <cairo.h>
#include <nan.h>
#include <v8.h>
/*
* Canvas types.
*/
typedef enum {
NO_REPEAT, // match CAIRO_EXTEND_NONE
REPEAT, // match CAIRO_EXTEND_REPEAT
REPEAT_X, // needs custom processing
REPEAT_Y // needs custom processing
} repeat_type_t;
extern const cairo_user_data_key_t *pattern_repeat_key;
class Pattern: public Nan::ObjectWrap {
public:
static Nan::Persistent<v8::FunctionTemplate> constructor;
static Nan::Persistent<v8::Function> _DOMMatrix;
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
static NAN_METHOD(New);
static NAN_METHOD(SaveExternalModules);
static NAN_METHOD(SetTransform);
static repeat_type_t get_repeat_type_for_cairo_pattern(cairo_pattern_t *pattern);
Pattern(cairo_surface_t *surface, repeat_type_t repeat);
inline cairo_pattern_t *pattern(){ return _pattern; }
private:
~Pattern();
cairo_pattern_t *_pattern;
repeat_type_t _repeat;
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,224 @@
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
#pragma once
#include "cairo.h"
#include "Canvas.h"
#include "color.h"
#include "nan.h"
#include <pango/pangocairo.h>
#include <stack>
/*
* State struct.
*
* Used in conjunction with Save() / Restore() since
* cairo's gstate maintains only a single source pattern at a time.
*/
struct canvas_state_t {
rgba_t fill = { 0, 0, 0, 1 };
rgba_t stroke = { 0, 0, 0, 1 };
rgba_t shadow = { 0, 0, 0, 0 };
double shadowOffsetX = 0.;
double shadowOffsetY = 0.;
cairo_pattern_t* fillPattern = nullptr;
cairo_pattern_t* strokePattern = nullptr;
cairo_pattern_t* fillGradient = nullptr;
cairo_pattern_t* strokeGradient = nullptr;
PangoFontDescription* fontDescription = nullptr;
cairo_filter_t patternQuality = CAIRO_FILTER_GOOD;
float globalAlpha = 1.f;
int shadowBlur = 0;
text_align_t textAlignment = TEXT_ALIGNMENT_LEFT; // TODO default is supposed to be START
text_baseline_t textBaseline = TEXT_BASELINE_ALPHABETIC;
canvas_draw_mode_t textDrawingMode = TEXT_DRAW_PATHS;
bool imageSmoothingEnabled = true;
canvas_state_t() {
fontDescription = pango_font_description_from_string("sans");
pango_font_description_set_absolute_size(fontDescription, 10 * PANGO_SCALE);
}
canvas_state_t(const canvas_state_t& other) {
fill = other.fill;
stroke = other.stroke;
patternQuality = other.patternQuality;
fillPattern = other.fillPattern;
strokePattern = other.strokePattern;
fillGradient = other.fillGradient;
strokeGradient = other.strokeGradient;
globalAlpha = other.globalAlpha;
textAlignment = other.textAlignment;
textBaseline = other.textBaseline;
shadow = other.shadow;
shadowBlur = other.shadowBlur;
shadowOffsetX = other.shadowOffsetX;
shadowOffsetY = other.shadowOffsetY;
textDrawingMode = other.textDrawingMode;
fontDescription = pango_font_description_copy(other.fontDescription);
imageSmoothingEnabled = other.imageSmoothingEnabled;
}
~canvas_state_t() {
pango_font_description_free(fontDescription);
}
};
/*
* Equivalent to a PangoRectangle but holds floats instead of ints
* (software pixels are stored here instead of pango units)
*
* Should be compatible with PANGO_ASCENT, PANGO_LBEARING, etc.
*/
typedef struct {
float x;
float y;
float width;
float height;
} float_rectangle;
class Context2d : public Nan::ObjectWrap {
public:
std::stack<canvas_state_t> states;
canvas_state_t *state;
Context2d(Canvas *canvas);
static Nan::Persistent<v8::Function> _DOMMatrix;
static Nan::Persistent<v8::Function> _parseFont;
static Nan::Persistent<v8::FunctionTemplate> constructor;
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
static NAN_METHOD(New);
static NAN_METHOD(SaveExternalModules);
static NAN_METHOD(DrawImage);
static NAN_METHOD(PutImageData);
static NAN_METHOD(Save);
static NAN_METHOD(Restore);
static NAN_METHOD(Rotate);
static NAN_METHOD(Translate);
static NAN_METHOD(Scale);
static NAN_METHOD(Transform);
static NAN_METHOD(GetTransform);
static NAN_METHOD(ResetTransform);
static NAN_METHOD(SetTransform);
static NAN_METHOD(IsPointInPath);
static NAN_METHOD(BeginPath);
static NAN_METHOD(ClosePath);
static NAN_METHOD(AddPage);
static NAN_METHOD(Clip);
static NAN_METHOD(Fill);
static NAN_METHOD(Stroke);
static NAN_METHOD(FillText);
static NAN_METHOD(StrokeText);
static NAN_METHOD(SetFont);
static NAN_METHOD(SetFillColor);
static NAN_METHOD(SetStrokeColor);
static NAN_METHOD(SetStrokePattern);
static NAN_METHOD(SetTextAlignment);
static NAN_METHOD(SetLineDash);
static NAN_METHOD(GetLineDash);
static NAN_METHOD(MeasureText);
static NAN_METHOD(BezierCurveTo);
static NAN_METHOD(QuadraticCurveTo);
static NAN_METHOD(LineTo);
static NAN_METHOD(MoveTo);
static NAN_METHOD(FillRect);
static NAN_METHOD(StrokeRect);
static NAN_METHOD(ClearRect);
static NAN_METHOD(Rect);
static NAN_METHOD(RoundRect);
static NAN_METHOD(Arc);
static NAN_METHOD(ArcTo);
static NAN_METHOD(Ellipse);
static NAN_METHOD(GetImageData);
static NAN_METHOD(CreateImageData);
static NAN_METHOD(GetStrokeColor);
static NAN_METHOD(CreatePattern);
static NAN_METHOD(CreateLinearGradient);
static NAN_METHOD(CreateRadialGradient);
static NAN_GETTER(GetFormat);
static NAN_GETTER(GetPatternQuality);
static NAN_GETTER(GetImageSmoothingEnabled);
static NAN_GETTER(GetGlobalCompositeOperation);
static NAN_GETTER(GetGlobalAlpha);
static NAN_GETTER(GetShadowColor);
static NAN_GETTER(GetMiterLimit);
static NAN_GETTER(GetLineCap);
static NAN_GETTER(GetLineJoin);
static NAN_GETTER(GetLineWidth);
static NAN_GETTER(GetLineDashOffset);
static NAN_GETTER(GetShadowOffsetX);
static NAN_GETTER(GetShadowOffsetY);
static NAN_GETTER(GetShadowBlur);
static NAN_GETTER(GetAntiAlias);
static NAN_GETTER(GetTextDrawingMode);
static NAN_GETTER(GetQuality);
static NAN_GETTER(GetCurrentTransform);
static NAN_GETTER(GetFillStyle);
static NAN_GETTER(GetStrokeStyle);
static NAN_GETTER(GetFont);
static NAN_GETTER(GetTextBaseline);
static NAN_GETTER(GetTextAlign);
static NAN_SETTER(SetPatternQuality);
static NAN_SETTER(SetImageSmoothingEnabled);
static NAN_SETTER(SetGlobalCompositeOperation);
static NAN_SETTER(SetGlobalAlpha);
static NAN_SETTER(SetShadowColor);
static NAN_SETTER(SetMiterLimit);
static NAN_SETTER(SetLineCap);
static NAN_SETTER(SetLineJoin);
static NAN_SETTER(SetLineWidth);
static NAN_SETTER(SetLineDashOffset);
static NAN_SETTER(SetShadowOffsetX);
static NAN_SETTER(SetShadowOffsetY);
static NAN_SETTER(SetShadowBlur);
static NAN_SETTER(SetAntiAlias);
static NAN_SETTER(SetTextDrawingMode);
static NAN_SETTER(SetQuality);
static NAN_SETTER(SetCurrentTransform);
static NAN_SETTER(SetFillStyle);
static NAN_SETTER(SetStrokeStyle);
static NAN_SETTER(SetFont);
static NAN_SETTER(SetTextBaseline);
static NAN_SETTER(SetTextAlign);
inline void setContext(cairo_t *ctx) { _context = ctx; }
inline cairo_t *context(){ return _context; }
inline Canvas *canvas(){ return _canvas; }
inline bool hasShadow();
void inline setSourceRGBA(rgba_t color);
void inline setSourceRGBA(cairo_t *ctx, rgba_t color);
void setTextPath(double x, double y);
void blur(cairo_surface_t *surface, int radius);
void shadow(void (fn)(cairo_t *cr));
void shadowStart();
void shadowApply();
void savePath();
void restorePath();
void saveState();
void restoreState();
void inline setFillRule(v8::Local<v8::Value> value);
void fill(bool preserve = false);
void stroke(bool preserve = false);
void save();
void restore();
void setFontFromState();
void resetState();
inline PangoLayout *layout(){ return _layout; }
private:
~Context2d();
void _resetPersistentHandles();
v8::Local<v8::Value> _getFillColor();
v8::Local<v8::Value> _getStrokeColor();
void _setFillColor(v8::Local<v8::Value> arg);
void _setFillPattern(v8::Local<v8::Value> arg);
void _setStrokeColor(v8::Local<v8::Value> arg);
void _setStrokePattern(v8::Local<v8::Value> arg);
Nan::Persistent<v8::Value> _fillStyle;
Nan::Persistent<v8::Value> _strokeStyle;
Nan::Persistent<v8::Value> _font;
Canvas *_canvas;
cairo_t *_context;
cairo_path_t *_path;
PangoLayout *_layout;
};

1434
ccc-tnt-psd2ui-v2.4.x/node_modules/canvas/src/Image.cc generated vendored Normal file

File diff suppressed because it is too large Load Diff

127
ccc-tnt-psd2ui-v2.4.x/node_modules/canvas/src/Image.h generated vendored Normal file
View File

@@ -0,0 +1,127 @@
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
#pragma once
#include <cairo.h>
#include "CanvasError.h"
#include <functional>
#include <nan.h>
#include <stdint.h> // node < 7 uses libstdc++ on macOS which lacks complete c++11
#include <v8.h>
#ifdef HAVE_JPEG
#include <jpeglib.h>
#include <jerror.h>
#endif
#ifdef HAVE_GIF
#include <gif_lib.h>
#if GIFLIB_MAJOR > 5 || GIFLIB_MAJOR == 5 && GIFLIB_MINOR >= 1
#define GIF_CLOSE_FILE(gif) DGifCloseFile(gif, NULL)
#else
#define GIF_CLOSE_FILE(gif) DGifCloseFile(gif)
#endif
#endif
#ifdef HAVE_RSVG
#include <librsvg/rsvg.h>
// librsvg <= 2.36.1, identified by undefined macro, needs an extra include
#ifndef LIBRSVG_CHECK_VERSION
#include <librsvg/rsvg-cairo.h>
#endif
#endif
using JPEGDecodeL = std::function<uint32_t (uint8_t* const src)>;
class Image: public Nan::ObjectWrap {
public:
char *filename;
int width, height;
int naturalWidth, naturalHeight;
static Nan::Persistent<v8::FunctionTemplate> constructor;
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
static NAN_METHOD(New);
static NAN_GETTER(GetComplete);
static NAN_GETTER(GetWidth);
static NAN_GETTER(GetHeight);
static NAN_GETTER(GetNaturalWidth);
static NAN_GETTER(GetNaturalHeight);
static NAN_GETTER(GetDataMode);
static NAN_SETTER(SetDataMode);
static NAN_SETTER(SetWidth);
static NAN_SETTER(SetHeight);
static NAN_METHOD(GetSource);
static NAN_METHOD(SetSource);
inline uint8_t *data(){ return cairo_image_surface_get_data(_surface); }
inline int stride(){ return cairo_image_surface_get_stride(_surface); }
static int isPNG(uint8_t *data);
static int isJPEG(uint8_t *data);
static int isGIF(uint8_t *data);
static int isSVG(uint8_t *data, unsigned len);
static int isBMP(uint8_t *data, unsigned len);
static cairo_status_t readPNG(void *closure, unsigned char *data, unsigned len);
inline int isComplete(){ return COMPLETE == state; }
cairo_surface_t *surface();
cairo_status_t loadSurface();
cairo_status_t loadFromBuffer(uint8_t *buf, unsigned len);
cairo_status_t loadPNGFromBuffer(uint8_t *buf);
cairo_status_t loadPNG();
void clearData();
#ifdef HAVE_RSVG
cairo_status_t loadSVGFromBuffer(uint8_t *buf, unsigned len);
cairo_status_t loadSVG(FILE *stream);
cairo_status_t renderSVGToSurface();
#endif
#ifdef HAVE_GIF
cairo_status_t loadGIFFromBuffer(uint8_t *buf, unsigned len);
cairo_status_t loadGIF(FILE *stream);
#endif
#ifdef HAVE_JPEG
cairo_status_t loadJPEGFromBuffer(uint8_t *buf, unsigned len);
cairo_status_t loadJPEG(FILE *stream);
void jpegToARGB(jpeg_decompress_struct* args, uint8_t* data, uint8_t* src, JPEGDecodeL decode);
cairo_status_t decodeJPEGIntoSurface(jpeg_decompress_struct *info);
cairo_status_t decodeJPEGBufferIntoMimeSurface(uint8_t *buf, unsigned len);
cairo_status_t assignDataAsMime(uint8_t *data, int len, const char *mime_type);
#endif
cairo_status_t loadBMPFromBuffer(uint8_t *buf, unsigned len);
cairo_status_t loadBMP(FILE *stream);
CanvasError errorInfo;
void loaded();
cairo_status_t load();
Image();
enum {
DEFAULT
, LOADING
, COMPLETE
} state;
enum data_mode_t {
DATA_IMAGE = 1
, DATA_MIME = 2
} data_mode;
typedef enum {
UNKNOWN
, GIF
, JPEG
, PNG
, SVG
} type;
static type extension(const char *filename);
private:
cairo_surface_t *_surface;
uint8_t *_data = nullptr;
int _data_len;
#ifdef HAVE_RSVG
RsvgHandle *_rsvg;
bool _is_svg;
int _svg_last_width;
int _svg_last_height;
#endif
~Image();
};

View File

@@ -0,0 +1,146 @@
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
#include "ImageData.h"
using namespace v8;
Nan::Persistent<FunctionTemplate> ImageData::constructor;
/*
* Initialize ImageData.
*/
void
ImageData::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {
Nan::HandleScope scope;
// Constructor
Local<FunctionTemplate> ctor = Nan::New<FunctionTemplate>(ImageData::New);
constructor.Reset(ctor);
ctor->InstanceTemplate()->SetInternalFieldCount(1);
ctor->SetClassName(Nan::New("ImageData").ToLocalChecked());
// Prototype
Local<ObjectTemplate> proto = ctor->PrototypeTemplate();
Nan::SetAccessor(proto, Nan::New("width").ToLocalChecked(), GetWidth);
Nan::SetAccessor(proto, Nan::New("height").ToLocalChecked(), GetHeight);
Local<Context> ctx = Nan::GetCurrentContext();
Nan::Set(target, Nan::New("ImageData").ToLocalChecked(), ctor->GetFunction(ctx).ToLocalChecked());
}
/*
* Initialize a new ImageData object.
*/
NAN_METHOD(ImageData::New) {
if (!info.IsConstructCall()) {
return Nan::ThrowTypeError("Class constructors cannot be invoked without 'new'");
}
Local<TypedArray> dataArray;
uint32_t width;
uint32_t height;
int length;
if (info[0]->IsUint32() && info[1]->IsUint32()) {
width = Nan::To<uint32_t>(info[0]).FromMaybe(0);
if (width == 0) {
Nan::ThrowRangeError("The source width is zero.");
return;
}
height = Nan::To<uint32_t>(info[1]).FromMaybe(0);
if (height == 0) {
Nan::ThrowRangeError("The source height is zero.");
return;
}
length = width * height * 4; // ImageData(w, h) constructor assumes 4 BPP; documented.
dataArray = Uint8ClampedArray::New(ArrayBuffer::New(Isolate::GetCurrent(), length), 0, length);
} else if (info[0]->IsUint8ClampedArray() && info[1]->IsUint32()) {
dataArray = info[0].As<Uint8ClampedArray>();
length = dataArray->Length();
if (length == 0) {
Nan::ThrowRangeError("The input data has a zero byte length.");
return;
}
// Don't assert that the ImageData length is a multiple of four because some
// data formats are not 4 BPP.
width = Nan::To<uint32_t>(info[1]).FromMaybe(0);
if (width == 0) {
Nan::ThrowRangeError("The source width is zero.");
return;
}
// Don't assert that the byte length is a multiple of 4 * width, ditto.
if (info[2]->IsUint32()) { // Explicit height given
height = Nan::To<uint32_t>(info[2]).FromMaybe(0);
} else { // Calculate height assuming 4 BPP
int size = length / 4;
height = size / width;
}
} else if (info[0]->IsUint16Array() && info[1]->IsUint32()) { // Intended for RGB16_565 format
dataArray = info[0].As<Uint16Array>();
length = dataArray->Length();
if (length == 0) {
Nan::ThrowRangeError("The input data has a zero byte length.");
return;
}
width = Nan::To<uint32_t>(info[1]).FromMaybe(0);
if (width == 0) {
Nan::ThrowRangeError("The source width is zero.");
return;
}
if (info[2]->IsUint32()) { // Explicit height given
height = Nan::To<uint32_t>(info[2]).FromMaybe(0);
} else { // Calculate height assuming 2 BPP
int size = length / 2;
height = size / width;
}
} else {
Nan::ThrowTypeError("Expected (Uint8ClampedArray, width[, height]), (Uint16Array, width[, height]) or (width, height)");
return;
}
Nan::TypedArrayContents<uint8_t> dataPtr(dataArray);
ImageData *imageData = new ImageData(reinterpret_cast<uint8_t*>(*dataPtr), width, height);
imageData->Wrap(info.This());
Nan::Set(info.This(), Nan::New("data").ToLocalChecked(), dataArray).Check();
info.GetReturnValue().Set(info.This());
}
/*
* Get width.
*/
NAN_GETTER(ImageData::GetWidth) {
if (!ImageData::constructor.Get(info.GetIsolate())->HasInstance(info.This())) {
Nan::ThrowTypeError("Method ImageData.GetWidth called on incompatible receiver");
return;
}
ImageData *imageData = Nan::ObjectWrap::Unwrap<ImageData>(info.This());
info.GetReturnValue().Set(Nan::New<Number>(imageData->width()));
}
/*
* Get height.
*/
NAN_GETTER(ImageData::GetHeight) {
if (!ImageData::constructor.Get(info.GetIsolate())->HasInstance(info.This())) {
Nan::ThrowTypeError("Method ImageData.GetHeight called on incompatible receiver");
return;
}
ImageData *imageData = Nan::ObjectWrap::Unwrap<ImageData>(info.This());
info.GetReturnValue().Set(Nan::New<Number>(imageData->height()));
}

View File

@@ -0,0 +1,27 @@
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
#pragma once
#include <nan.h>
#include <stdint.h> // node < 7 uses libstdc++ on macOS which lacks complete c++11
#include <v8.h>
class ImageData: public Nan::ObjectWrap {
public:
static Nan::Persistent<v8::FunctionTemplate> constructor;
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
static NAN_METHOD(New);
static NAN_GETTER(GetWidth);
static NAN_GETTER(GetHeight);
inline int width() { return _width; }
inline int height() { return _height; }
inline uint8_t *data() { return _data; }
ImageData(uint8_t *data, int width, int height) : _width(width), _height(height), _data(data) {}
private:
int _width;
int _height;
uint8_t *_data;
};

View File

@@ -0,0 +1,167 @@
#pragma once
#include "closure.h"
#include <jpeglib.h>
#include <jerror.h>
/*
* Expanded data destination object for closure output,
* inspired by IJG's jdatadst.c
*/
struct closure_destination_mgr {
jpeg_destination_mgr pub;
JpegClosure* closure;
JOCTET *buffer;
int bufsize;
};
void
init_closure_destination(j_compress_ptr cinfo){
// we really don't have to do anything here
}
boolean
empty_closure_output_buffer(j_compress_ptr cinfo){
Nan::HandleScope scope;
Nan::AsyncResource async("canvas:empty_closure_output_buffer");
closure_destination_mgr *dest = (closure_destination_mgr *) cinfo->dest;
v8::Local<v8::Object> buf = Nan::NewBuffer((char *)dest->buffer, dest->bufsize).ToLocalChecked();
// emit "data"
v8::Local<v8::Value> argv[2] = {
Nan::Null()
, buf
};
dest->closure->cb.Call(sizeof argv / sizeof *argv, argv, &async);
dest->buffer = (JOCTET *)malloc(dest->bufsize);
cinfo->dest->next_output_byte = dest->buffer;
cinfo->dest->free_in_buffer = dest->bufsize;
return true;
}
void
term_closure_destination(j_compress_ptr cinfo){
Nan::HandleScope scope;
Nan::AsyncResource async("canvas:term_closure_destination");
closure_destination_mgr *dest = (closure_destination_mgr *) cinfo->dest;
/* emit remaining data */
v8::Local<v8::Object> buf = Nan::NewBuffer((char *)dest->buffer, dest->bufsize - dest->pub.free_in_buffer).ToLocalChecked();
v8::Local<v8::Value> data_argv[2] = {
Nan::Null()
, buf
};
dest->closure->cb.Call(sizeof data_argv / sizeof *data_argv, data_argv, &async);
// emit "end"
v8::Local<v8::Value> end_argv[2] = {
Nan::Null()
, Nan::Null()
};
dest->closure->cb.Call(sizeof end_argv / sizeof *end_argv, end_argv, &async);
}
void
jpeg_closure_dest(j_compress_ptr cinfo, JpegClosure* closure, int bufsize){
closure_destination_mgr * dest;
/* The destination object is made permanent so that multiple JPEG images
* can be written to the same buffer without re-executing jpeg_mem_dest.
*/
if (cinfo->dest == NULL) { /* first time for this JPEG object? */
cinfo->dest = (struct jpeg_destination_mgr *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
sizeof(closure_destination_mgr));
}
dest = (closure_destination_mgr *) cinfo->dest;
cinfo->dest->init_destination = &init_closure_destination;
cinfo->dest->empty_output_buffer = &empty_closure_output_buffer;
cinfo->dest->term_destination = &term_closure_destination;
dest->closure = closure;
dest->bufsize = bufsize;
dest->buffer = (JOCTET *)malloc(bufsize);
cinfo->dest->next_output_byte = dest->buffer;
cinfo->dest->free_in_buffer = dest->bufsize;
}
void encode_jpeg(jpeg_compress_struct cinfo, cairo_surface_t *surface, int quality, bool progressive, int chromaHSampFactor, int chromaVSampFactor) {
int w = cairo_image_surface_get_width(surface);
int h = cairo_image_surface_get_height(surface);
cinfo.in_color_space = JCS_RGB;
cinfo.input_components = 3;
cinfo.image_width = w;
cinfo.image_height = h;
jpeg_set_defaults(&cinfo);
if (progressive)
jpeg_simple_progression(&cinfo);
jpeg_set_quality(&cinfo, quality, (quality < 25) ? 0 : 1);
cinfo.comp_info[0].h_samp_factor = chromaHSampFactor;
cinfo.comp_info[0].v_samp_factor = chromaVSampFactor;
JSAMPROW slr;
jpeg_start_compress(&cinfo, TRUE);
unsigned char *dst;
unsigned int *src = (unsigned int *)cairo_image_surface_get_data(surface);
int sl = 0;
dst = (unsigned char *)malloc(w * 3);
while (sl < h) {
unsigned char *dp = dst;
int x = 0;
while (x < w) {
dp[0] = (*src >> 16) & 255;
dp[1] = (*src >> 8) & 255;
dp[2] = *src & 255;
src++;
dp += 3;
x++;
}
slr = dst;
jpeg_write_scanlines(&cinfo, &slr, 1);
sl++;
}
free(dst);
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
}
void
write_to_jpeg_stream(cairo_surface_t *surface, int bufsize, JpegClosure* closure) {
jpeg_compress_struct cinfo;
jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
jpeg_closure_dest(&cinfo, closure, bufsize);
encode_jpeg(
cinfo,
surface,
closure->quality,
closure->progressive,
closure->chromaSubsampling,
closure->chromaSubsampling);
}
void
write_to_jpeg_buffer(cairo_surface_t* surface, JpegClosure* closure) {
jpeg_compress_struct cinfo;
jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
cinfo.client_data = closure;
cinfo.dest = closure->jpeg_dest_mgr;
encode_jpeg(
cinfo,
surface,
closure->quality,
closure->progressive,
closure->chromaSubsampling,
closure->chromaSubsampling);
}

292
ccc-tnt-psd2ui-v2.4.x/node_modules/canvas/src/PNG.h generated vendored Normal file
View File

@@ -0,0 +1,292 @@
#pragma once
#include <cairo.h>
#include "closure.h"
#include <cmath> // round
#include <cstdlib>
#include <cstring>
#include <png.h>
#include <pngconf.h>
#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
#define likely(expr) (__builtin_expect (!!(expr), 1))
#define unlikely(expr) (__builtin_expect (!!(expr), 0))
#else
#define likely(expr) (expr)
#define unlikely(expr) (expr)
#endif
static void canvas_png_flush(png_structp png_ptr) {
/* Do nothing; fflush() is said to be just a waste of energy. */
(void) png_ptr; /* Stifle compiler warning */
}
/* Converts native endian xRGB => RGBx bytes */
static void canvas_convert_data_to_bytes(png_structp png, png_row_infop row_info, png_bytep data) {
unsigned int i;
for (i = 0; i < row_info->rowbytes; i += 4) {
uint8_t *b = &data[i];
uint32_t pixel;
memcpy(&pixel, b, sizeof (uint32_t));
b[0] = (pixel & 0xff0000) >> 16;
b[1] = (pixel & 0x00ff00) >> 8;
b[2] = (pixel & 0x0000ff) >> 0;
b[3] = 0;
}
}
/* Unpremultiplies data and converts native endian ARGB => RGBA bytes */
static void canvas_unpremultiply_data(png_structp png, png_row_infop row_info, png_bytep data) {
unsigned int i;
for (i = 0; i < row_info->rowbytes; i += 4) {
uint8_t *b = &data[i];
uint32_t pixel;
uint8_t alpha;
memcpy(&pixel, b, sizeof (uint32_t));
alpha = (pixel & 0xff000000) >> 24;
if (alpha == 0) {
b[0] = b[1] = b[2] = b[3] = 0;
} else {
b[0] = (((pixel & 0xff0000) >> 16) * 255 + alpha / 2) / alpha;
b[1] = (((pixel & 0x00ff00) >> 8) * 255 + alpha / 2) / alpha;
b[2] = (((pixel & 0x0000ff) >> 0) * 255 + alpha / 2) / alpha;
b[3] = alpha;
}
}
}
/* Converts RGB16_565 format data to RGBA32 */
static void canvas_convert_565_to_888(png_structp png, png_row_infop row_info, png_bytep data) {
// Loop in reverse to unpack in-place.
for (ptrdiff_t col = row_info->width - 1; col >= 0; col--) {
uint8_t* src = &data[col * sizeof(uint16_t)];
uint8_t* dst = &data[col * 3];
uint16_t pixel;
memcpy(&pixel, src, sizeof(uint16_t));
// Convert and rescale to the full 0-255 range
// See http://stackoverflow.com/a/29326693
const uint8_t red5 = (pixel & 0xF800) >> 11;
const uint8_t green6 = (pixel & 0x7E0) >> 5;
const uint8_t blue5 = (pixel & 0x001F);
dst[0] = ((red5 * 255 + 15) / 31);
dst[1] = ((green6 * 255 + 31) / 63);
dst[2] = ((blue5 * 255 + 15) / 31);
}
}
struct canvas_png_write_closure_t {
cairo_write_func_t write_func;
PngClosure* closure;
};
#ifdef PNG_SETJMP_SUPPORTED
bool setjmp_wrapper(png_structp png) {
return setjmp(png_jmpbuf(png));
}
#endif
static cairo_status_t canvas_write_png(cairo_surface_t *surface, png_rw_ptr write_func, canvas_png_write_closure_t *closure) {
unsigned int i;
cairo_status_t status = CAIRO_STATUS_SUCCESS;
uint8_t *data;
png_structp png;
png_infop info;
png_bytep *volatile rows = NULL;
png_color_16 white;
int png_color_type;
int bpc;
unsigned int width = cairo_image_surface_get_width(surface);
unsigned int height = cairo_image_surface_get_height(surface);
data = cairo_image_surface_get_data(surface);
if (data == NULL) {
status = CAIRO_STATUS_SURFACE_TYPE_MISMATCH;
return status;
}
cairo_surface_flush(surface);
if (width == 0 || height == 0) {
status = CAIRO_STATUS_WRITE_ERROR;
return status;
}
rows = (png_bytep *) malloc(height * sizeof (png_byte*));
if (unlikely(rows == NULL)) {
status = CAIRO_STATUS_NO_MEMORY;
return status;
}
int stride = cairo_image_surface_get_stride(surface);
for (i = 0; i < height; i++) {
rows[i] = (png_byte *) data + i * stride;
}
#ifdef PNG_USER_MEM_SUPPORTED
png = png_create_write_struct_2(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL, NULL, NULL, NULL);
#else
png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
#endif
if (unlikely(png == NULL)) {
status = CAIRO_STATUS_NO_MEMORY;
free(rows);
return status;
}
info = png_create_info_struct (png);
if (unlikely(info == NULL)) {
status = CAIRO_STATUS_NO_MEMORY;
png_destroy_write_struct(&png, &info);
free(rows);
return status;
}
#ifdef PNG_SETJMP_SUPPORTED
if (setjmp_wrapper(png)) {
png_destroy_write_struct(&png, &info);
free(rows);
return status;
}
#endif
png_set_write_fn(png, closure, write_func, canvas_png_flush);
png_set_compression_level(png, closure->closure->compressionLevel);
png_set_filter(png, 0, closure->closure->filters);
if (closure->closure->resolution != 0) {
uint32_t res = static_cast<uint32_t>(round(static_cast<double>(closure->closure->resolution) * 39.3701));
png_set_pHYs(png, info, res, res, PNG_RESOLUTION_METER);
}
cairo_format_t format = cairo_image_surface_get_format(surface);
switch (format) {
case CAIRO_FORMAT_ARGB32:
bpc = 8;
png_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
break;
#ifdef CAIRO_FORMAT_RGB30
case CAIRO_FORMAT_RGB30:
bpc = 10;
png_color_type = PNG_COLOR_TYPE_RGB;
break;
#endif
case CAIRO_FORMAT_RGB24:
bpc = 8;
png_color_type = PNG_COLOR_TYPE_RGB;
break;
case CAIRO_FORMAT_A8:
bpc = 8;
png_color_type = PNG_COLOR_TYPE_GRAY;
break;
case CAIRO_FORMAT_A1:
bpc = 1;
png_color_type = PNG_COLOR_TYPE_GRAY;
#ifndef WORDS_BIGENDIAN
png_set_packswap(png);
#endif
break;
case CAIRO_FORMAT_RGB16_565:
bpc = 8; // 565 gets upconverted to 888
png_color_type = PNG_COLOR_TYPE_RGB;
break;
case CAIRO_FORMAT_INVALID:
default:
status = CAIRO_STATUS_INVALID_FORMAT;
png_destroy_write_struct(&png, &info);
free(rows);
return status;
}
if ((format == CAIRO_FORMAT_A8 || format == CAIRO_FORMAT_A1) &&
closure->closure->palette != NULL) {
png_color_type = PNG_COLOR_TYPE_PALETTE;
}
png_set_IHDR(png, info, width, height, bpc, png_color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
if (png_color_type == PNG_COLOR_TYPE_PALETTE) {
size_t nColors = closure->closure->nPaletteColors;
uint8_t* colors = closure->closure->palette;
uint8_t backgroundIndex = closure->closure->backgroundIndex;
png_colorp pngPalette = (png_colorp)png_malloc(png, nColors * sizeof(png_colorp));
png_bytep transparency = (png_bytep)png_malloc(png, nColors * sizeof(png_bytep));
for (i = 0; i < nColors; i++) {
pngPalette[i].red = colors[4 * i];
pngPalette[i].green = colors[4 * i + 1];
pngPalette[i].blue = colors[4 * i + 2];
transparency[i] = colors[4 * i + 3];
}
png_set_PLTE(png, info, pngPalette, nColors);
png_set_tRNS(png, info, transparency, nColors, NULL);
png_set_packing(png); // pack pixels
// have libpng free palette and trans:
png_data_freer(png, info, PNG_DESTROY_WILL_FREE_DATA, PNG_FREE_PLTE | PNG_FREE_TRNS);
png_color_16 bkg;
bkg.index = backgroundIndex;
png_set_bKGD(png, info, &bkg);
}
if (png_color_type != PNG_COLOR_TYPE_PALETTE) {
white.gray = (1 << bpc) - 1;
white.red = white.blue = white.green = white.gray;
png_set_bKGD(png, info, &white);
}
/* We have to call png_write_info() before setting up the write
* transformation, since it stores data internally in 'png'
* that is needed for the write transformation functions to work.
*/
png_write_info(png, info);
if (png_color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
png_set_write_user_transform_fn(png, canvas_unpremultiply_data);
} else if (format == CAIRO_FORMAT_RGB16_565) {
png_set_write_user_transform_fn(png, canvas_convert_565_to_888);
} else if (png_color_type == PNG_COLOR_TYPE_RGB) {
png_set_write_user_transform_fn(png, canvas_convert_data_to_bytes);
png_set_filler(png, 0, PNG_FILLER_AFTER);
}
png_write_image(png, rows);
png_write_end(png, info);
png_destroy_write_struct(&png, &info);
free(rows);
return status;
}
static void canvas_stream_write_func(png_structp png, png_bytep data, png_size_t size) {
cairo_status_t status;
struct canvas_png_write_closure_t *png_closure;
png_closure = (struct canvas_png_write_closure_t *) png_get_io_ptr(png);
status = png_closure->write_func(png_closure->closure, data, size);
if (unlikely(status)) {
cairo_status_t *error = (cairo_status_t *) png_get_error_ptr(png);
if (*error == CAIRO_STATUS_SUCCESS) {
*error = status;
}
png_error(png, NULL);
}
}
static cairo_status_t canvas_write_to_png_stream(cairo_surface_t *surface, cairo_write_func_t write_func, PngClosure* closure) {
struct canvas_png_write_closure_t png_closure;
if (cairo_surface_status(surface)) {
return cairo_surface_status(surface);
}
png_closure.write_func = write_func;
png_closure.closure = closure;
return canvas_write_png(surface, canvas_stream_write_func, &png_closure);
}

Some files were not shown because too many files have changed in this diff Show More