diff --git a/README.md b/README.md index f4015d3695..5a56d29548 100755 --- a/README.md +++ b/README.md @@ -153,6 +153,8 @@ List of Definitions * [node_zeromq](https://github.com/JustinTulloss/zeromq.node) (by [Dave McKeown](https://github.com/davemckeown)) * [node-sqlserver](https://github.com/WindowsAzure/node-sqlserver) (by [Boris Yankov](https://github.com/borisyankov)) * [Numeral.js](https://github.com/adamwdraper/Numeral-js) (by [Vincent Bortone](https://github.com/vbortone/)) +* [Parallel.js](https://github.com/adambom/parallel.js) (by [Josh Baldwin](https://github.com/jbaldwin)) +* [PDF.js](https://github.com/mozilla/pdf.js) (by [Josh Baldwin](https://github.com/jbaldwin)) * [Persona](http://www.mozilla.org/en-US/persona) (by [James Frasca](https://github.com/Nycto)) * [PhantomJS](http://phantomjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker)) * [PhoneGap](http://phonegap.com) (by [Boris Yankov](https://github.com/borisyankov)) diff --git a/parallel/parallel-tests.ts b/parallel/parallel-tests.ts new file mode 100644 index 0000000000..e0c9cb7a80 --- /dev/null +++ b/parallel/parallel-tests.ts @@ -0,0 +1,54 @@ +/// + +interface String { + reverse(): string; +} + +var p = new Parallel([1, 2, 3, 4, 5]); +console.log(p.data); + +var p2 = new Parallel('forwards'); + +// Spawn a remote job (we'll see more on how to use then later) +p2.spawn(function (data) { + data = data.reverse(); + + console.log(data); // logs sdrawrof + + return data; +}).then(function (data) { + console.log(data) // logs sdrawrof +}); + +var p3 = new Parallel([0, 1, 2, 3, 4, 5, 6]), + log = function () { console.log(arguments); }; + +// One gotcha: anonymous functions cannot be serialzed +// If you want to do recursion, make sure the function +// is named appropriately +function fib(n: number): number { + return n < 2 ? 1 : fib(n - 1) + fib(n - 2); +}; + +p3.map(fib).then(log); + +var p4 = new Parallel([0, 1, 2, 3, 4, 5, 6, 7, 8]); + +function add(d: number[]) { return d[0] + d[1]; } +function factorial(n: number) { return n < 2 ? 1 : n * factorial(n - 1); } + +p4.require(factorial); + +// Approximate e^10 +p4.map(function (n: number) { return Math.pow(10, n); }).reduce(add).then(log); + +var p5 = new Parallel([1, 2, 3]); + +function dbl(n) { return n * 2; } + +p5.map(dbl).map(dbl).map(dbl).then(function (data) { + console.log(data); // logs [8, 16, 24] +}); + +// Approximate e^10 +p5.map(function (n: number) { return Math.pow(10, n) / factorial(n); }).reduce(add).then(log); diff --git a/parallel/parallel.d.ts b/parallel/parallel.d.ts new file mode 100644 index 0000000000..06c8979e46 --- /dev/null +++ b/parallel/parallel.d.ts @@ -0,0 +1,99 @@ +/* +Copyright(c) 2013 Josh Baldwin https://github.com/jbaldwin/parallel.d.ts + +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. +*/ + +interface ParallelOptions { + + /** + * This is the path to the file eval.js. This is required when running in node, and required for some browsers (IE 10) in order to work around cross-domain restrictions for web workers. Defaults to the same location as parallel.js in node environments, and null in the browser. + **/ + evalPath?: string; + + /** + * The maximum number of permitted worker threads. This will default to 4, or the number of cpus on your computer if you're running node. + **/ + maxWorkers?: number; + + /** + * If webworkers are not available, whether or not to fall back to synchronous processing using setTimeout. Defaults to true. + **/ + synchronous?: boolean; +} + +declare class Parallel { + + /** + * This is the constructor. Use it to new up any parallel jobs. The constructor takes an array of data you want to operate on. This data will be held in memory until you finish your job, and can be accessed via the .data attribute of your job. + * The object returned by the Parallel constructor is meant to be chained, so you can produce a chain of operations on the provided data. + * @param data This is the data you wish to operate on. Will often be an array, but the only restrictions are that your values are serializable as JSON. + * @param opts Some options for your job. + **/ + constructor(data: T, opts?: ParallelOptions); + + /** + * Data + **/ + public data: T; + + /** + * This function will spawn a new process on a worker thread. Pass it the function you want to call. Your function will receive one argument, which is the current data. The value returned from your spawned function will update the current data. + * @param fn A function to execute on a worker thread. Receives the wrapped data as an argument. The value returned will be assigned to the wrapped data. + * @return Parallel instance. + **/ + public spawn(fn: (data: T) => T): Parallel; + + /** + * Map will apply the supplied function to every element in the wrapped data. Parallel will spawn one worker for each array element in the data, or the supplied maxWorkers argument. The values returned will be stored for further processing. + * @param fn A function to apply. Receives the wrapped data as an argument. The value returned will be assigned to the wrapped data. + * @return Parallel instance. + **/ + public map(fn: (data: N) => N): Parallel; + + /** + * Reduce applies an operation to every member of the wrapped data, and returns a scalar value produced by the operation. Use it for combining the results of a map operation, by summing numbers for example. This takes a reducing function, which gets an argument, data, an array of the stored value, and the current element. + * @param fn A function to apply. Receives the stored value and current element as argument. The value returned will be stored as the current value for the next iteration. Finally, the current value will be assigned to current data. + * @return Parallel instance. + **/ + public reduce(fn: (data: N[]) => N): Parallel; + + /** + * The functions given to then are called after the last requested operation has finished. success receives the resulting data object, while fail will receive an error object. + * @param success A function that gets called upon successful completion. Receives the wrapped data as an argument. + * @param fail A function that gets called if the job fails. The function is passed an error object. + * @return Parallel instance. + **/ + public then(success: (data: T) => void, fail?: (e: Error) => void): Parallel; + + /** + * If you have state that you want to share between your main thread and worker threads, this is how. Require takes either a string or a function. A string should point to a file name. NOte that in order to use require with a file name as an argument, you have to provide the evalPath property in the options object. + * @param state Shared state function or js file. + * @return Parallel instance. + **/ + public require(file: string): Parallel; + + /** + * @see require + **/ + public require(fn: Function): Parallel; +} + diff --git a/pdf/pdf-tests.ts b/pdf/pdf-tests.ts new file mode 100644 index 0000000000..30e5c013bf --- /dev/null +++ b/pdf/pdf-tests.ts @@ -0,0 +1,31 @@ +/// + +var pdf: PDFPageProxy; + +// +// Fetch the PDF document from the URL using promises +// +PDFJS.getDocument('helloworld.pdf').then(function (pdf) { + // Using promise to fetch the page + pdf.getPage(1).then(function (page) { + var scale = 1.5; + var viewport = page.getViewport(scale); + + // + // Prepare canvas using PDF page dimensions + // + var canvas = document.getElementById('the-canvas'); + var context = canvas.getContext('2d'); + canvas.height = viewport.height; + canvas.width = viewport.width; + + // + // Render PDF page into canvas context + // + var renderContext = { + canvasContext: context, + viewport: viewport + }; + page.render(renderContext); + }); +}); diff --git a/pdf/pdf.d.ts b/pdf/pdf.d.ts new file mode 100644 index 0000000000..bddfca74fb --- /dev/null +++ b/pdf/pdf.d.ts @@ -0,0 +1,327 @@ +/* +Copyright (c) 2013 Josh Baldwin https://github.com/jbaldwin/pdf.d.ts + +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. +*/ + +interface PDFPromise { + isResolved(): boolean; + isRejected(): boolean; + resolve(value: T): void; + reject(reason: string): void; + then(onResolve: (promise: T) => void, onReject?: (reason: string) => void): PDFPromise; +} + +interface PDFTreeNode { + title: string; + bold: boolean; + italic: boolean; + color: number[]; // [r,g,b] + dest: any; + items: PDFTreeNode[]; +} + +interface PDFInfo { + PDFFormatVersion: string; + IsAcroFormPresent: boolean; + IsXFAPresent: boolean; + [key: string]: any; // return type is string, typescript chokes +} + +interface PDFMetadata { + parse(): void; + get(name: string): string; + has(name: string): boolean; +} + +interface PDFSource { + url?: string; + data?: Uint8Array; + httpHeaders?: any; + password?: string; +} + +interface PDFProgressData { + loaded: number; + total: number; +} + +interface PDFDocumentProxy { + + /** + * Total number of pages the PDF contains. + **/ + numPages(): number; + + /** + * A unique ID to identify a PDF. Not guaranteed to be unique. [jbaldwin: haha what] + **/ + fingerprint(): string; + + /** + * True if embedded document fonts are in use. Will be set during rendering of the pages. + **/ + embeddedFontsUsed(): boolean; + + /** + * @param number The page number to get. The first page is 1. + * @return A promise that is resolved with a PDFPageProxy. + **/ + getPage(number: number): PDFPromise; + + /** + * TODO: return type of Promise + * A promise that is resolved with a lookup table for mapping named destinations to reference numbers. + **/ + getDestinations(): PDFPromise; + + /** + * A promise that is resolved with an array of all the JavaScript strings in the name tree. + **/ + getJavaScript(): PDFPromise; + + /** + * A promise that is resolved with an array that is a tree outline (if it has one) of the PDF. @see PDFTreeNode + **/ + getOutline(): PDFPromise; + + /** + * A promise that is resolved with the info and metadata of the PDF. + **/ + getMetadata(): PDFPromise<{ info: PDFInfo; metadata: PDFMetadata }>; + + /** + * Is the PDF encrypted? + **/ + isEncrypted(): PDFPromise; + + /** + * A promise that is resolved with Uint8Array that has the raw PDF data. + **/ + getData(): PDFPromise; + + /** + * TODO: return type of Promise + * A promise that is resolved when the document's data is loaded. + **/ + dataLoaded(): PDFPromise; + + /** + * + **/ + destroy(): void; +} + +interface PDFRef { + num: number; + gen: any; // todo +} + +interface PDFPageViewportOptions { + viewBox: any; + scale: number; + rotation: number; + offsetX: number; + offsetY: number; + dontFlip: boolean; +} + +interface PDFPageViewport { + width: number; + height: number; + fontScale: number; + transforms: number[]; + + clone(options: PDFPageViewportOptions): PDFPageViewport; + convertToViewportPoint(): number[]; // [x, y] + convertToViewportRectangle(): number[]; // [x1, y1, x2, y2] + convertToPdfPoint(): number[]; // [x, y] +} + +interface PDFAnnotationData { + subtype: string; + rect: number[]; // [x1, y1, x2, y2] + annotationFlags: any; // todo + color: number[]; // [r,g,b] + borderWidth: number; + hasAppearance: boolean; +} + +interface PDFAnnotations { + getData(): PDFAnnotationData; + hasHtml(): boolean; // always false + getHtmlElement(commonOjbs): HTMLElement; // throw new NotImplementedException() + getEmptyContainer(tagName: string, rect: number[]): HTMLElement; // deprecated + isViewable(): boolean; + loadResources(keys): PDFPromise; + getOperatorList(evaluator): PDFPromise; + // ... todo +} + +interface PDFRenderTextLayer { + beginLayout(): void; + endLayout(): void; + appendText(): void; +} + +interface PDFRenderImageLayer { + beginLayout(): void; + endLayout(): void; + appendImage(): void; +} + +interface PDFRenderParams { + canvasContext: CanvasRenderingContext2D; + textLayer?: PDFRenderTextLayer; + imageLayer?: PDFRenderImageLayer; + continueCallback?: (_continue: () => void) => void; +} + +/** +* RenderTask is basically a promise but adds a cancel function to termiate it. +**/ +interface PDFRenderTask extends PDFPromise { + + /** + * Cancel the rendering task. If the task is currently rendering it will not be cancelled until graphics pauses with a timeout. The promise that this object extends will resolve when cancelled. + **/ + cancel(): void; +} + +interface PDFPageProxy { + + /** + * Page number of the page. First page is 1. + **/ + pageNumber(): number; + + /** + * The number of degrees the page is rotated clockwise. + **/ + rotate(): number; + + /** + * The reference that points to this page. + **/ + ref(): PDFRef; + + /** + * @return An array of the visible portion of the PDF page in the user space units - [x1, y1, x2, y2]. + **/ + view(): number[]; + + /** + * @param scale The desired scale of the viewport. + * @param rotate Degrees to rotate the viewport. If omitted this defaults to the page rotation. + * @return + **/ + getViewport(scale: number, rotate?: number): PDFPageViewport; + + /** + * A promise that is resolved with an array of the annotation objects. + **/ + getAnnotations(): PDFPromise; + + /** + * Begins the process of rendering a page to the desired context. + * @param params Rendering options. + * @return An extended promise that is resolved when the page finishes rendering. + **/ + render(params: PDFRenderParams): PDFRenderTask; + + /** + * A promise that is resolved with the string that is the text content frm the page. + **/ + getTextContext(): PDFPromise; + + /** + * marked as future feature + **/ + //getOperationList(): PDFPromise<>; + + /** + * Destroyes resources allocated by the page. + **/ + destroy(): void; +} + +/** +* A PDF document and page is built of many objects. E.g. there are objects for fonts, images, rendering code and such. These objects might get processed inside of a worker. The `PDFObjects` implements some basic functions to manage these objects. +**/ +interface PDFObjects { + get(objId, callback?): any; + resolve(objId, data); + isResolved(objId): boolean; + hasData(objId): boolean; + getData(objId): any; + clear(): void; +} + +interface PDFJSStatic { + + /** + * The maximum allowed image size in total pixels e.g. width * height. Images above this value will not be drawn. Use -1 for no limit. + **/ + maxImageSize: number; + + /** + * By default fonts are converted to OpenType fonts and loaded via font face rules. If disabled, the font will be rendered using a built in font renderer that constructs the glyphs with primitive path commands. + **/ + disableFontFace: boolean; + + /** + * This is the main entry point for loading a PDF and interacting with it. + * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR) + * is used, which means it must follow the same origin rules that any XHR does + * e.g. No corss domain requests without CORS. + * @param source + * @param pdfDataRangeTransport Used if you want to manually server range requests for data in the PDF. @ee viewer.js for an example of pdfDataRangeTransport's interface. + * @param passwordCallback Used to request a password if wrong or no password was provided. The callback receives two parameters: function that needs to be called with new password and the reason. + * @param progressCallback Progress callback. + * @return A promise that is resolved with PDFDocumentProxy object. + **/ + getDocument( + source: string, + pdfDataRangeTransport?, + passwordCallback?: (fn: (password: string) => void, reason: string) => string, + progressCallback?: (progressData: PDFProgressData) => void) + : PDFPromise; + + getDocument( + source: Uint8Array, + pdfDataRangeTransport?, + passwordCallback?: (fn: (password: string) => void, reason: string) => string, + progressCallback?: (progressData: PDFProgressData) => void) + : PDFPromise; + + getDocument( + source: PDFSource, + pdfDataRangeTransport?, + passwordCallback?: (fn: (password: string) => void, reason: string) => string, + progressCallback?: (progressData: PDFProgressData) => void) + : PDFPromise; +} + +declare var PDFJS: PDFJSStatic; + +declare module "PDFJS" { + export = PDFJS; +}