From cba49c0fab400a6d1ce2d3d064ad37d7feb47cc5 Mon Sep 17 00:00:00 2001 From: Thomas Bluemel Date: Thu, 17 Sep 2015 20:27:54 -0600 Subject: [PATCH] Initial commit. --- LICENSE | 21 + README.md | 3 + rtf.js | 1663 +++++++++++++++++++++++++++++ samples/jquery.binarytransport.js | 50 + samples/jquery.svg.css | 10 + samples/jquery.svg.min.js | 6 + samples/rtf.html | 156 +++ samples/rtf.js.wmf | Bin 0 -> 51562 bytes samples/simple1.rtf | Bin 0 -> 260 bytes samples/simple2.rtf | Bin 0 -> 342 bytes samples/simple3.rtf | Bin 0 -> 474 bytes samples/simplepict.rtf | 1418 ++++++++++++++++++++++++ samples/simplepng.rtf | 26 + samples/simplepngbin.rtf | Bin 0 -> 1415 bytes samples/wmf.html | 147 +++ wmf.js | 836 +++++++++++++++ 16 files changed, 4336 insertions(+) create mode 100644 LICENSE create mode 100644 README.md create mode 100644 rtf.js create mode 100644 samples/jquery.binarytransport.js create mode 100644 samples/jquery.svg.css create mode 100644 samples/jquery.svg.min.js create mode 100644 samples/rtf.html create mode 100644 samples/rtf.js.wmf create mode 100644 samples/simple1.rtf create mode 100644 samples/simple2.rtf create mode 100644 samples/simple3.rtf create mode 100644 samples/simplepict.rtf create mode 100644 samples/simplepng.rtf create mode 100644 samples/simplepngbin.rtf create mode 100644 samples/wmf.html create mode 100644 wmf.js diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0a42541 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Thomas Bluemel + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..4ef74c2 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# rtf.js +Render RTF documents in HTML. + diff --git a/rtf.js b/rtf.js new file mode 100644 index 0000000..5b924d0 --- /dev/null +++ b/rtf.js @@ -0,0 +1,1663 @@ +/* + +The MIT License (MIT) + +Copyright (c) 2015 Thomas Bluemel + +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. + +*/ + +if (typeof RTFJS === "undefined") { + (typeof window !== "undefined" ? window : this).RTFJS = { + Error: function(message) { + this.message = message; + }, + _A: "A".charCodeAt(0), + _a: "a".charCodeAt(0), + _F: "F".charCodeAt(0), + _f: "f".charCodeAt(0), + _Z: "Z".charCodeAt(0), + _z: "z".charCodeAt(0), + _0: "0".charCodeAt(0), + _9: "9".charCodeAt(0), + + JUSTIFICATION: { + LEFT: "left", + CENTER: "center", + RIGHT: "right", + JUSTIFY: "justify" + }, + BREAKTYPE: { + NONE: "none", + COL: "col", // TODO: ??? + EVEN: "even", + ODD: "odd", + PAGE: "page" + }, + PAGENUMBER: { + DECIMAL: "decimal", + UROM: "urom", // TODO: ??? + LROM: "lrom", // TODO: ??? + ULTR: "ultr", // TODO: ??? + LLTR: "lltr" // TODO: ??? + }, + UNDERLINE: { + NONE: "none", + CONTINUOUS: "continuous", + DOTTED: "dotted", + DASHED: "dashed", + DASHDOTTED: "dashdotted", + DASHDOTDOTTED:" dashdotdotted", + DOUBLE: "double", + HEAVYWAVE: "heavywave", + LONGDASHED: "longdashed", + THICK: "thick", + THICKDOTTED: "thickdotted", + THICKDASHED: "thickdashed", + THICKDASHDOTTED: "thickdashdotted", + THICKDASHDOTDOTTED: "thickdashdotdotted", + THICKLONGDASH: "thicklongdash", + DOUBLEWAVE: "doublewave", + WORD: "word", + WAVE: "wave" + }, + FONTPITCH: { + DEFAULT: 0, + FIXED: 1, + VARIABLE: 2 + }, + + _isalpha: function(str) { + var len = str.length; + for (var i = 0; i < len; i++) { + var ch = str.charCodeAt(i); + if (!((ch >= this._A && ch <= this._Z) || + (ch >= this._a && ch <= this._z))) { + return false; + } + } + return len > 0; + }, + _isdigit: function(str) { + var len = str.length; + for (var i = 0; i < len; i++) { + var ch = str.charCodeAt(i); + if (ch < this._0 || ch > this._9) + return false; + } + return len > 0; + }, + _parseHex: function(str) { + var len = str.length; + for (var i = 0; i < len; i++) { + var ch = str.charCodeAt(i); + if (!((ch >= this._0 && ch <= this._9) || + (ch >= this._a && ch <= this._f) || + (ch >= this._A && ch <= this._F))) { + return NaN + } + } + if (len > 0) + return parseInt(str, 16); + return NaN; + }, + _blobToBinary: function(blob) { + var view = new Uint8Array(blob); + var ret = ""; + var len = view.length; + for (var i = 0; i < len; i++) + ret += String.fromCharCode(view[i]); + return ret; + }, + _hexToBlob: function(str) { + var len = str.length; + var buf = new ArrayBuffer(Math.floor(len-- / 2)); + var view = new Uint8Array(buf); + var d = 0; + for (var i = 0; i < len; i += 2) { + var val = this._parseHex(str.substr(i, 2)); + if (isNaN(val)) + return null; + view[d++] = val; + } + return buf; + }, + _hexToBinary: function(str) { + var bin = "" + var len = str.length - 1; + for (var i = 0; i < len; i += 2) { + var val = this._parseHex(str.substr(i, 2)); + if (isNaN(val)) + return null; + bin += String.fromCharCode(val); + } + return bin; + }, + + _charsetMap: { + "0": "windows-1252", + // TODO + }, + _mapCharset: function(idx) { + return this._charsetMap[idx.toString()]; + }, + + _colorThemeMap: { + // TODO + maindarkone: null, + mainlightone: null, + maindarktwo: null, + mainlighttwo: null, + accentone: null, + accenttwo: null, + accentthree: null, + accentfour: null, + accentfive: null, + accentsix: null, + hyperlink: null, + followedhyperlink: null, + backgroundone: null, + textone: null, + backgroundtwo: null, + texttwo: null, + }, + _mapColorTheme: function(name) { + return this.__colorThemeMap[name]; + }, + _colorToStr: function(color) { + return "rgb(" + color.r + "," + color.g + "," + color.b + ")"; + }, + _twipsToPt: function(twips) { + return Math.floor(twips / 20); + } + }; +} + +RTFJS.RenderChp = function(chp) { + this._chp = chp; +}; + +RTFJS.RenderChp.prototype.apply = function(doc, el) { + var chp = this._chp; + if (chp.bold) + el.css("font-weight", "bold"); + if (chp.italic) + el.css("font-style", "italic"); + + var deco = []; + if (chp.underline != RTFJS.UNDERLINE.NONE) + deco.push("underline"); + if (chp.strikethrough || chp.dblstrikethrough) + deco.push("line-through"); + + if (deco.length > 0) + el.css("text-decoration-line", deco.join(" ")); + if (chp.colorindex != 0) { + var color = doc._lookupColor(chp.colorindex); + if (color != null) + el.css("color", RTFJS._colorToStr(color)); + } + el.css("font-size", Math.floor(chp.fontsize / 2) + "pt"); +}; + +RTFJS.RenderPap = function(pap) { + this._pap = pap; +}; + +RTFJS.RenderPap.prototype.apply = function(doc, el, rchp) { + var pap = this._pap; + if (pap.spacebefore != 0) + el.css("margin-top", RTFJS._twipsToPt(pap.spacebefore) + "pt"); + else + el.css("margin-top", ""); + if (pap.spaceafter != 0) + el.css("margin-bottom", RTFJS._twipsToPt(pap.spaceafter) + "pt"); + else + el.css("margin-bottom", ""); + if (rchp != null) + el.css("min-height", Math.floor(rchp._chp.fontsize / 2) + "pt"); +}; + +RTFJS.Renderer = function(doc) { + this._doc = doc; + this._ins = []; + this._dom = null; + + this._curRChp = null; + this._curRPap = null; + this._curpar = null; +}; + +RTFJS.Renderer.prototype.addIns = function(ins) { + this._ins.push(ins); +}; + +RTFJS.Renderer.prototype._appendToPar = function(el) { + if (this._curpar == null) + this.startPar(); + this._curpar.append(el); +}; + +RTFJS.Renderer.prototype.startPar = function() { + this._curpar = $("
"); + if (this._curRPap != null) + this._curRPap.apply(this._doc, this._curpar, this._curRChp); + this._dom.push(this._curpar); +}; + +RTFJS.Renderer.prototype.lineBreak = function() { + this._appendToPar($("
")); +}; + +RTFJS.Renderer.prototype.setChp = function(rchp) { + this._curRChp = rchp; +}; + +RTFJS.Renderer.prototype.setPap = function(rpap) { + this._curRPap = rpap; + if (this._curpar != null) + this._curRPap.apply(this._doc, this._curpar); +}; + +RTFJS.Renderer.prototype.appendElement = function(element) { + this._appendToPar(element); +}; + +RTFJS.Renderer.prototype.buildRenderedPicture = function(element) { + if (element == null) + element = $("").text("[failed to render image]") + return element; +}; + +RTFJS.Renderer.prototype.renderedPicture = function(element) { + this._appendToPar(this.buildRenderedPicture(element)); +}; + +RTFJS.Renderer.prototype.buildPicture = function(mime, data) { + if (data != null) { + return $("", { + src: "data:" + mime + ";base64," + btoa(data) + }); + } else { + var err = "image type not supported"; + if (typeof mime === "string" && mime != "") + err = mime; + return $("").text("[" + mime + "]"); + } +}; + +RTFJS.Renderer.prototype.picture = function(mime, data) { + this._appendToPar(this.buildPicture(mime, data)); +}; + +RTFJS.Renderer.prototype.buildDom = function() { + if (this._dom != null) + return this._dom; + + this._dom = []; + + this._curRChp = null; + this._curRPap = null; + this._curpar = null; + + var len = this._ins.length; + for (var i = 0; i < len; i++) { + var ins = this._ins[i]; + if (typeof ins === "string") { + var span = $(""); + if (this._curRChp != null) + this._curRChp.apply(this._doc, span); + this._appendToPar(span.text(ins)); + } else { + ins.call(this); + } + } + return this._dom; +}; + +RTFJS.Document = function(blob, settings) { + this._settings = settings || {}; + this._meta = {}; + this._fonts = []; + this._colors = []; + this._autoColor = null; + this._stylesheets = []; + this._renderer = new RTFJS.Renderer(this); + this.parse(blob); +}; + +RTFJS.Document.prototype._lookupColor = function(idx) { + if (idx == 0) { + if (this._autoColor == null) + return null; + return this._colors[this._autoColor]; + } + if (idx < 0 || idx >= this._colors.length) + throw new RTFJS.Error("Invalid color index"); + return this._colors[idx]; +}; + +RTFJS.Document.prototype.metadata = function() { + return this._meta; +} + +RTFJS.Document.prototype.render = function() { + return this._renderer.buildDom(); +}; + +RTFJS.Document.prototype.parse = function(blob) { + if (!('TextDecoder' in window)) + throw new RTFJS.Error("Encoding API required"); + + var inst = this; + + var parseKeyword, processKeyword, appendText, parseLoop; + + var Chp = function(parent) { + if (parent != null) { + this.bold = parent.bold; + this.underline = parent.underline; + this.italic = parent.italic; + this.strikethrough = parent.strikethrough; + this.dblstrikethrough = parent.dblstrikethrough; + this.colorindex = parent.colorindex; + this.fontsize = parent.fontsize; + } else { + this.bold = false; + this.underline = RTFJS.UNDERLINE.NONE; + this.italic = false; + this.strikethrough = false; + this.dblstrikethrough = false; + this.colorindex = 0; + this.fontsize = 12; + } + }; + + var Pap = function(parent) { + if (parent != null) { + this.indent = { + left: parent.indent.left, + right: parent.indent.right, + firstline: parent.indent.firstline + }; + this.justification = parent.justification; + this.spacebefore = parent.spacebefore; + this.spaceafter = parent.spaceafter; + } else { + this.indent = { + left: 0, + right: 0, + firstline: 0 + }; + this.justification = RTFJS.JUSTIFICATION.LEFT; + this.spacebefore = 0; + this.spaceafter = 0; + } + }; + + var Sep = function(parent) { + if (parent != null) { + this.columns = parent.columns; + this.breaktype = parent.breaktype; + this.pagenumber = { + x: parent.pagenumber.x, + y: parent.pagenumber.y + }; + this.pagenumberformat = parent.pagenumberformat; + } else { + this.columns = 0; + this.breaktype = RTFJS.BREAKTYPE.NONE; + this.pagenumber = { + x: 0, + y: 0, + }; + this.pagenumberformat = RTFJS.PAGENUMBER.DECIMAL; + } + }; + + var Dop = function(parent) { + if (parent != null) { + this.width = parent.width; + this.height = parent.height; + this.margin = { + left: parent.margin.left, + top: parent.margin.top, + right: parent.margin.right, + bottom: parent.margin.bottom + }; + this.pagenumberstart = parent.pagenumberstart; + this.facingpages = parent.facingpages; + this.landscape = parent.landscape; + } else { + this.width = 0; + this.height = 0; + this.margin = { + left: 0, + top: 0, + right: 0, + bottom: 0 + }; + this.pagenumberstart = 0; + this.facingpages = false; + this.landscape = false; + } + }; + + var State = function(parent) { + this.parent = parent; + this.first = true; + this.skipchars = 0; + this.bindata = 0; + if (parent != null) { + this.chp = new Chp(parent.chp); + this.pap = new Pap(parent.pap); + this.sep = new Sep(parent.sep); + this.dop = new Dop(parent.dop); + this.destination = parent.destination; + this.skipunknowndestination = parent.skipunknowndestination; + this.skipdestination = parent.skipdestination; + this.ucn = parent.ucn; + } else { + this.chp = new Chp(null); + this.pap = new Pap(null); + this.sep = new Sep(null); + this.dop = new Dop(null); + this.destination = null; + this.skipunknowndestination = false; + this.skipdestination = false; + this.ucn = 1; + } + }; + + var parser = { + data: new Uint8Array(blob), + pos: 0, + state: null, + version: null, + text: "", + eof: function() { + return this.pos >= this.data.length; + }, + readChar: function() { + if (this.pos < this.data.length) { + return String.fromCharCode(this.data[this.pos++]); + } + + throw new RTFJS.Error("Unexpected end of file"); + }, + unreadChar: function() { + if (this.pos > 0) + this.pos--; + else + throw new RTFJS.Error("Already at beginning of file"); + }, + readBlob: function(cnt) { + if (this.pos + cnt > this.data.length) + throw new RTFJS.Error("Cannot read binary data: too long"); + var buf = new ArrayBuffer(cnt); + var view = new Uint8Array(buf); + for (var i = 0; i < cnt; i++) + view[i] = this.data[this.pos + i]; + return buf; + } + }; + + var findParentDestination = function(dest) { + var state = parser.state; + while (state != null) { + if (state.destination == null) + break; + if (state.destination._name == dest) + return state.destination; + state = state.parent; + } + console.log("findParentDestination() did not find destination " + dest); + }; + + var DestinationBase = function(name) { + this._name = name; + }; + + var DestinationTextBase = function(name) { + this._name = name; + this.text = ""; + }; + DestinationTextBase.prototype.appendText = function(text) { + this.text += text; + }; + + var rtfDestination = function() { + var cls = function(name, param) { + if (parser.version != null) + throw new RTFJS.Error("Unexpected rtf destination"); + DestinationBase.call(this, name); + if (param != 1) + throw new RTFJS.Error("Unsupported rtf version"); + parser.version = param; + + this._metadata = {}; + }; + cls.prototype = Object.create(DestinationBase.prototype); + cls.prototype.appendText = function(text) { + console.log("[rtf] output: " + text); + inst._renderer.addIns(text); + } + cls.prototype.sub = function() { + console.log("[rtf].sub()"); + } + + var _addInsHandler = function(func) { + return function(param) { + inst._renderer.addIns(func); + }; + }; + var _addFormatIns = function(ptype, props) { + switch (ptype) { + case "chp": + var rchp = new RTFJS.RenderChp(new Chp(props)); + inst._renderer.addIns(function() { + this.setChp(rchp); + }); + break; + case "pap": + var rpap = new RTFJS.RenderPap(new Pap(props)); + inst._renderer.addIns(function() { + this.setPap(rpap); + }); + break; + } + }; + var _genericFormatSetNoParam = function(ptype, prop, val) { + return function(param) { + var props = parser.state[ptype]; + props[prop] = val; + console.log("[rtf] state." + ptype + "." + prop + " = " + props[prop].toString()); + _addFormatIns(ptype, props); + }; + }; + var _genericFormatOnOff = function(ptype, prop, onval, offval) { + return function(param) { + var props = parser.state[ptype]; + props[prop] = (param == null || param != 0) ? (onval != null ? onval : true) : (offval != null ? offval : false); + console.log("[rtf] state." + ptype + "." + prop + " = " + props[prop].toString()); + _addFormatIns(ptype, props); + }; + }; + var _genericFormatSetVal = function(ptype, prop, defaultval) { + return function(param) { + var props = parser.state[ptype]; + props[prop] = (param == null) ? defaultval : param; + console.log("[rtf] state." + ptype + "." + prop + " = " + props[prop].toString()); + _addFormatIns(ptype, props); + }; + }; + var _genericFormatSetValRequired = function(ptype, prop) { + return function(param) { + if (param == null) + throw new RTFJS.Error("Keyword without required param"); + var props = parser.state[ptype]; + props[prop] = param; + console.log("[rtf] state." + ptype + "." + prop + " = " + props[prop].toString()); + _addFormatIns(ptype, props); + }; + }; + var _genericFormatSetMemberVal = function(ptype, prop, member, defaultval) { + return function(param) { + var props = parser.state[ptype]; + var members = props[prop]; + members[member] = (param == null) ? defaultval : param; + console.log("[rtf] state." + ptype + "." + prop + "." + member + " = " + members[member].toString()); + _addFormatIns(ptype, props); + }; + }; + var _charFormatHandlers = { + sectd: function(param) { + console.log("[rtf] reset to section defaults"); + parser.state.sep = new Sep(null); + }, + plain: function(param) { + console.log("[rtf] reset to character defaults"); + parser.state.chp = new Chp(null); + }, + pard: function(param) { + console.log("[rtf] reset to paragraph defaults"); + parser.state.pap = new Pap(null); + }, + b: _genericFormatOnOff("chp", "bold"), + i: _genericFormatOnOff("chp", "italic"), + cf: _genericFormatSetValRequired("chp", "colorindex"), + fs: _genericFormatSetValRequired("chp", "fontsize"), + strike: _genericFormatOnOff("chp", "strikethrough"), + striked: _genericFormatOnOff("chp", "dblstrikethrough"), // TODO: reject param == null in this particular case? + ul: _genericFormatOnOff("chp", "underline", RTFJS.UNDERLINE.CONTINUOUS, RTFJS.UNDERLINE.NONE), + uld: _genericFormatOnOff("chp", "underline", RTFJS.UNDERLINE.DOTTED, RTFJS.UNDERLINE.NONE), + uldash: _genericFormatOnOff("chp", "underline", RTFJS.UNDERLINE.DASHED, RTFJS.UNDERLINE.NONE), + uldashd: _genericFormatOnOff("chp", "underline", RTFJS.UNDERLINE.DASHDOTTED, RTFJS.UNDERLINE.NONE), + uldashdd: _genericFormatOnOff("chp", "underline", RTFJS.UNDERLINE.DASHDOTDOTTED, RTFJS.UNDERLINE.NONE), + uldb: _genericFormatOnOff("chp", "underline", RTFJS.UNDERLINE.DOUBLE, RTFJS.UNDERLINE.NONE), + ulhwave: _genericFormatOnOff("chp", "underline", RTFJS.UNDERLINE.HEAVYWAVE, RTFJS.UNDERLINE.NONE), + ulldash: _genericFormatOnOff("chp", "underline", RTFJS.UNDERLINE.LONGDASHED, RTFJS.UNDERLINE.NONE), + ulnone: _genericFormatSetNoParam("chp", "underline", RTFJS.UNDERLINE.NONE), + ulth: _genericFormatOnOff("chp", "underline", RTFJS.UNDERLINE.THICK, RTFJS.UNDERLINE.NONE), + ulthd: _genericFormatOnOff("chp", "underline", RTFJS.UNDERLINE.THICKDOTTED, RTFJS.UNDERLINE.NONE), + ulthdash: _genericFormatOnOff("chp", "underline", RTFJS.UNDERLINE.THICKDASHED, RTFJS.UNDERLINE.NONE), + ulthdashd: _genericFormatOnOff("chp", "underline", RTFJS.UNDERLINE.THICKDASHDOTTED, RTFJS.UNDERLINE.NONE), + ulthdashdd: _genericFormatOnOff("chp", "underline", RTFJS.UNDERLINE.THICKDASHDOTDOTTED, RTFJS.UNDERLINE.NONE), + ululdbwave: _genericFormatOnOff("chp", "underline", RTFJS.UNDERLINE.DOUBLEWAVE, RTFJS.UNDERLINE.NONE), + ulw: _genericFormatOnOff("chp", "underline", RTFJS.UNDERLINE.WORD, RTFJS.UNDERLINE.NONE), + ulwave: _genericFormatOnOff("chp", "underline", RTFJS.UNDERLINE.WAVE, RTFJS.UNDERLINE.NONE), + li: _genericFormatSetMemberVal("pap", "indent", "left", 0), + ri: _genericFormatSetMemberVal("pap", "indent", "right", 0), + fi: _genericFormatSetMemberVal("pap", "indent", "firstline", 0), + sa: _genericFormatSetValRequired("pap", "spaceafter"), + sb: _genericFormatSetValRequired("pap", "spacebefore"), + cols: _genericFormatSetVal("sep", "columns", 0), + sbknone: _genericFormatSetNoParam("sep", "breaktype", RTFJS.BREAKTYPE.NONE), + sbkcol: _genericFormatSetNoParam("sep", "breaktype", RTFJS.BREAKTYPE.COL), + sbkeven: _genericFormatSetNoParam("sep", "breaktype", RTFJS.BREAKTYPE.EVEN), + sbkodd: _genericFormatSetNoParam("sep", "breaktype", RTFJS.BREAKTYPE.ODD), + sbkpage: _genericFormatSetNoParam("sep", "breaktype", RTFJS.BREAKTYPE.PAGE), + pgnx: _genericFormatSetMemberVal("sep", "pagenumber", "x", 0), + pgny: _genericFormatSetMemberVal("sep", "pagenumber", "y", 0), + pgndec: _genericFormatSetNoParam("sep", "pagenumberformat", RTFJS.PAGENUMBER.DECIMAL), + pgnucrm: _genericFormatSetNoParam("sep", "pagenumberformat", RTFJS.PAGENUMBER.UROM), + pgnlcrm: _genericFormatSetNoParam("sep", "pagenumberformat", RTFJS.PAGENUMBER.LROM), + pgnucltr: _genericFormatSetNoParam("sep", "pagenumberformat", RTFJS.PAGENUMBER.ULTR), + pgnlcltr: _genericFormatSetNoParam("sep", "pagenumberformat", RTFJS.PAGENUMBER.LLTR), + qc: _genericFormatSetNoParam("pap", "justification", RTFJS.JUSTIFICATION.CENTER), + ql: _genericFormatSetNoParam("pap", "justification", RTFJS.JUSTIFICATION.LEFT), + qr: _genericFormatSetNoParam("pap", "justification", RTFJS.JUSTIFICATION.RIGHT), + qj: _genericFormatSetNoParam("pap", "justification", RTFJS.JUSTIFICATION.JUSTIFY), + paperw: _genericFormatSetVal("dop", "width", 12240), + paperh: _genericFormatSetVal("dop", "height", 15480), + margl: _genericFormatSetMemberVal("dop", "margin", "left", 1800), + margr: _genericFormatSetMemberVal("dop", "margin", "right", 1800), + margt: _genericFormatSetMemberVal("dop", "margin", "top", 1440), + margb: _genericFormatSetMemberVal("dop", "margin", "bottom", 1440), + pgnstart: _genericFormatSetVal("dop", "pagenumberstart", 1), + facingp: _genericFormatSetNoParam("dop", "facingpages", true), + landscape: _genericFormatSetNoParam("dop", "landscape", true), + par: _addInsHandler(function() { + this.startPar(); + }), + line: _addInsHandler(function() { + this.lineBreak(); + }), + }; + cls.prototype.handleKeyword = function(keyword, param) { + var handler = _charFormatHandlers[keyword]; + if (handler != null) { + handler(param); + return true; + } + //console.log("[rtf] unhandled keyword: " + keyword + " param: " + param); + return false; + } + cls.prototype.apply = function() { + console.log("[rtf] apply()"); + for (var prop in this._metadata) + inst._meta[prop] = this._metadata[prop]; + delete this._metadata; + } + cls.prototype.setMetadata = function(prop, val) { + this._metadata[prop] = val; + } + return cls; + }; + + var genericPropertyDestination = function(parentdest, metaprop) { + var cls = function(name) { + DestinationTextBase.call(this, name); + }; + cls.prototype = Object.create(DestinationTextBase.prototype); + cls.prototype.apply = function() { + var dest = findParentDestination(parentdest); + if (dest == null) + throw new RTFJS.Error("Destination " + this._name + " must be within " + parentdest + " destination"); + if (dest.setMetadata == null) + throw new RTFJS.Error("Destination " + parentdest + " does not accept meta data"); + dest.setMetadata(metaprop, this.text); + }; + return cls; + }; + + var infoDestination = function() { + var cls = function(name) { + DestinationBase.call(this, name); + this._metadata = {}; + }; + cls.prototype.apply = function() { + for (var prop in this._metadata) + inst._meta[prop] = this._metadata[prop]; + delete this._metadata; + } + cls.prototype.setMetadata = function(prop, val) { + this._metadata[prop] = val; + } + return cls; + }; + + var metaPropertyDestination = function(metaprop) { + var cls = function(name) { + DestinationTextBase.call(this, name); + }; + cls.prototype = Object.create(DestinationTextBase.prototype); + cls.prototype.apply = function() { + var info = findParentDestination("info"); + if (info == null) + throw new RTFJS.Error("Destination " + this._name + " must be within info destination"); + info.setMetadata(metaprop, this.text); + }; + return cls; + }; + + var metaPropertyTimeDestination = function(metaprop) { + var cls = function(name) { + DestinationBase.call(this, name); + this._yr = null; + this._mo = null; + this._dy = null; + this._hr = null; + this._min = null; + this._sec = null; + }; + cls.prototype.handleKeyword = function(keyword, param) { + switch (keyword) { + case "yr": + this._yr = param; + break; + case "mo": + this._mo = param; + break; + case "dy": + this._dy = param; + break; + case "hr": + this._hr = param; + break; + case "min": + this._min = param; + break; + case "sec": + this._sec = param; + break; + default: + return false; + } + + if (param == null) + throw new RTFJS.Error("No param found for keyword " + keyword); + return true; + }; + cls.prototype.apply = function() { + var info = findParentDestination("info"); + if (info == null) + throw new RTFJS.Error("Destination " + this._name + " must be within info destination"); + var date = new Date( + this._yr != null ? this._yr : 1970, + this._mo != null ? this._mo : 1, + this._dy != null ? this._dy : 1, + this._hr != null ? this._hr : 0, + this._min != null ? this._min : 0, + this._sec != null ? this._sec : 0, + 0); + info.setMetadata(metaprop, date); + }; + return cls; + }; + + var fonttblDestinationSub = function() { + var cls = function(fonttbl) { + DestinationBase.call(this, "fonttbl:sub"); + this._fonttbl = fonttbl; + this.index = null; + this.fontname = null; + this.altfontname = null; + this.family = null; + this.pitch = RTFJS.FONTPITCH.DEFAULT; + this.bias = 0; + this.charset = null; + }; + cls.prototype.handleKeyword = function(keyword, param) { + switch (keyword) { + case "f": + this.index = param; + return true; + case "fnil": + return true; + case "froman": + case "fswiss": + case "fmodern": + case "fscript": + case "fdecor": + case "ftech": + case "fbidi": + this.family = keyword.slice(1); + return true; + case "fprq": + switch (param) { + case 0: + this.pitch = RTFJS.FONTPITCH.DEFAULT; + break; + case 1: + this.pitch = RTFJS.FONTPITCH.FIXED; + break; + case 2: + this.pitch = RTFJS.FONTPITCH.VARIABLE; + break; + } + return true; + case "fbias": + if (param != null) + this.bias = param; + return true; + case "fcharset": + if (param != null) { + this.charset = RTFJS._mapCharset(param); + if (this.charset == null) + console.log("Unknown font charset: " + param); + } + return true; + } + return false; + }; + cls.prototype.appendText = function(text) { + if (this.fontname == null) + this.fontname = text; + else + this.fontname += text; + }; + cls.prototype.apply = function() { + if (this.index == null) + throw new RTFJS.Error("No font index provided"); + if (this.fontname == null) + throw new RTFJS.Error("No font name provided"); + this._fonttbl.addSub(this); + delete this._fonttbl; + }; + cls.prototype.setAltFontName = function(name) { + this.altfontname = name; + }; + return cls; + }; + + var fonttblDestination = function() { + var cls = function() { + DestinationBase.call(this, "fonttbl"); + this._fonts = []; + }; + cls.prototype.sub = function() { + var subCls = fonttblDestinationSub(); + return new subCls(this); + }; + cls.prototype.apply = function() { + console.log("[fonttbl] apply()"); + for (var idx in this._fonts) { + console.log("[fonttbl][" + idx + "] index = " + this._fonts[idx].fontname + " alternative: " + this._fonts[idx].altfontname); + } + } + cls.prototype.addSub = function(sub) { + this._fonts[sub.index] = sub; + }; + return cls; + }; + + var genericSubTextPropertyDestination = function(name, parentDest, propOrFunc) { + var cls = function() { + DestinationTextBase.call(this, name); + }; + cls.prototype = Object.create(DestinationTextBase.prototype); + cls.prototype.apply = function() { + var dest = findParentDestination(parentDest); + if (dest == null) + throw new RTFJS.Error(this._name + " destination must be child of " + parentDest + " destination"); + if (dest[propOrFunc] == null) + throw new RTFJS.Error(this._name + " destination cannot find member + " + propOrFunc + " in " + parentDest + " destination"); + if (dest[propOrFunc] instanceof Function) + dest[propOrFunc](this.text); + else + dest[propOrFunc] = this.text; + } + return cls; + }; + + var colortblDestination = function() { + var cls = function() { + DestinationBase.call(this, "colortbl"); + this._colors = []; + this._current = null; + this._autoIndex = null; + }; + cls.prototype._startNewColor = function() { + this._current = { + r: 0, + g: 0, + b: 0, + tint: 255, + shade: 255, + theme: null + }; + return this._current; + }; + cls.prototype.appendText = function(text) { + var len = text.length; + for (var i = 0; i < len; i++) { + if (text[i] != ";") + throw new RTFJS.Error("Error parsing colortbl destination"); + if (this._current == null) { + if (this._autoIndex != null) + throw new RTFJS.Error("colortbl cannot define more than one auto color"); + this._autoIndex = this._colors.length; + this._startNewColor(); + } else { + if (this._current.tint < 255 && this._current.shade < 255) + throw new RTFJS.Error("colortbl cannot define shade and tint at the same time"); + } + this._colors.push(this._current); + this._current = null; + } + }; + var _validateColorValueRange = function(keyword, param) { + if (param == null) + throw new RTFJS.Error(keyword + " has no param"); + if (param < 0 || param > 255) + throw new RTFJS.Error(keyword + " has invalid param value"); + return param; + }; + cls.prototype.handleKeyword = function(keyword, param) { + if (this._current == null) + this._startNewColor(); + + switch (keyword) { + case "red": + this._current.r = _validateColorValueRange(keyword, param); + return true; + case "green": + this._current.g = _validateColorValueRange(keyword, param); + return true; + case "blue": + this._current.b = _validateColorValueRange(keyword, param); + return true; + case "ctint": + this._current.tint = _validateColorValueRange(keyword, param); + return true; + case "cshade": + this._current.shade = _validateColorValueRange(keyword, param); + return true; + default: + if (keyword[0] == "c") { + this._current.theme = RTFJS._mapColorTheme(keyword.slice(1)); + return true; + } + break; + } + + console.log("[colortbl] handleKeyword(): unhandled keyword: " + keyword); + return false; + } + cls.prototype.apply = function() { + console.log("[colortbl] apply()"); + if (this._autoIndex == null) + this._autoIndex = 0; + if (this._autoIndex >= this._colors.length) + throw new RTFJS.Error("colortbl doesn't define auto color") + for (var idx in this._colors) + console.log("[colortbl] [" + idx + "] = " + this._colors[idx].r + "," + this._colors[idx].g + "," + this._colors[idx].b + " theme: " + this._colors[idx].theme); + inst._colors = this._colors; + inst._autoColor = this._autoIndex; + delete this._colors; + } + return cls; + }; + + var stylesheetDestinationSub = function() { + var _handleKeywordCommon = function(member) { + var data = this[member]; + if (data == null) + this[member] = data = {}; + return function(keyword, param) { + console.log("[stylesheet:sub]." + member + ": unhandled keyword: " + keyword + " param: " + param); + return false; + }; + }; + + var cls = function(stylesheet) { + DestinationBase.call(this, "stylesheet:sub"); + this._stylesheet = stylesheet; + this.index = 0; + this.name = null; + this.handler = _handleKeywordCommon("paragraph"); + }; + cls.prototype.handleKeyword = function(keyword, param) { + switch (keyword) { + case "s": + this.index = param; + return true; + case "cs": + delete this.paragraph; + this.handler = _handleKeywordCommon("character"); + this.index = param; + return true; + case "ds": + delete this.paragraph; + this.handler = _handleKeywordCommon("section"); + this.index = param; + return true; + case "ts": + delete this.paragraph; + this.handler = _handleKeywordCommon("table"); + this.index = param; + return true; + } + + return this.handler(keyword, param); + }; + cls.prototype.appendText = function(text) { + if (this.name == null) + this.name = text; + else + this.name += text; + }; + cls.prototype.apply = function() { + this._stylesheet.addSub({ + index: this.index, + name: this.name + }); + delete this._stylesheet; + }; + return cls; + }; + + var stylesheetDestination = function() { + var cls = function() { + DestinationBase.call(this, "stylesheet"); + this._stylesheets = []; + }; + cls.prototype.sub = function() { + var subCls = stylesheetDestinationSub(); + return new subCls(this); + }; + cls.prototype.apply = function() { + console.log("[stylesheet] apply()"); + for (var idx in this._stylesheets) + console.log("[stylesheet] [" + idx + "] name: " + this._stylesheets[idx].name); + inst._stylesheets = this._stylesheets; + delete this._stylesheets; + } + cls.prototype.addSub = function(sub) { + if (this._stylesheets[sub.index] != null) + throw new RTFJS.Error("Cannot redefine stylesheet with index " + sub.index); + this._stylesheets[sub.index] = sub; + } + return cls; + }; + + var pictDestination = function() { + var cls = function() { + DestinationTextBase.call(this, "pict"); + this._type = null; + this._blob = null; + this._displaysize = { + width: null, + height: null + }; + this._size = { + width: null, + height: null + }; + }; + cls.prototype = Object.create(DestinationTextBase.prototype); + _setPropValueRequired = function(member, prop) { + return function(param) { + if (param == null) + throw new RTFJS.Error("Picture property has no value"); + console.log("[pict] set " + member + "." + prop + " = " + param); + var obj = (member != null ? this[member] : this); + obj[prop] = param; + }; + }; + var _pictHandlers = { + picw: _setPropValueRequired("_size", "width"), + pich: _setPropValueRequired("_size", "height"), + picwgoal: _setPropValueRequired("_displaysize", "width"), + pichgoal: _setPropValueRequired("_displaysize", "height") + }; + var _pictTypeHandler = { + emfblip: "", // TODO + pngblip: "image/png", + jpegblip: "image/jpeg", + macpict: "", // TODO + pmmetafile: "", // TODO + wmetafile: (function() { + if (typeof WMFJS !== "undefined") { + return function(param) { + if (param == null || param < 0 || param > 8) + throw new RTFJS.Error("Insufficient metafile information"); + return { + load: function() { + try { + return new WMFJS.Renderer(this._blob); + } catch(e) { + if (e instanceof WMFJS.Error) + return e.message; + else + throw e; + } + }, + render: function(img) { + return img.render({ + width: RTFJS._twipsToPt(this._displaysize.width) + "pt", + height: RTFJS._twipsToPt(this._displaysize.height) + "pt", + xExt: this._size.width, + yExt: this._size.height, + mapMode: param + }); + } + }; + }; + } else { + return ""; + } + })(), + dibitmap: "" // TODO + }; + cls.prototype.handleKeyword = function(keyword, param) { + var handler = _pictHandlers[keyword]; + if (handler != null) { + handler.call(this, param); + return true; + } + var inst = this; + var type = _pictTypeHandler[keyword]; + if (type != null) { + if (this._type == null) { + if (typeof type === "function") { + var info = type.call(this, param); + if (info != null) { + if (typeof info === "string") { + this._type = info; + } else { + this._type = function() { + var renderer = info.load.call(inst); + if (renderer != null) { + if (typeof renderer === "string") + return renderer; + return function() { + return info.render.call(inst, renderer); + }; + } + }; + } + } + } else { + this._type = type; + } + } + return true; + } + return false; + }; + cls.prototype.handleBlob = function(blob) { + this._blob = blob; + }; + cls.prototype.apply = function() { + if (this._type == null) + throw new RTFJS.Error("Picture type unknown or not specified"); + //if (this._size.width == null || this._size.height == null) + // throw new RTFJS.Error("Picture dimensions not specified"); + //if (this._displaysize.width == null || this._displaysize.height == null) + // throw new RTFJS.Error("Picture display dimensions not specified"); + + var type = this._type; + if (typeof type === "function") { + // type is the trampoline function that executes the .load function + // and returns a renderer trampoline that ends up calling the .render function + if (this._blob == null) { + this._blob = RTFJS._hexToBlob(this.text); + if (this._blob == null) + throw new RTFJS.Error("Could not parse picture data"); + delete this.text; + } + + var info = this; + var doRender = function(rendering) { + var pictrender = type.call(info); + if (pictrender != null) { + if (typeof pictrender === "string") { + console.log("[pict] Could not load image: " + pictrender); + if (rendering) { + return this.buildPicture(pictrender, null); + } else { + inst._renderer.addIns(function() { + this.picture(pictrender, null); + }); + } + } else { + if (typeof pictrender !== "function") + throw new RTFJS.Error("Expected a picture render function"); + if (rendering) { + return this.buildRenderedPicture(pictrender()); + } else { + inst._renderer.addIns(function() { + this.renderedPicture(pictrender()); + }); + } + } + } + }; + + if (inst._settings.onPicture != null) { + inst._renderer.addIns(function() { + var renderer = this; + var elem = inst._settings.onPicture.call(inst, function() { + return doRender.call(renderer, true); + }); + if (elem != null) + this.appendElement(elem); + }); + } else { + doRender(false); + } + } else if (typeof type === "string") { + var text = this.text; + var blob = this._blob; + + var doRender = function(rendering) { + var bin = blob != null ? RTFJS._blobToBinary(blob) : RTFJS._hexToBinary(text); + if (type !== "") { + if (rendering) { + return this.buildPicture(type, bin); + } else { + inst._renderer.addIns(function() { + this.picture(type, bin); + }); + } + } else { + if (rendering) { + return this.buildPicture("Unsupported image format", null); + } else { + inst._renderer.addIns(function() { + this.picture("Unsupported image format", null); + }); + } + } + }; + + if (inst._settings.onPicture != null) { + inst._renderer.addIns(function() { + var renderer = this; + var elem = inst._settings.onPicture.call(inst, function() { + return doRender.call(renderer, true); + }); + if (elem != null) + this.appendElement(elem); + }); + } else { + doRender(false); + } + } + + delete this.text; + } + return cls; + }; + + var requiredDestination = function(name) { + return function() { + DestinationBase.call(this, name); + }; + }; + + var destinations = { + rtf: rtfDestination(), + info: infoDestination(), + title: metaPropertyDestination("title"), + subject: metaPropertyDestination("subject"), + author: metaPropertyDestination("author"), + manager: metaPropertyDestination("manager"), + company: metaPropertyDestination("company"), + operator: metaPropertyDestination("operator"), + category: metaPropertyDestination("category"), + keywords: metaPropertyDestination("keywords"), + doccomm: metaPropertyDestination("doccomm"), + hlinkbase: metaPropertyDestination("hlinkbase"), + generator: genericPropertyDestination("rtf", "generator"), + creatim: metaPropertyTimeDestination("creatim"), + revtim: metaPropertyTimeDestination("revtim"), + printim: metaPropertyTimeDestination("printim"), + buptim: metaPropertyTimeDestination("buptim"), + fonttbl: fonttblDestination(), + falt: genericSubTextPropertyDestination("falt", "fonttbl:sub", "setAltFontName"), + colortbl: colortblDestination(), + stylesheet: stylesheetDestination(), + footer: requiredDestination("footer"), + footerf: requiredDestination("footerf"), + footerl: requiredDestination("footerl"), + footerr: requiredDestination("footerr"), + footnote: requiredDestination("footnote"), + ftncn: requiredDestination("ftncn"), + ftnsep: requiredDestination("ftnsep"), + ftnsepc: requiredDestination("ftnsepc"), + header: requiredDestination("header"), + headerf: requiredDestination("headerf"), + headerl: requiredDestination("headerl"), + headerr: requiredDestination("headerr"), + pict: pictDestination(), + private1: requiredDestination("private1"), + rxe: requiredDestination("rxe"), + tc: requiredDestination("tc"), + txe: requiredDestination("txe"), + xe: requiredDestination("xe"), + }; + + var applyDestination = function(always) { + var dest = parser.state.destination; + if (dest != null) { + if (always || parser.state.parent == null || parser.state.parent.destination != parser.state.destination) { + if (dest.apply != null) + dest.apply(); + parser.state.destination = null; + } + } + }; + + var applyText = function() { + if (parser.text.length > 0) { + var dest = parser.state.destination; + if (dest == null) + throw new RTFJS.Error("Cannot route text to destination"); + if (dest != null && dest.appendText != null && !parser.state.skipdestination) + dest.appendText(parser.text); + parser.text = ""; + } + } + + var pushState = function(forceSkip) { + parser.state = new State(parser.state); + if (forceSkip) + parser.state.skipdestination = true; + + var dest = parser.state.destination; + if (dest != null && !parser.state.skipdestination) { + if (dest.sub != null) { + var sub = dest.sub(); + if (sub != null) + parser.state.destination = sub; + } + } + }; + + var popState = function() { + var state = parser.state; + if (state == null) + throw new RTFJS.Error("Unexpected end of state"); + + applyText(); + if (state.parent == null || state.destination != state.parent.destination) + applyDestination(true); + parser.state = state.parent; + return parser.state; + }; + + var changeDestination = function(name, param) { + applyText(); + var handler = destinations[name]; + if (handler != null) { + applyDestination(false); + parser.state.destination = new handler(name, param); + return true; + } + return false; + }; + + processKeyword = function(keyword, param) { + var first = parser.state.first; + if (first) { + if (keyword == "*") { + parser.state.skipunknowndestination = true; + return; + } + + parser.state.first = false; + } + + //if (param != null) + // console.log("keyword " + keyword + " with param " + param); + //else + // console.log("keyword " + keyword); + + if (parser.state.bindata > 0) + throw new RTFJS.Error("Keyword encountered within binary data"); + + // Reset if we unexpectedly encounter a keyword + parser.state.skipchars = 0; + switch (keyword) { + case "\n": + return "\n"; + case "\r": + return "\r"; + case "tab": + return "\t"; + case "ldblquote": + return "“"; + case "rdblquote": + return "”"; + case "{": + case "}": + case "\\": + return keyword; + + case "uc": + if (param != null && param >= 0) + parser.state.ucn = param; + break; + case "u": + if (param != null) { + if (param < 0) + param += 65536; + if (param < 0 || param > 65535) + throw new RTFJS.Error("Invalid unicode character encountered"); + + appendText(String.fromCharCode(param)); + parser.state.skipchars = parser.state.ucn; + } + return; + + case "bin": + if (param == null) + throw new RTFJS.Error("Binary data is missing length"); + if (param < 0) + throw new RTFJS.Error("Binary data with invalid length"); + parser.state.bindata = param; + return; + + case "upr": + parseLoop(true, null); // skip the first sub destination (ansi) + // this will be followed by a \ud sub destination + return; + case "ud": + return; + + default: + if (!parser.state.skipdestination) { + if (first) { + if (!changeDestination(keyword, param)) { + var handled = false; + var dest = parser.state.destination; + if (dest != null) { + if (dest.handleKeyword != null) + handled = dest.handleKeyword(keyword, param); + } + if (!handled && parser.state.skipunknowndestination) + parser.state.skipdestination = true; + } + } else { + applyText(); + var dest = parser.state.destination; + if (dest != null) { + if (dest.handleKeyword != null) + dest.handleKeyword(keyword, param); + } else { + console.log("Unhandled keyword: " + keyword + " param: " + param); + } + } + } + return; + } + + parser.state.skipdestination = false; + }; + + appendText = function(text) { + parser.state.first = false; + if (parser.state.skipchars > 0) { + var len = text.length; + if (parser.state.skipchars >= len) { + parser.state.skipchars -= len; + return; + } + + if (parser.state.destination == null || !parser.state.skipdestination) + parser.text += text.slice(parser.state.skipchars); + parser.state.skipchars = 0; + } else if (parser.state.destination == null || !parser.state.skipdestination) { + parser.text += text; + } + }; + + var applyBlob = function(blob) { + parser.state.first = false; + applyText(); + if (parser.state.skipchars > 0) { + // \bin and all its data is considered one character for skipping purposes + parser.state.skipchars--; + } else { + var dest = parser.state.destination; + if (dest == null) + throw new RTFJS.Error("Cannot route binary to destination"); + if (dest != null && dest.handleBlob != null && !parser.state.skipdestination) + dest.handleBlob(blob); + } + }; + + parseKeyword = function(process) { + if (parser.state == null) + throw new RTFJS.Error("No state"); + + var param; + var ch = parser.readChar(); + if (!RTFJS._isalpha(ch)) { + if (ch == "\'") { + param = RTFJS._parseHex(parser.readChar() + parser.readChar()) + if (isNaN(param)) + throw new RTFJS.Error("Could not parse hexadecimal number"); + + if (process != null) + appendText(String.fromCharCode(param)); + } else if (process != null) { + var text = process(ch, param); + if (text != null) + appendText(text); + } + } else { + var keyword = ch; + ch = parser.readChar(); + while (keyword.length < 30 && RTFJS._isalpha(ch)) { + keyword += ch; + ch = parser.readChar(); + } + + var num; + if (ch == "-") { + num = "-"; + ch = parser.readChar(); + } else { + num = ""; + } + + if (RTFJS._isdigit(ch)) { + do { + num += ch; + ch = parser.readChar(); + } while (num.length < 20 && RTFJS._isdigit(ch)); + + if (num.length >= 20) + throw new RTFJS.Error("Param for keyword " + keyword + " too long"); + + param = parseInt(num, 10); + if (isNaN(param)) + throw new RTFJS.Error("Invalid keyword " + keyword + " param"); + } + + if (ch != " ") + parser.unreadChar(); + + if (process != null) { + var text = process(keyword, param); + if (text != null) + appendText(text); + } + } + }; + + parseLoop = function(skip, process) { + var initialState = parser.state; + main_loop: while (!parser.eof()) { + if (parser.state != null && parser.state.bindata > 0) { + var blob = parser.readBlob(parser.state.bindata); + parser.state.bindata = 0; + applyBlob(blob); + } else { + var ch = parser.readChar(); + switch (ch) { + case "\r": + case "\n": + continue; + case "{": + pushState(skip); + break; + case "}": + if (initialState == parser.state) { + parser.unreadChar(); + break main_loop; + } + else if (popState() == initialState) + break main_loop; + break; + case "\\": + parseKeyword(!skip ? process : null); + break; + default: + if (!skip) + appendText(ch); + break; + } + } + } + }; + + if (parser.data.length > 1 && String.fromCharCode(parser.data[0]) == "{") { + parseLoop(false, processKeyword); + } + if (parser.version == null) + throw new RTFJS.Error("Not a valid rtf document"); + if (parser.state != null) + throw new RTFJS.Error("File truncated"); +} diff --git a/samples/jquery.binarytransport.js b/samples/jquery.binarytransport.js new file mode 100644 index 0000000..4f073bc --- /dev/null +++ b/samples/jquery.binarytransport.js @@ -0,0 +1,50 @@ + /** + * + * jquery.binarytransport.js + * + * @description. jQuery ajax transport for making binary data type requests. + * @version 1.0 + * @author Henry Algus + * + */ + +// use this transport for "binary" data type +$.ajaxTransport("+binary", function(options, originalOptions, jqXHR){ + // check for conditions and support for blob / arraybuffer response type + if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob))))) + { + return { + // create new XMLHttpRequest + send: function(headers, callback){ + // setup all variables + var xhr = new XMLHttpRequest(), + url = options.url, + type = options.type, + async = options.async || true, + // blob or arraybuffer. Default is blob + dataType = options.responseType || "blob", + data = options.data || null, + username = options.username || null, + password = options.password || null; + + xhr.addEventListener('load', function(){ + var data = {}; + data[options.dataType] = xhr.response; + // make callback and send data + callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders()); + }); + + xhr.open(type, url, async, username, password); + + // setup custom headers + for (var i in headers ) { + xhr.setRequestHeader(i, headers[i] ); + } + + xhr.responseType = dataType; + xhr.send(data); + }, + abort: function(){} + }; + } +}); diff --git a/samples/jquery.svg.css b/samples/jquery.svg.css new file mode 100644 index 0000000..5263233 --- /dev/null +++ b/samples/jquery.svg.css @@ -0,0 +1,10 @@ +/* http://keith-wood.name/svg.html + SVG for jQuery v1.5.0. + Written by Keith Wood (kbwood{at}iinet.com.au) August 2007.*/ +svg\:svg { + display: none; +} +.svg_error { + color: red; + font-weight: bold; +} diff --git a/samples/jquery.svg.min.js b/samples/jquery.svg.min.js new file mode 100644 index 0000000..87887ee --- /dev/null +++ b/samples/jquery.svg.min.js @@ -0,0 +1,6 @@ +/* http://keith-wood.name/svg.html + SVG for jQuery v1.5.0. + Written by Keith Wood (kbwood{at}iinet.com.au) August 2007. + Available under the MIT (http://keith-wood.name/licence.html) license. + Please attribute the author if you use it. */ +(function($){function SVGManager(){this._settings=[];this._extensions=[];this.regional=[];this.regional['']={errorLoadingText:'Error loading'};this.local=this.regional[''];this._uuid=new Date().getTime();this._ie=!!window.ActiveXObject}$.extend(SVGManager.prototype,{markerClassName:'hasSVG',propertyName:'svgwrapper',svgNS:'http://www.w3.org/2000/svg',xlinkNS:'http://www.w3.org/1999/xlink',_wrapperClass:SVGWrapper,_attrNames:{class_:'class',in_:'in',alignmentBaseline:'alignment-baseline',baselineShift:'baseline-shift',clipPath:'clip-path',clipRule:'clip-rule',colorInterpolation:'color-interpolation',colorInterpolationFilters:'color-interpolation-filters',colorRendering:'color-rendering',dominantBaseline:'dominant-baseline',enableBackground:'enable-background',fillOpacity:'fill-opacity',fillRule:'fill-rule',floodColor:'flood-color',floodOpacity:'flood-opacity',fontFamily:'font-family',fontSize:'font-size',fontSizeAdjust:'font-size-adjust',fontStretch:'font-stretch',fontStyle:'font-style',fontVariant:'font-variant',fontWeight:'font-weight',glyphOrientationHorizontal:'glyph-orientation-horizontal',glyphOrientationVertical:'glyph-orientation-vertical',horizAdvX:'horiz-adv-x',horizOriginX:'horiz-origin-x',imageRendering:'image-rendering',letterSpacing:'letter-spacing',lightingColor:'lighting-color',markerEnd:'marker-end',markerMid:'marker-mid',markerStart:'marker-start',stopColor:'stop-color',stopOpacity:'stop-opacity',strikethroughPosition:'strikethrough-position',strikethroughThickness:'strikethrough-thickness',strokeDashArray:'stroke-dasharray',strokeDashOffset:'stroke-dashoffset',strokeLineCap:'stroke-linecap',strokeLineJoin:'stroke-linejoin',strokeMiterLimit:'stroke-miterlimit',strokeOpacity:'stroke-opacity',strokeWidth:'stroke-width',textAnchor:'text-anchor',textDecoration:'text-decoration',textRendering:'text-rendering',underlinePosition:'underline-position',underlineThickness:'underline-thickness',vertAdvY:'vert-adv-y',vertOriginY:'vert-origin-y',wordSpacing:'word-spacing',writingMode:'writing-mode'},_attachSVG:function(a,b){var c=(a.namespaceURI===this.svgNS?a:null);var a=(c?null:a);if($(a||c).hasClass(this.markerClassName)){return}if(typeof b==='string'){b={loadURL:b}}else if(typeof b==='function'){b={onLoad:b}}$(a||c).addClass(this.markerClassName);try{if(!c){c=document.createElementNS(this.svgNS,'svg');c.setAttribute('version','1.1');if(a.clientWidth>0){c.setAttribute('width',a.clientWidth)}if(a.clientHeight>0){c.setAttribute('height',a.clientHeight)}a.appendChild(c)}this._afterLoad(a,c,b||{})}catch(e){$(a).html('

