text_layer.js 19 KB

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