text_layer.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2019 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.renderTextLayer = void 0;
  27. var _util = require("../shared/util");
  28. var _global_scope = _interopRequireDefault(require("../shared/global_scope"));
  29. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  30. var renderTextLayer = function renderTextLayerClosure() {
  31. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  32. var NonWhitespaceRegexp = /\S/;
  33. function isAllWhitespace(str) {
  34. return !NonWhitespaceRegexp.test(str);
  35. }
  36. var styleBuf = ['left: ', 0, 'px; top: ', 0, 'px; font-size: ', 0, 'px; font-family: ', '', ';'];
  37. function appendText(task, geom, styles) {
  38. var textDiv = document.createElement('span');
  39. var textDivProperties = {
  40. style: null,
  41. angle: 0,
  42. canvasWidth: 0,
  43. isWhitespace: false,
  44. originalTransform: null,
  45. paddingBottom: 0,
  46. paddingLeft: 0,
  47. paddingRight: 0,
  48. paddingTop: 0,
  49. scale: 1
  50. };
  51. task._textDivs.push(textDiv);
  52. if (isAllWhitespace(geom.str)) {
  53. textDivProperties.isWhitespace = true;
  54. task._textDivProperties.set(textDiv, textDivProperties);
  55. return;
  56. }
  57. var tx = _util.Util.transform(task._viewport.transform, geom.transform);
  58. var angle = Math.atan2(tx[1], tx[0]);
  59. var style = styles[geom.fontName];
  60. if (style.vertical) {
  61. angle += Math.PI / 2;
  62. }
  63. var fontHeight = Math.sqrt(tx[2] * tx[2] + tx[3] * tx[3]);
  64. var fontAscent = fontHeight;
  65. if (style.ascent) {
  66. fontAscent = style.ascent * fontAscent;
  67. } else if (style.descent) {
  68. fontAscent = (1 + style.descent) * fontAscent;
  69. }
  70. var left;
  71. var top;
  72. if (angle === 0) {
  73. left = tx[4];
  74. top = tx[5] - fontAscent;
  75. } else {
  76. left = tx[4] + fontAscent * Math.sin(angle);
  77. top = tx[5] - fontAscent * Math.cos(angle);
  78. }
  79. styleBuf[1] = left;
  80. styleBuf[3] = top;
  81. styleBuf[5] = fontHeight;
  82. styleBuf[7] = style.fontFamily;
  83. textDivProperties.style = styleBuf.join('');
  84. textDiv.setAttribute('style', textDivProperties.style);
  85. textDiv.textContent = geom.str;
  86. if (task._fontInspectorEnabled) {
  87. textDiv.dataset.fontName = geom.fontName;
  88. }
  89. if (angle !== 0) {
  90. textDivProperties.angle = angle * (180 / Math.PI);
  91. }
  92. if (geom.str.length > 1) {
  93. if (style.vertical) {
  94. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  95. } else {
  96. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  97. }
  98. }
  99. task._textDivProperties.set(textDiv, textDivProperties);
  100. if (task._textContentStream) {
  101. task._layoutText(textDiv);
  102. }
  103. if (task._enhanceTextSelection) {
  104. var angleCos = 1,
  105. angleSin = 0;
  106. if (angle !== 0) {
  107. angleCos = Math.cos(angle);
  108. angleSin = Math.sin(angle);
  109. }
  110. var divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale;
  111. var divHeight = fontHeight;
  112. var m, b;
  113. if (angle !== 0) {
  114. m = [angleCos, angleSin, -angleSin, angleCos, left, top];
  115. b = _util.Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m);
  116. } else {
  117. b = [left, top, left + divWidth, top + divHeight];
  118. }
  119. task._bounds.push({
  120. left: b[0],
  121. top: b[1],
  122. right: b[2],
  123. bottom: b[3],
  124. div: textDiv,
  125. size: [divWidth, divHeight],
  126. m: m
  127. });
  128. }
  129. }
  130. function render(task) {
  131. if (task._canceled) {
  132. return;
  133. }
  134. var textDivs = task._textDivs;
  135. var capability = task._capability;
  136. var textDivsLength = textDivs.length;
  137. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  138. task._renderingDone = true;
  139. capability.resolve();
  140. return;
  141. }
  142. if (!task._textContentStream) {
  143. for (var i = 0; i < textDivsLength; i++) {
  144. task._layoutText(textDivs[i]);
  145. }
  146. }
  147. task._renderingDone = true;
  148. capability.resolve();
  149. }
  150. function expand(task) {
  151. var bounds = task._bounds;
  152. var viewport = task._viewport;
  153. var expanded = expandBounds(viewport.width, viewport.height, bounds);
  154. for (var i = 0; i < expanded.length; i++) {
  155. var div = bounds[i].div;
  156. var divProperties = task._textDivProperties.get(div);
  157. if (divProperties.angle === 0) {
  158. divProperties.paddingLeft = bounds[i].left - expanded[i].left;
  159. divProperties.paddingTop = bounds[i].top - expanded[i].top;
  160. divProperties.paddingRight = expanded[i].right - bounds[i].right;
  161. divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
  162. task._textDivProperties.set(div, divProperties);
  163. continue;
  164. }
  165. var e = expanded[i],
  166. b = bounds[i];
  167. var m = b.m,
  168. c = m[0],
  169. s = m[1];
  170. var points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size];
  171. var ts = new Float64Array(64);
  172. points.forEach(function (p, i) {
  173. var t = _util.Util.applyTransform(p, m);
  174. ts[i + 0] = c && (e.left - t[0]) / c;
  175. ts[i + 4] = s && (e.top - t[1]) / s;
  176. ts[i + 8] = c && (e.right - t[0]) / c;
  177. ts[i + 12] = s && (e.bottom - t[1]) / s;
  178. ts[i + 16] = s && (e.left - t[0]) / -s;
  179. ts[i + 20] = c && (e.top - t[1]) / c;
  180. ts[i + 24] = s && (e.right - t[0]) / -s;
  181. ts[i + 28] = c && (e.bottom - t[1]) / c;
  182. ts[i + 32] = c && (e.left - t[0]) / -c;
  183. ts[i + 36] = s && (e.top - t[1]) / -s;
  184. ts[i + 40] = c && (e.right - t[0]) / -c;
  185. ts[i + 44] = s && (e.bottom - t[1]) / -s;
  186. ts[i + 48] = s && (e.left - t[0]) / s;
  187. ts[i + 52] = c && (e.top - t[1]) / -c;
  188. ts[i + 56] = s && (e.right - t[0]) / s;
  189. ts[i + 60] = c && (e.bottom - t[1]) / -c;
  190. });
  191. var findPositiveMin = function findPositiveMin(ts, offset, count) {
  192. var result = 0;
  193. for (var i = 0; i < count; i++) {
  194. var t = ts[offset++];
  195. if (t > 0) {
  196. result = result ? Math.min(t, result) : t;
  197. }
  198. }
  199. return result;
  200. };
  201. var boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
  202. divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
  203. divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
  204. divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
  205. divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
  206. task._textDivProperties.set(div, divProperties);
  207. }
  208. }
  209. function expandBounds(width, height, boxes) {
  210. var bounds = boxes.map(function (box, i) {
  211. return {
  212. x1: box.left,
  213. y1: box.top,
  214. x2: box.right,
  215. y2: box.bottom,
  216. index: i,
  217. x1New: undefined,
  218. x2New: undefined
  219. };
  220. });
  221. expandBoundsLTR(width, bounds);
  222. var expanded = new Array(boxes.length);
  223. bounds.forEach(function (b) {
  224. var i = b.index;
  225. expanded[i] = {
  226. left: b.x1New,
  227. top: 0,
  228. right: b.x2New,
  229. bottom: 0
  230. };
  231. });
  232. boxes.map(function (box, i) {
  233. var e = expanded[i],
  234. b = bounds[i];
  235. b.x1 = box.top;
  236. b.y1 = width - e.right;
  237. b.x2 = box.bottom;
  238. b.y2 = width - e.left;
  239. b.index = i;
  240. b.x1New = undefined;
  241. b.x2New = undefined;
  242. });
  243. expandBoundsLTR(height, bounds);
  244. bounds.forEach(function (b) {
  245. var i = b.index;
  246. expanded[i].top = b.x1New;
  247. expanded[i].bottom = b.x2New;
  248. });
  249. return expanded;
  250. }
  251. function expandBoundsLTR(width, bounds) {
  252. bounds.sort(function (a, b) {
  253. return a.x1 - b.x1 || a.index - b.index;
  254. });
  255. var fakeBoundary = {
  256. x1: -Infinity,
  257. y1: -Infinity,
  258. x2: 0,
  259. y2: Infinity,
  260. index: -1,
  261. x1New: 0,
  262. x2New: 0
  263. };
  264. var horizon = [{
  265. start: -Infinity,
  266. end: Infinity,
  267. boundary: fakeBoundary
  268. }];
  269. bounds.forEach(function (boundary) {
  270. var i = 0;
  271. while (i < horizon.length && horizon[i].end <= boundary.y1) {
  272. i++;
  273. }
  274. var j = horizon.length - 1;
  275. while (j >= 0 && horizon[j].start >= boundary.y2) {
  276. j--;
  277. }
  278. var horizonPart, affectedBoundary;
  279. var q,
  280. k,
  281. maxXNew = -Infinity;
  282. for (q = i; q <= j; q++) {
  283. horizonPart = horizon[q];
  284. affectedBoundary = horizonPart.boundary;
  285. var xNew;
  286. if (affectedBoundary.x2 > boundary.x1) {
  287. xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1;
  288. } else if (affectedBoundary.x2New === undefined) {
  289. xNew = (affectedBoundary.x2 + boundary.x1) / 2;
  290. } else {
  291. xNew = affectedBoundary.x2New;
  292. }
  293. if (xNew > maxXNew) {
  294. maxXNew = xNew;
  295. }
  296. }
  297. boundary.x1New = maxXNew;
  298. for (q = i; q <= j; q++) {
  299. horizonPart = horizon[q];
  300. affectedBoundary = horizonPart.boundary;
  301. if (affectedBoundary.x2New === undefined) {
  302. if (affectedBoundary.x2 > boundary.x1) {
  303. if (affectedBoundary.index > boundary.index) {
  304. affectedBoundary.x2New = affectedBoundary.x2;
  305. }
  306. } else {
  307. affectedBoundary.x2New = maxXNew;
  308. }
  309. } else if (affectedBoundary.x2New > maxXNew) {
  310. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
  311. }
  312. }
  313. var changedHorizon = [],
  314. lastBoundary = null;
  315. for (q = i; q <= j; q++) {
  316. horizonPart = horizon[q];
  317. affectedBoundary = horizonPart.boundary;
  318. var useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary;
  319. if (lastBoundary === useBoundary) {
  320. changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
  321. } else {
  322. changedHorizon.push({
  323. start: horizonPart.start,
  324. end: horizonPart.end,
  325. boundary: useBoundary
  326. });
  327. lastBoundary = useBoundary;
  328. }
  329. }
  330. if (horizon[i].start < boundary.y1) {
  331. changedHorizon[0].start = boundary.y1;
  332. changedHorizon.unshift({
  333. start: horizon[i].start,
  334. end: boundary.y1,
  335. boundary: horizon[i].boundary
  336. });
  337. }
  338. if (boundary.y2 < horizon[j].end) {
  339. changedHorizon[changedHorizon.length - 1].end = boundary.y2;
  340. changedHorizon.push({
  341. start: boundary.y2,
  342. end: horizon[j].end,
  343. boundary: horizon[j].boundary
  344. });
  345. }
  346. for (q = i; q <= j; q++) {
  347. horizonPart = horizon[q];
  348. affectedBoundary = horizonPart.boundary;
  349. if (affectedBoundary.x2New !== undefined) {
  350. continue;
  351. }
  352. var used = false;
  353. for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) {
  354. used = horizon[k].boundary === affectedBoundary;
  355. }
  356. for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) {
  357. used = horizon[k].boundary === affectedBoundary;
  358. }
  359. for (k = 0; !used && k < changedHorizon.length; k++) {
  360. used = changedHorizon[k].boundary === affectedBoundary;
  361. }
  362. if (!used) {
  363. affectedBoundary.x2New = maxXNew;
  364. }
  365. }
  366. Array.prototype.splice.apply(horizon, [i, j - i + 1].concat(changedHorizon));
  367. });
  368. horizon.forEach(function (horizonPart) {
  369. var affectedBoundary = horizonPart.boundary;
  370. if (affectedBoundary.x2New === undefined) {
  371. affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
  372. }
  373. });
  374. }
  375. function TextLayerRenderTask(_ref) {
  376. var _this = this;
  377. var textContent = _ref.textContent,
  378. textContentStream = _ref.textContentStream,
  379. container = _ref.container,
  380. viewport = _ref.viewport,
  381. textDivs = _ref.textDivs,
  382. textContentItemsStr = _ref.textContentItemsStr,
  383. enhanceTextSelection = _ref.enhanceTextSelection;
  384. this._textContent = textContent;
  385. this._textContentStream = textContentStream;
  386. this._container = container;
  387. this._viewport = viewport;
  388. this._textDivs = textDivs || [];
  389. this._textContentItemsStr = textContentItemsStr || [];
  390. this._enhanceTextSelection = !!enhanceTextSelection;
  391. this._fontInspectorEnabled = !!(_global_scope["default"].FontInspector && _global_scope["default"].FontInspector.enabled);
  392. this._reader = null;
  393. this._layoutTextLastFontSize = null;
  394. this._layoutTextLastFontFamily = null;
  395. this._layoutTextCtx = null;
  396. this._textDivProperties = new WeakMap();
  397. this._renderingDone = false;
  398. this._canceled = false;
  399. this._capability = (0, _util.createPromiseCapability)();
  400. this._renderTimer = null;
  401. this._bounds = [];
  402. this._capability.promise["finally"](function () {
  403. if (_this._layoutTextCtx) {
  404. _this._layoutTextCtx.canvas.width = 0;
  405. _this._layoutTextCtx.canvas.height = 0;
  406. _this._layoutTextCtx = null;
  407. }
  408. });
  409. }
  410. TextLayerRenderTask.prototype = {
  411. get promise() {
  412. return this._capability.promise;
  413. },
  414. cancel: function TextLayer_cancel() {
  415. this._canceled = true;
  416. if (this._reader) {
  417. this._reader.cancel(new _util.AbortException('TextLayer task cancelled.'));
  418. this._reader = null;
  419. }
  420. if (this._renderTimer !== null) {
  421. clearTimeout(this._renderTimer);
  422. this._renderTimer = null;
  423. }
  424. this._capability.reject(new Error('TextLayer task cancelled.'));
  425. },
  426. _processItems: function _processItems(items, styleCache) {
  427. for (var i = 0, len = items.length; i < len; i++) {
  428. this._textContentItemsStr.push(items[i].str);
  429. appendText(this, items[i], styleCache);
  430. }
  431. },
  432. _layoutText: function _layoutText(textDiv) {
  433. var textLayerFrag = this._container;
  434. var textDivProperties = this._textDivProperties.get(textDiv);
  435. if (textDivProperties.isWhitespace) {
  436. return;
  437. }
  438. var fontSize = textDiv.style.fontSize;
  439. var fontFamily = textDiv.style.fontFamily;
  440. if (fontSize !== this._layoutTextLastFontSize || fontFamily !== this._layoutTextLastFontFamily) {
  441. this._layoutTextCtx.font = fontSize + ' ' + fontFamily;
  442. this._layoutTextLastFontSize = fontSize;
  443. this._layoutTextLastFontFamily = fontFamily;
  444. }
  445. var width = this._layoutTextCtx.measureText(textDiv.textContent).width;
  446. var transform = '';
  447. if (textDivProperties.canvasWidth !== 0 && width > 0) {
  448. textDivProperties.scale = textDivProperties.canvasWidth / width;
  449. transform = "scaleX(".concat(textDivProperties.scale, ")");
  450. }
  451. if (textDivProperties.angle !== 0) {
  452. transform = "rotate(".concat(textDivProperties.angle, "deg) ").concat(transform);
  453. }
  454. if (transform.length > 0) {
  455. textDivProperties.originalTransform = transform;
  456. textDiv.style.transform = transform;
  457. }
  458. this._textDivProperties.set(textDiv, textDivProperties);
  459. textLayerFrag.appendChild(textDiv);
  460. },
  461. _render: function TextLayer_render(timeout) {
  462. var _this2 = this;
  463. var capability = (0, _util.createPromiseCapability)();
  464. var styleCache = Object.create(null);
  465. var canvas = document.createElement('canvas');
  466. canvas.mozOpaque = true;
  467. this._layoutTextCtx = canvas.getContext('2d', {
  468. alpha: false
  469. });
  470. if (this._textContent) {
  471. var textItems = this._textContent.items;
  472. var textStyles = this._textContent.styles;
  473. this._processItems(textItems, textStyles);
  474. capability.resolve();
  475. } else if (this._textContentStream) {
  476. var pump = function pump() {
  477. _this2._reader.read().then(function (_ref2) {
  478. var value = _ref2.value,
  479. done = _ref2.done;
  480. if (done) {
  481. capability.resolve();
  482. return;
  483. }
  484. Object.assign(styleCache, value.styles);
  485. _this2._processItems(value.items, styleCache);
  486. pump();
  487. }, capability.reject);
  488. };
  489. this._reader = this._textContentStream.getReader();
  490. pump();
  491. } else {
  492. throw new Error('Neither "textContent" nor "textContentStream"' + ' parameters specified.');
  493. }
  494. capability.promise.then(function () {
  495. styleCache = null;
  496. if (!timeout) {
  497. render(_this2);
  498. } else {
  499. _this2._renderTimer = setTimeout(function () {
  500. render(_this2);
  501. _this2._renderTimer = null;
  502. }, timeout);
  503. }
  504. }, this._capability.reject);
  505. },
  506. expandTextDivs: function TextLayer_expandTextDivs(expandDivs) {
  507. if (!this._enhanceTextSelection || !this._renderingDone) {
  508. return;
  509. }
  510. if (this._bounds !== null) {
  511. expand(this);
  512. this._bounds = null;
  513. }
  514. for (var i = 0, ii = this._textDivs.length; i < ii; i++) {
  515. var div = this._textDivs[i];
  516. var divProperties = this._textDivProperties.get(div);
  517. if (divProperties.isWhitespace) {
  518. continue;
  519. }
  520. if (expandDivs) {
  521. var transform = '',
  522. padding = '';
  523. if (divProperties.scale !== 1) {
  524. transform = 'scaleX(' + divProperties.scale + ')';
  525. }
  526. if (divProperties.angle !== 0) {
  527. transform = 'rotate(' + divProperties.angle + 'deg) ' + transform;
  528. }
  529. if (divProperties.paddingLeft !== 0) {
  530. padding += ' padding-left: ' + divProperties.paddingLeft / divProperties.scale + 'px;';
  531. transform += ' translateX(' + -divProperties.paddingLeft / divProperties.scale + 'px)';
  532. }
  533. if (divProperties.paddingTop !== 0) {
  534. padding += ' padding-top: ' + divProperties.paddingTop + 'px;';
  535. transform += ' translateY(' + -divProperties.paddingTop + 'px)';
  536. }
  537. if (divProperties.paddingRight !== 0) {
  538. padding += ' padding-right: ' + divProperties.paddingRight / divProperties.scale + 'px;';
  539. }
  540. if (divProperties.paddingBottom !== 0) {
  541. padding += ' padding-bottom: ' + divProperties.paddingBottom + 'px;';
  542. }
  543. if (padding !== '') {
  544. div.setAttribute('style', divProperties.style + padding);
  545. }
  546. if (transform !== '') {
  547. div.style.transform = transform;
  548. }
  549. } else {
  550. div.style.padding = 0;
  551. div.style.transform = divProperties.originalTransform || '';
  552. }
  553. }
  554. }
  555. };
  556. function renderTextLayer(renderParameters) {
  557. var task = new TextLayerRenderTask({
  558. textContent: renderParameters.textContent,
  559. textContentStream: renderParameters.textContentStream,
  560. container: renderParameters.container,
  561. viewport: renderParameters.viewport,
  562. textDivs: renderParameters.textDivs,
  563. textContentItemsStr: renderParameters.textContentItemsStr,
  564. enhanceTextSelection: renderParameters.enhanceTextSelection
  565. });
  566. task._render(renderParameters.timeout);
  567. return task;
  568. }
  569. return renderTextLayer;
  570. }();
  571. exports.renderTextLayer = renderTextLayer;