SVG is not supported natively on this browser

')}},_afterLoad:function(a,b,c){var c=c||this._settings[a.id];this._settings[a?a.id:'']=null;var d=new this._wrapperClass(b,a);$.data(a||b,$.svg.propertyName,d);try{if(c.loadURL){d.load(c.loadURL,c)}if(c.settings){d.configure(c.settings)}if(c.onLoad&&!c.loadURL){c.onLoad.apply(a||b,[d])}}catch(e){alert(e)}},_getSVG:function(a){return $(a).data(this.propertyName)},_destroySVG:function(a){a=$(a);if(!a.hasClass(this.markerClassName)){return}a.removeClass(this.markerClassName).removeData(this.propertyName);if(a[0].namespaceURI!==this.svgNS){a.empty()}},addExtension:function(a,b){this._extensions.push([a,b])},isSVGElem:function(a){return(a.nodeType===1&&a.namespaceURI===$.svg.svgNS)}});function SVGWrapper(a,b){this._svg=a;this._container=b;for(var i=0;i<$.svg._extensions.length;i++){var c=$.svg._extensions[i];this[c[0]]=new c[1](this)}}$.extend(SVGWrapper.prototype,{width:function(){return(this._container?this._container.clientWidth:this._svg.width)},height:function(){return(this._container?this._container.clientHeight:this._svg.height)},root:function(){return this._svg},configure:function(a,b,c){if(!a.nodeName){c=b;b=a;a=this._svg}if(c){for(var i=a.attributes.length-1;i>=0;i--){var d=a.attributes.item(i);if(!(d.nodeName==='onload'||d.nodeName==='version'||d.nodeName.substring(0,5)==='xmlns')){a.attributes.removeNamedItem(d.nodeName)}}}for(var e in b){a.setAttribute($.svg._attrNames[e]||e,b[e])}return this},getElementById:function(a){return this._svg.ownerDocument.getElementById(a)},change:function(a,b){if(a){for(var c in b){if(b[c]==null){a.removeAttribute($.svg._attrNames[c]||c)}else{a.setAttribute($.svg._attrNames[c]||c,b[c])}}}return this},_args:function(b,c,d){c.splice(0,0,'parent');c.splice(c.length,0,'settings');var e={};var f=0;if(b[0]!=null&&b[0].jquery){b[0]=b[0][0]}if(b[0]!=null&&!(typeof b[0]==='object'&&b[0].nodeName)){e['parent']=null;f=1}for(var i=0;i/g,'>'))}}}return b},_checkName:function(a){a=(a.substring(0,1)>='A'&&a.substring(0,1)<='Z'?a.toLowerCase():a);return(a.substring(0,4)==='svg:'?a.substring(4):a)},load:function(l,m){m=(typeof m==='boolean'?{addTo:m}:(typeof m==='function'?{onLoad:m}:(typeof m==='string'?{parent:m}:(typeof m==='object'&&m.nodeName?{parent:m}:(typeof m==='object'&&m.jquery?{parent:m}:m||{})))));if(!m.parent&&!m.addTo){this.clear(false)}var n=[this._svg.getAttribute('width'),this._svg.getAttribute('height')];var o=this;var p=function(a){a=$.svg.local.errorLoadingText+': '+a;if(m.onLoad){m.onLoad.apply(o._container||o._svg,[o,a])}else{o.text(null,10,20,a)}};var q=function(a){var b=new ActiveXObject('Microsoft.XMLDOM');b.validateOnParse=false;b.resolveExternals=false;b.async=false;b.loadXML(a);if(b.parseError.errorCode!==0){p(b.parseError.reason);return null}return b};var r=function(b){if(!b){return}if(b.documentElement.nodeName!=='svg'){var c=b.getElementsByTagName('parsererror');var d=(c.length?c[0].getElementsByTagName('div'):[]);p(!c.length?'???':(d.length?d[0]:c[0]).firstChild.nodeValue);return}var f=(m.parent?$(m.parent)[0]:o._svg);var g={};for(var i=0;i'}else{b='<'+a.nodeName;if(a.attributes){for(var i=0;i';var d=a.firstChild;while(d){b+=this._toSVG(d);d=d.nextSibling}b+=''}else{b+='/>'}}return b}});function SVGPath(){this._path=''}$.extend(SVGPath.prototype,{reset:function(){this._path='';return this},move:function(x,y,a){a=($.isArray(x)?y:a);return this._coords((a?'m':'M'),x,y)},line:function(x,y,a){a=($.isArray(x)?y:a);return this._coords((a?'l':'L'),x,y)},horiz:function(x,a){this._path+=(a?'h':'H')+($.isArray(x)?x.join(' '):x);return this},vert:function(y,a){this._path+=(a?'v':'V')+($.isArray(y)?y.join(' '):y);return this},curveC:function(a,b,c,d,x,y,e){e=($.isArray(a)?b:e);return this._coords((e?'c':'C'),a,b,c,d,x,y)},smoothC:function(a,b,x,y,c){c=($.isArray(a)?b:c);return this._coords((c?'s':'S'),a,b,x,y)},curveQ:function(a,b,x,y,c){c=($.isArray(a)?b:c);return this._coords((c?'q':'Q'),a,b,x,y)},smoothQ:function(x,y,a){a=($.isArray(x)?y:a);return this._coords((a?'t':'T'),x,y)},_coords:function(a,b,c,d,e,f,g){if($.isArray(b)){for(var i=0;i + + + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ Drop an RTF document here +
+ +
+ + diff --git a/samples/rtf.js.wmf b/samples/rtf.js.wmf new file mode 100644 index 0000000000000000000000000000000000000000..ee86995398affdcf7fb193063dd1f3ba41084e97 GIT binary patch literal 51562 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 Sw7l#C3!6T`%NO|Tbp9W9n>&2~ literal 0 HcmV?d00001 diff --git a/samples/simple1.rtf b/samples/simple1.rtf new file mode 100644 index 0000000000000000000000000000000000000000..75615bb5104283a2df49ad6104dadde70212f9a0 GIT binary patch literal 260 zcmXAjv2KJg5JXd-bpNn*3S|2rQFP_i=~7O!U>jC32H7Sl5dR)?kyf*#SM1vzsdx>J zS)MVhqc)v^b>6Ep1IJOT+iizmVkv#7MZrf2@WaF@yQ1j9LHZ>3@sY#iv^;nIi=T2efZ@Ml+sxM literal 0 HcmV?d00001 diff --git a/samples/simple2.rtf b/samples/simple2.rtf new file mode 100644 index 0000000000000000000000000000000000000000..01ffec6fe8637c1b764653f70bd72ea73e8a72e2 GIT binary patch literal 342 zcmYLEv1-IH4DEby|Dd_UVf&J%N5;b>!3`IK!$Q?L$2qed;TX^i;ts@s%qHH3v>`HPo1i5=@H$b}t5GaBm-~Z$l zQ}G&2%)A9V_qsY&=*WAu#$aNv)$w>mKgCkIAc;aBIiR{c-4*Q= zrX-!vVj`!oPeie4unP<6*QVW?p0TG$$&@LJ}v}$ko&2%|)bTuwk z<7|?{Y$~NNhpKszI4+@RTrIwBu5wku=fD}z=eh>Y@=FN}U`=urfX}1g_W7xh2!)(niInKkz6kq(VW+LhwdmpF5c-C+Ys3l z7uRwW;_`Jtp>s1ff6FozBG7X94sDOkNNb~&(PA_kO*W~tQOYPWij5*$E82)MB1YH< z*;dwum0>Z=h6zZ9v>|0k46z{uzy>t1(2Q!bbL>%Ci`J|)*|CU}(n_>qt;n)KQj`|a z!dl3ZLMXpHu~KC9VJspM zC9H(3T(CfrMKLQTs0S(3DiTGk2=d?uXrdc-KtD)8Ay@+pq`?xU;DN!w1~jn9I%m^} zaae?`k+h?s>5zCtcoASuK`@DWbK0PsRNjD}iR2|qv+-LM0kAQ%e48ekxePS64m z3~aZ#MxVC6as#zyTvoh4aPj_-E8j+K_9UR{!QKeuflzwtUI!!Xm@DI=Az8y-t^Vk zbI&)FhVte=Ii}mAO4e{Rn@xG?`)dLg#pFh2E{IB88B5(TkRo;K@_T%dNPEYM7N}y=KSK@pN z|KA6dOeD|2DiX@x%gd$4q*wA0Jij6A_ZPksj(8SjWFk(?r)`(Oq zds1i66SIDHEOz9@q|Rd_2dQG}obRITZ9{9O_5Ie?Jz_W0+?_qVz(bD|sjorz=Puk*bzt%saxiQBxc~|jZ zLrUbAKx`E~H}~GWU-zCmnf_U0OCU1v;my}y`Zg&Z8*9x<>stEL`;~kA8%O^hNDf!L zuqmt`r=3}G=UGo-;Yj=T3wu-cE&eEa?&$nVv#|J3$J>FKDQ!#EzUe>v + + + + + + + + + + + +
+ +
+ + + Render as: + x +
+
+ +
+
+ Drop an WMF image here +
+
+ + diff --git a/wmf.js b/wmf.js new file mode 100644 index 0000000..7572abc --- /dev/null +++ b/wmf.js @@ -0,0 +1,836 @@ +/* + +The MIT License (MIT) + +Copyright (c) 2015 Thomas Bluemel + +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. + +*/ + +if (typeof WMFJS === 'undefined') { + (typeof window !== 'undefined' ? window : this).WMFJS = { + Error: function(message) { + this.message = message; + }, + GDI: { + METAHEADER_SIZE: 18, + BITMAPINFOHEADER_SIZE: 40, + BITMAPCOREHEADER_SIZE: 12, + MetafileType: { + MEMORYMETAFILE: 1, + DISKMETAFILE: 2 + }, + MetafileVersion: { + METAVERSION100: 0x100, + METAVERSION300: 0x300 + }, + RecordType: { + META_EOF: 0x0000, + META_REALIZEPALETTE: 0x0035, + META_SETPALENTRIES: 0x0037, + META_SETBKMODE: 0x0102, + META_SETMAPMODE: 0x0103, + META_SETROP2: 0x0104, + META_SETRELABS: 0x0105, + META_SETPOLYFILLMODE: 0x0106, + META_SETSTRETCHBLTMODE: 0x0107, + META_SETTEXTCHAREXTRA: 0x0108, + META_RESTOREDC: 0x0127, + META_RESIZEPALETTE: 0x0139, + META_DIBCREATEPATTERNBRUSH: 0x0142, + META_SETLAYOUT: 0x0149, + META_SETBKCOLOR: 0x0201, + META_SETTEXTCOLOR: 0x0209, + META_OFFSETVIEWPORTORG: 0x0211, + META_LINETO: 0x0213, + META_MOVETO: 0x0214, + META_OFFSETCLIPRGN: 0x0220, + META_FILLREGION: 0x0228, + META_SETMAPPERFLAGS: 0x0231, + META_SELECTPALETTE: 0x0234, + META_POLYGON: 0x0324, + META_POLYLINE: 0x0325, + META_SETTEXTJUSTIFICATION: 0x020a, + META_SETWINDOWORG: 0x020b, + META_SETWINDOWEXT: 0x020c, + META_SETVIEWPORTORG: 0x020d, + META_SETVIEWPORTEXT: 0x020e, + META_OFFSETWINDOWORG: 0x020f, + META_SCALEWINDOWEXT: 0x0410, + META_SCALEVIEWPORTEXT: 0x0412, + META_EXCLUDECLIPRECT: 0x0415, + META_INTERSECTCLIPRECT: 0x0416, + META_ELLIPSE: 0x0418, + META_FLOODFILL: 0x0419, + META_FRAMEREGION: 0x0429, + META_ANIMATEPALETTE: 0x0436, + META_TEXTOUT: 0x0521, + META_POLYPOLYGON: 0x0538, + META_EXTFLOODFILL: 0x0548, + META_RECTANGLE: 0x041b, + META_SETPIXEL: 0x041f, + META_ROUNDRECT: 0x061c, + META_PATBLT: 0x061d, + META_SAVEDC: 0x001e, + META_PIE: 0x081a, + META_STRETCHBLT: 0x0b23, + META_ESCAPE: 0x0626, + META_INVERTREGION: 0x012a, + META_PAINTREGION: 0x012b, + META_SELECTCLIPREGION: 0x012c, + META_SELECTOBJECT: 0x012d, + META_SETTEXTALIGN: 0x012e, + META_ARC: 0x0817, + META_CHORD: 0x0830, + META_BITBLT: 0x0922, + META_EXTTEXTOUT: 0x0a32, + META_SETDIBTODEV: 0x0d33, + META_DIBBITBLT: 0x0940, + META_DIBSTRETCHBLT: 0x0b41, + META_STRETCHDIB: 0x0f43, + META_DELETEOBJECT: 0x01f0, + META_CREATEPALETTE: 0x00f7, + META_CREATEPATTERNBRUSH: 0x01f9, + META_CREATEPENINDIRECT: 0x02fa, + META_CREATEFONTINDIRECT: 0x02fb, + META_CREATEBRUSHINDIRECT: 0x02fc, + META_CREATEREGION: 0x06ff + }, + MetafileEscapes: { + NEWFRAME: 0x0001, + ABORTDOC: 0x0002, + NEXTBAND: 0x0003, + SETCOLORTABLE: 0x0004, + GETCOLORTABLE: 0x0005, + FLUSHOUT: 0x0006, + DRAFTMODE: 0x0007, + QUERYESCSUPPORT: 0x0008, + SETABORTPROC: 0x0009, + STARTDOC: 0x000a, + ENDDOC: 0x000b, + GETPHYSPAGESIZE: 0x000c, + GETPRINTINGOFFSET: 0x000d, + GETSCALINGFACTOR: 0x000e, + META_ESCAPE_ENHANCED_METAFILE: 0x000f, + SETPENWIDTH: 0x0010, + SETCOPYCOUNT: 0x0011, + SETPAPERSOURCE: 0x0012, + PASSTHROUGH: 0x0013, + GETTECHNOLOGY: 0x0014, + SETLINECAP: 0x0015, + SETLINEJOIN: 0x0016, + SETMITERLIMIT: 0x0017, + BANDINFO: 0x0018, + DRAWPATTERNRECT: 0x0019, + GETVECTORPENSIZE: 0x001a, + GETVECTORBRUSHSIZE: 0x001b, + ENABLEDUPLEX: 0x001c, + GETSETPAPERBINS: 0x001d, + GETSETPRINTORIENT: 0x001e, + ENUMPAPERBINS: 0x001f, + SETDIBSCALING: 0x0020, + EPSPRINTING: 0x0021, + ENUMPAPERMETRICS: 0x0022, + GETSETPAPERMETRICS: 0x0023, + POSTSCRIPT_DATA: 0x0025, + POSTSCRIPT_IGNORE: 0x0026, + GETDEVICEUNITS: 0x002a, + GETEXTENDEDTEXTMETRICS: 0x0100, + GETPAIRKERNTABLE: 0x0102, + EXTTEXTOUT: 0x0200, + GETFACENAME: 0x0201, + DOWNLOADFACE: 0x0202, + METAFILE_DRIVER: 0x0801, + QUERYDIBSUPPORT: 0x0c01, + BEGIN_PATH: 0x1000, + CLIP_TO_PATH: 0x1001, + END_PATH: 0x1002, + OPEN_CHANNEL: 0x100e, + DOWNLOADHEADER: 0x100f, + CLOSE_CHANNEL: 0x1010, + POSTSCRIPT_PASSTHROUGH: 0x1013, + ENCAPSULATED_POSTSCRIPT: 0x1014, + POSTSCRIPT_IDENTIFY: 0x1015, + POSTSCRIPT_INJECTION: 0x1016, + CHECKJPEGFORMAT: 0x1017, + CHECKPNGFORMAT: 0x1018, + GET_PS_FEATURESETTING: 0x1019, + MXDC_ESCAPE: 0x101a, + SPCLPASSTHROUGH2: 0x11d8 + }, + MapMode: { + MM_TEXT: 1, + MM_LOMETRIC: 2, + MM_HIMETRIC: 3, + MM_LOENGLISH: 4, + MM_HIENGLISH: 5, + MM_TWIPS: 6, + MM_ISOTROPIC: 7, + MM_ANISOTROPIC: 8 + }, + StretchMode: { + BLACKONWHITE: 1, + WHITEONBLACK: 2, + COLORONCOLOR: 3, + HALFTONE: 4 + }, + BitmapCompression: { + BI_RGB: 0, + BI_RLE8: 1, + BI_RLE4: 2, + BI_BITFIELDS: 3, + BI_JPEG: 4, + BI_PNG: 5 + }, + }, + _uniqueId: 0, + _makeUniqueId: function(prefix) { + return prefix + (this._uniqueId++); + }, + _writeUint32Val: function(uint8arr, pos, val) { + uint8arr[pos++] = val & 0xff; + uint8arr[pos++] = (val >>> 8) & 0xff; + uint8arr[pos++] = (val >>> 16) & 0xff; + uint8arr[pos++] = (val >>> 24) & 0xff; + }, + _blobToBinary: function(blob) { + var ret = ""; + var len = blob.length; + for (var i = 0; i < len; i++) + ret += String.fromCharCode(blob[i]); + return ret; + }, + }; +} + +WMFJS.Blob = function(blob, offset) { + if (blob instanceof WMFJS.Blob) { + this.blob = blob.blob; + this.data = blob.data; + this.pos = offset || blob.pos; + } else { + this.blob = blob; + this.data = new Uint8Array(blob); + this.pos = offset || 0; + } +}; + +WMFJS.Blob.prototype.eof = function() { + return this.pos >= this.data.length; +}; + +WMFJS.Blob.prototype.seek = function(newpos) { + if (newpos < 0 || newpos > this.data.length) + throw new WMFJS.Error("Invalid seek position"); + this.pos = newpos; +}; + +WMFJS.Blob.prototype.skip = function(cnt) { + var newPos = this.pos + cnt; + if (newPos > this.data.length) + throw new WMFJS.Error("Unexpected end of file"); + this.pos = newPos; +}; + +WMFJS.Blob.prototype.readBinary = function(cnt) { + var end = this.pos + cnt; + if (end > this.data.length) + throw new WMFJS.Error("Unexpected end of file"); + var ret = ""; + while (cnt-- > 0) + ret += String.fromCharCode(this.data[this.pos++]); + return ret; +}; + +WMFJS.Blob.prototype.readInt32 = function() { + if (this.pos + 4 > this.data.length) + throw new WMFJS.Error("Unexpected end of file"); + var val = this.data[this.pos++]; + val |= this.data[this.pos++] << 8; + val |= this.data[this.pos++] << 16; + val |= this.data[this.pos++] << 24; + return val; +}; + +WMFJS.Blob.prototype.readUint32 = function() { + return this.readInt32() >>> 0; +}; + +WMFJS.Blob.prototype.readUint16 = function() { + if (this.pos + 2 > this.data.length) + throw new WMFJS.Error("Unexpected end of file"); + var val = this.data[this.pos++]; + val |= this.data[this.pos++] << 8; + return val; +}; + +WMFJS.Blob.prototype.readInt16 = function() { + var val = this.readUint16(); + if (val > 32767) + val -= 65536; + return val; +}; + +WMFJS.BitmapCoreHeader = function(reader, skipsize) { + if (skipsize) + reader.skip(4); + this.width = reader.readUint16(); + this.height = reader.readUint16(); + this.planes = reader.readUint16(); + this.bitcount = reader.readUint16(); +} + +WMFJS.BitmapCoreHeader.prototype.colors = function() { + return this.bitcount <= 8 ? 1 << this.bitcount : 0; +}; + +WMFJS.BitmapInfoHeader = function(reader, skipsize) { + if (skipsize) + reader.skip(4); + this.width = reader.readInt32(); + this.height = reader.readInt32(); + this.planes = reader.readUint16(); + this.bitcount = reader.readUint16(); + this.compression = reader.readUint32(); + this.sizeimage = reader.readUint32(); + this.xpelspermeter = reader.readInt32(); + this.ypelspermeter = reader.readInt32(); + this.clrused = reader.readUint32(); + this.clrimportant = reader.readUint32(); +}; + +WMFJS.BitmapInfoHeader.prototype.colors = function() { + if (this.clrused != 0) + return this.clrused < 256 ? this.clrused : 256; + else + return this.bitcount > 8 ? 0 : 1 << this.bitcount; +}; + +WMFJS.BitmapInfo = function(reader, usergb) { + this._reader = reader; + this._offset = reader.pos; + this._usergb = usergb; + var hdrsize = reader.readUint32(); + this._infosize = hdrsize; + if (hdrsize == WMFJS.GDI.BITMAPCOREHEADER_SIZE) { + this._header = new WMFJS.BitmapCoreHeader(reader, false); + this._infosize += this._header.colors() * (usergb ? 3 : 2); + } + else { + this._header = new WMFJS.BitmapInfoHeader(reader, false); + var masks = this._header.compression == WMFJS.GDI.BitmapCompression.BI_BITFIELDS ? 3 : 0; + if (hdrsize <= WMFJS.GDI.BITMAPINFOHEADER_SIZE + (masks * 4)) + this._infosize = WMFJS.GDI.BITMAPINFOHEADER_SIZE + (masks * 4); + this._infosize += this._header.colors() * (usergb ? 4 : 2); + } +}; + +WMFJS.BitmapInfo.prototype.infosize = function() { + return this._infosize; +}; + +WMFJS.BitmapInfo.prototype.header = function() { + return this._header; +}; + +WMFJS.DIBitmap = function(reader, size) { + this._reader = reader; + this._offset = reader.pos; + this._size = size; + this._info = new WMFJS.BitmapInfo(reader, true); +}; + +WMFJS.DIBitmap.prototype.makeBitmapFileHeader = function() { + var buf = new ArrayBuffer(14); + var view = new Uint8Array(buf); + view[0] = 0x42; + view[1] = 0x4d; + WMFJS._writeUint32Val(view, 2, this._size + 14); + WMFJS._writeUint32Val(view, 10, this._info.infosize() + 14); + return WMFJS._blobToBinary(view); +}; + +WMFJS.DIBitmap.prototype.base64ref = function() { + var prevpos = this._reader.pos; + this._reader.seek(this._offset); + var mime = "image/bmp"; + var header = this._info.header(); + var data; + if (header.compression != null) { + switch (header.compression) { + case WMFJS.GDI.BitmapCompression.BI_JPEG: + mime = "data:image/jpeg"; + break; + case WMFJS.GDI.BitmapCompression.BI_PNG: + mime = "data:image/png"; + break; + default: + data = this.makeBitmapFileHeader(); + break; + } + } else { + data = this.makeBitmapFileHeader(); + } + + if (data != null) + data += this._reader.readBinary(this._size); + else + data = this._reader.readBinary(this._size); + + var ref = "data:" + mime + ";base64," + btoa(data); + this._reader.seek(prevpos); + return ref; +}; + +WMFJS.GDIContextState = function(copy) { + if (copy != null) { + this._svggroup = copy._svggroup; + this.mapmode = copy.mapmode; + this.stretchmode = copy.stretchmode; + this.wx = copy.wx; + this.wy = copy.wy; + this.ww = copy.ww; + this.wh = copy.wh; + this.vx = copy.vx; + this.vy = copy.vy; + this.vw = copy.vw; + this.vh = copy.vh; + } else { + this._svggroup = null; + this.mapmode = WMFJS.GDI.MapMode.MM_ANISOTROPIC; + this.stretchmode = WMFJS.GDI.StretchMode.COLORONCOLOR; + this.wx = 0; + this.wy = 0; + this.ww = 0; + this.wh = 0; + this.vx = 0; + this.vy = 0; + this.vw = 0; + this.vh = 0; + } +} + +WMFJS.GDIContext = function(svg) { + this._svg = svg; + this.state = new WMFJS.GDIContextState(null); + this.statestack = [this.state]; +}; + +WMFJS.GDIContext.prototype._pushGroup = function() { + if (this.state._svggroup == null) { + var settings = { + viewBox: [this.state.vx + this._todevX(0), this.state.vy + this._todevY(0), this.state.vw, this.state.vh].join(" "), + preserveAspectRatio: "none" + }; + //this.state._svggroup = this._svg.group(WMFJS._makeUniqueId("wmfjs_grp"), settings); + this.state._svggroup = this._svg.svg(this.state._svggroup, + this.state.vx, this.state.vy, this.state.vw, this.state.vh, this.state.vx, this.state.vy, this.state.vw, this.state.vh, settings); + } +}; + +WMFJS.GDIContext.prototype._todevX = function(val) { + // http://wvware.sourceforge.net/caolan/mapmode.html + // logical -> device + return Math.floor((val - this.state.wx) * (this.state.vw / this.state.ww)) + this.state.vx; +}; + +WMFJS.GDIContext.prototype._todevY = function(val) { + // http://wvware.sourceforge.net/caolan/mapmode.html + // logical -> device + return Math.floor((val - this.state.wy) * (this.state.vh / this.state.wh)) + this.state.vy; +}; + +WMFJS.GDIContext.prototype._todevW = function(val) { + // http://wvware.sourceforge.net/caolan/mapmode.html + // logical -> device + return Math.floor(val * (this.state.vw / this.state.ww)) + this.state.vx; +}; + +WMFJS.GDIContext.prototype._todevH = function(val) { + // http://wvware.sourceforge.net/caolan/mapmode.html + // logical -> device + return Math.floor(val * (this.state.vh / this.state.wh)) + this.state.vy; +}; + +WMFJS.GDIContext.prototype._tologicalX = function(val) { + // http://wvware.sourceforge.net/caolan/mapmode.html + // logical -> device + return Math.floor((val - this.state.vx) / (this.state.vw / this.state.ww)) + this.state.wx; +}; + +WMFJS.GDIContext.prototype._tologicalY = function(val) { + // http://wvware.sourceforge.net/caolan/mapmode.html + // logical -> device + return Math.floor((val - this.state.vy) / (this.state.vh / this.state.wh)) + this.state.wy; +}; + +WMFJS.GDIContext.prototype._tologicalW = function(val) { + // http://wvware.sourceforge.net/caolan/mapmode.html + // logical -> device + return Math.floor(val / (this.state.vw / this.state.ww)) + this.state.wx; +}; + +WMFJS.GDIContext.prototype._tologicalH = function(val) { + // http://wvware.sourceforge.net/caolan/mapmode.html + // logical -> device + return Math.floor(val / (this.state.vh / this.state.wh)) + this.state.wy; +}; + +WMFJS.GDIContext.prototype.setMapMode = function(mode) { + console.log("[gdi] setMapMode: mode=" + mode); + this.state.mapmode = mode; + this.state._svggroup = null; +}; + +WMFJS.GDIContext.prototype.setWindowOrg = function(x, y) { + console.log("[gdi] setWindowOrg: x=" + x + " y=" + y); + this.state.wx = x; + this.state.wy = y; + this.state._svggroup = null; +}; + +WMFJS.GDIContext.prototype.setWindowExt = function(x, y) { + console.log("[gdi] setWindowExt: x=" + x + " y=" + y); + this.state.ww = x; + this.state.wh = y; + this.state._svggroup = null; +}; + +WMFJS.GDIContext.prototype.setViewportOrg = function(x, y) { + console.log("[gdi] setViewportOrg: x=" + x + " y=" + y); + this.state.vx = x; + this.state.vy = y; + this.state._svggroup = null; +}; + +WMFJS.GDIContext.prototype.setViewportExt = function(x, y) { + console.log("[gdi] setViewportExt: x=" + x + " y=" + y); + this.state.vw = x; + this.state.vh = y; + this.state._svggroup = null; +}; + +WMFJS.GDIContext.prototype.saveDC = function() { + console.log("[gdi] saveDC"); + var prevstate = this.state; + this.state = new WMFJS.GDIContextState(this.state); + this.statestack.push(prevstate); + this.state._svggroup = null; +}; + +WMFJS.GDIContext.prototype.restoreDC = function(saved) { + console.log("[gdi] restoreDC: saved=" + saved); + if (this.statestack.length > 1) { + if (saved == -1) { + this.state = this.statestack.pop(); + } else if (saved < -1) { + throw new WMFJS.Error("restoreDC: relative restore not implemented"); + } else if (saved > 1) { + throw new WMFJS.Error("restoreDC: absolute restore not implemented"); + } + } else { + throw new WMFJS.Error("No saved contexts"); + } + + this.state._svggroup = null; +}; + +WMFJS.GDIContext.prototype.escape = function(func, blob, offset, count) { + console.log("[gdi] escape: func=" + func + " offset=" + offset + " count=" + count); +}; + +WMFJS.GDIContext.prototype.setStretchBltMode = function(stretchMode) { + console.log("[gdi] setStretchBltMode: stretchMode=" + stretchMode); +}; + +WMFJS.GDIContext.prototype.stretchDibBits = function(srcX, srcY, srcW, srcH, dstX, dstY, dstW, dstH, rasterOp, dib) { + console.log("[gdi] stretchDibBits: srcX=" + srcX + " srcY=" + srcY + " srcW=" + srcW + " srcH=" + srcH + " dstX=" + dstX + " dstY=" + dstY + " dstW=" + dstW + " dstH=" + dstH + " rasterOp=0x" + rasterOp.toString(16)); + srcX = this._todevX(srcX); + srcY = this._todevY(srcY); + srcW = this._todevW(srcW); + srcH = this._todevH(srcH); + dstX = this._todevX(dstX); + dstY = this._todevY(dstY); + dstW = this._todevW(dstW); + dstH = this._todevH(dstH); + console.log("[gdi] stretchDibBits: TRANSLATED: srcX=" + srcX + " srcY=" + srcY + " srcW=" + srcW + " srcH=" + srcH + " dstX=" + dstX + " dstY=" + dstY + " dstW=" + dstW + " dstH=" + dstH + " rasterOp=0x" + rasterOp.toString(16)); + this._pushGroup(); + this._svg.image(this.state._svggroup, dstX, dstY, dstW, dstH, dib.base64ref()); +}; + +WMFJS.WMFRect16 = function(reader) { + this.left = reader.readInt16(); + this.top = reader.readInt16(); + this.right = reader.readInt16(); + this.bottom = reader.readInt16(); +}; + +WMFJS.WMFRect16.prototype.toString = function() { + return "{left: " + this.left + ", top: " + this.top + ", right: " + this.right + ", bottom: " + this.bottom + "}"; +}; + +WMFJS.WMFRecords = function(reader, first) { + this._records = []; + + var all = false; + var curpos = first; + main_loop: while (!all) { + reader.seek(curpos); + var size = reader.readUint32(); + if (size < 3) + throw new WMFJS.Error("Invalid record size"); + var type = reader.readUint16(); + switch (type) { + case WMFJS.GDI.RecordType.META_EOF: + all = true; + break main_loop; + case WMFJS.GDI.RecordType.META_SETMAPMODE: + var mapMode = reader.readUint16(); + this._records.push(function(gdi) { + gdi.setMapMode(mapMode); + }); + break; + case WMFJS.GDI.RecordType.META_SETWINDOWORG: + var y = reader.readInt16(); + var x = reader.readInt16(); + this._records.push(function(gdi) { + gdi.setWindowOrg(x, y); + }); + break; + case WMFJS.GDI.RecordType.META_SETWINDOWEXT: + var y = reader.readInt16(); + var x = reader.readInt16(); + this._records.push(function(gdi) { + gdi.setWindowExt(x, y); + }); + break; + case WMFJS.GDI.RecordType.META_SAVEDC: + this._records.push(function(gdi) { + gdi.saveDC(); + }); + break; + case WMFJS.GDI.RecordType.META_RESTOREDC: + var saved = reader.readInt16(); + this._records.push(function(gdi) { + gdi.restoreDC(saved); + }); + break; + case WMFJS.GDI.RecordType.META_SETSTRETCHBLTMODE: + var stretchMode = reader.readUint16(); + this._records.push(function(gdi) { + gdi.setStretchBltMode(stretchMode); + }); + break; + case WMFJS.GDI.RecordType.META_DIBSTRETCHBLT: + var haveSrcDib = ((type >> 8) + 3 != size); + var rasterOp = reader.readUint16() | (reader.readUint16() << 16); + var srcH = reader.readInt16(); + var srcW = reader.readInt16(); + var srcY = reader.readInt16(); + var srcX = reader.readInt16(); + var destH = reader.readInt16(); + var destW = reader.readInt16(); + var destY = reader.readInt16(); + var destX = reader.readInt16(); + var datalength = size * 2 - (reader.pos - curpos); + var dib = new WMFJS.DIBitmap(reader, datalength); + this._records.push(function(gdi) { + gdi.stretchDibBits(srcX, srcY, srcW, srcH, destX, destY, destW, destH, rasterOp, dib); + }); + break; + case WMFJS.GDI.RecordType.META_ESCAPE: + var func = reader.readUint16(); + var count = reader.readUint16(); + var offset = reader.pos; + var blob = new WMFJS.Blob(reader, offset); + this._records.push(function(gdi) { + gdi.escape(func, blob, offset, count); + }); + break; + case WMFJS.GDI.RecordType.META_REALIZEPALETTE: + case WMFJS.GDI.RecordType.META_SETPALENTRIES: + case WMFJS.GDI.RecordType.META_SETBKMODE: + case WMFJS.GDI.RecordType.META_SETROP2: + case WMFJS.GDI.RecordType.META_SETRELABS: + case WMFJS.GDI.RecordType.META_SETPOLYFILLMODE: + case WMFJS.GDI.RecordType.META_SETTEXTCHAREXTRA: + case WMFJS.GDI.RecordType.META_RESIZEPALETTE: + case WMFJS.GDI.RecordType.META_DIBCREATEPATTERNBRUSH: + case WMFJS.GDI.RecordType.META_SETLAYOUT: + case WMFJS.GDI.RecordType.META_SETBKCOLOR: + case WMFJS.GDI.RecordType.META_SETTEXTCOLOR: + case WMFJS.GDI.RecordType.META_OFFSETVIEWPORTORG: + case WMFJS.GDI.RecordType.META_LINETO: + case WMFJS.GDI.RecordType.META_MOVETO: + case WMFJS.GDI.RecordType.META_OFFSETCLIPRGN: + case WMFJS.GDI.RecordType.META_FILLREGION: + case WMFJS.GDI.RecordType.META_SETMAPPERFLAGS: + case WMFJS.GDI.RecordType.META_SELECTPALETTE: + case WMFJS.GDI.RecordType.META_POLYGON: + case WMFJS.GDI.RecordType.META_POLYLINE: + case WMFJS.GDI.RecordType.META_SETTEXTJUSTIFICATION: + case WMFJS.GDI.RecordType.META_SETVIEWPORTORG: + case WMFJS.GDI.RecordType.META_SETVIEWPORTEXT: + case WMFJS.GDI.RecordType.META_OFFSETWINDOWORG: + case WMFJS.GDI.RecordType.META_SCALEWINDOWEXT: + case WMFJS.GDI.RecordType.META_SCALEVIEWPORTEXT: + case WMFJS.GDI.RecordType.META_EXCLUDECLIPRECT: + case WMFJS.GDI.RecordType.META_INTERSECTCLIPRECT: + case WMFJS.GDI.RecordType.META_ELLIPSE: + case WMFJS.GDI.RecordType.META_FLOODFILL: + case WMFJS.GDI.RecordType.META_FRAMEREGION: + case WMFJS.GDI.RecordType.META_ANIMATEPALETTE: + case WMFJS.GDI.RecordType.META_TEXTOUT: + case WMFJS.GDI.RecordType.META_POLYPOLYGON: + case WMFJS.GDI.RecordType.META_EXTFLOODFILL: + case WMFJS.GDI.RecordType.META_RECTANGLE: + case WMFJS.GDI.RecordType.META_SETPIXEL: + case WMFJS.GDI.RecordType.META_ROUNDRECT: + case WMFJS.GDI.RecordType.META_PATBLT: + case WMFJS.GDI.RecordType.META_PIE: + case WMFJS.GDI.RecordType.META_STRETCHBLT: + case WMFJS.GDI.RecordType.META_INVERTREGION: + case WMFJS.GDI.RecordType.META_PAINTREGION: + case WMFJS.GDI.RecordType.META_SELECTCLIPREGION: + case WMFJS.GDI.RecordType.META_SELECTOBJECT: + case WMFJS.GDI.RecordType.META_SETTEXTALIGN: + case WMFJS.GDI.RecordType.META_ARC: + case WMFJS.GDI.RecordType.META_CHORD: + case WMFJS.GDI.RecordType.META_BITBLT: + case WMFJS.GDI.RecordType.META_EXTTEXTOUT: + case WMFJS.GDI.RecordType.META_SETDIBTODEV: + case WMFJS.GDI.RecordType.META_DIBBITBLT: + case WMFJS.GDI.RecordType.META_STRETCHDIB: + case WMFJS.GDI.RecordType.META_DELETEOBJECT: + case WMFJS.GDI.RecordType.META_CREATEPALETTE: + case WMFJS.GDI.RecordType.META_CREATEPATTERNBRUSH: + case WMFJS.GDI.RecordType.META_CREATEPENINDIRECT: + case WMFJS.GDI.RecordType.META_CREATEFONTINDIRECT: + case WMFJS.GDI.RecordType.META_CREATEBRUSHINDIRECT: + case WMFJS.GDI.RecordType.META_CREATEREGION: + console.log("[WMF] record 0x" + type.toString(16) + " at offset 0x" + curpos.toString(16) + " with " + (size * 2) + " bytes"); + break; + default: + console.log("[WMF] UNKNOWN record 0x" + type.toString(16) + " at offset 0x" + curpos.toString(16) + " with " + (size * 2) + " bytes"); + //throw new WMFJS.Error("Record type not recognized: 0x" + type.toString(16)); + break; + } + + curpos += size * 2; + } + + if (!all) + throw new WMFJS.Error("Could not read all records"); +}; + +WMFJS.WMFRecords.prototype.play = function(gdi) { + var len = this._records.length; + for (var i = 0; i < len; i++) { + this._records[i].call(this, gdi); + } +}; + +WMFJS.WMFPlacable = function(reader) { + reader.skip(2); + this.boundingBox = new WMFJS.WMFRect16(reader); + this.unitsPerInch = reader.readInt16(); + reader.skip(4); + reader.skip(2); // TODO: checksum + console.log("Got bounding box " + this.boundingBox + " and " + this.unitsPerInch + " units/inch"); +}; + +WMFJS.WMF = function(reader, placable, version, hdrsize) { + this._reader = reader; + this._version = version; + this._hdrsize = hdrsize; + this._placable = placable; + this._img = null; + this._records = new WMFJS.WMFRecords(reader, this._hdrsize); +}; + +WMFJS.WMF.prototype.render = function(gdi) { + this._records.play(gdi); +}; + +WMFJS.Renderer = function(blob) { + this.parse(blob); + console.log("WMFJS.Renderer instantiated"); +}; + +WMFJS.Renderer.prototype.parse = function(blob) { + this._img = null; + + var reader = new WMFJS.Blob(blob); + + var type, size, placeable, headerstart; + var key = reader.readUint32(); + if (key == 0x9ac6cdd7) { + placable = new WMFJS.WMFPlacable(reader); + headerstart = reader.pos; + type = reader.readUint16(); + size = reader.readUint16(); + } else { + headerstart = 0; + type = key & 0xffff; + size = (key >>> 16) & 0xffff; + } + switch (type) { + case WMFJS.GDI.MetafileType.MEMORYMETAFILE: + case WMFJS.GDI.MetafileType.DISKMETAFILE: + if (size == WMFJS.GDI.METAHEADER_SIZE / 2) { + var version = reader.readUint16(); + switch (version) { + case WMFJS.GDI.MetafileVersion.METAVERSION100: + case WMFJS.GDI.MetafileVersion.METAVERSION300: + this._img = new WMFJS.WMF(reader, placeable, version, headerstart + (size * 2)); + break; + } + } + break; + } + + if (this._img == null) + throw new WMFJS.Error("Format not recognized"); +}; + +WMFJS.Renderer.prototype._render = function(svg, info) { + // See https://www-user.tu-chemnitz.de/~ygu/petzold/ch18b.htm + var gdi = new WMFJS.GDIContext(svg); + gdi.setViewportExt(info.xExt, info.yExt); + gdi.setMapMode(info.mapMode); + console.log("[WMF] BEGIN RENDERING --->"); + this._img.render(gdi); + console.log("[WMF] <--- DONE RENDERING"); +}; + +WMFJS.Renderer.prototype.render = function(info) { + var inst = this; + var img = $("
").svg({ + onLoad: function(svg) { + return inst._render.call(inst, svg, info); + }, + settings: { + viewBox: [0, 0, info.xExt, info.yExt].join(" "), + preserveAspectRatio: "none" // TODO: MM_ISOTROPIC vs MM_ANISOTROPIC + } + }); + var svg = $(img[0]).svg("get"); + return $(svg.root()).attr("width", info.width).attr("height", info.height); +};