PageRenderTime 42ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/web/text_layer_builder.js

https://gitlab.com/itesoft/pdf.js
JavaScript | 365 lines | 252 code | 38 blank | 75 comment | 43 complexity | 277345f5c317a2f45e3a9a753ee6cf8b MD5 | raw file
  1. /* Copyright 2012 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. 'use strict';
  16. (function (root, factory) {
  17. if (typeof define === 'function' && define.amd) {
  18. define('pdfjs-web/text_layer_builder', ['exports', 'pdfjs-web/dom_events',
  19. 'pdfjs-web/pdfjs'],
  20. factory);
  21. } else if (typeof exports !== 'undefined') {
  22. factory(exports, require('./dom_events.js'), require('./pdfjs.js'));
  23. } else {
  24. factory((root.pdfjsWebTextLayerBuilder = {}), root.pdfjsWebDOMEvents,
  25. root.pdfjsWebPDFJS);
  26. }
  27. }(this, function (exports, domEvents, pdfjsLib) {
  28. /**
  29. * @typedef {Object} TextLayerBuilderOptions
  30. * @property {HTMLDivElement} textLayerDiv - The text layer container.
  31. * @property {EventBus} eventBus - The application event bus.
  32. * @property {number} pageIndex - The page index.
  33. * @property {PageViewport} viewport - The viewport of the text layer.
  34. * @property {PDFFindController} findController
  35. */
  36. /**
  37. * TextLayerBuilder provides text-selection functionality for the PDF.
  38. * It does this by creating overlay divs over the PDF text. These divs
  39. * contain text that matches the PDF text they are overlaying. This object
  40. * also provides a way to highlight text that is being searched for.
  41. * @class
  42. */
  43. var TextLayerBuilder = (function TextLayerBuilderClosure() {
  44. function TextLayerBuilder(options) {
  45. this.textLayerDiv = options.textLayerDiv;
  46. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  47. this.renderingDone = false;
  48. this.divContentDone = false;
  49. this.pageIdx = options.pageIndex;
  50. this.pageNumber = this.pageIdx + 1;
  51. this.matches = [];
  52. this.viewport = options.viewport;
  53. this.textDivs = [];
  54. this.findController = options.findController || null;
  55. this.textLayerRenderTask = null;
  56. this._bindMouse();
  57. }
  58. TextLayerBuilder.prototype = {
  59. _finishRendering: function TextLayerBuilder_finishRendering() {
  60. this.renderingDone = true;
  61. var endOfContent = document.createElement('div');
  62. endOfContent.className = 'endOfContent';
  63. this.textLayerDiv.appendChild(endOfContent);
  64. this.eventBus.dispatch('textlayerrendered', {
  65. source: this,
  66. pageNumber: this.pageNumber
  67. });
  68. },
  69. /**
  70. * Renders the text layer.
  71. * @param {number} timeout (optional) if specified, the rendering waits
  72. * for specified amount of ms.
  73. */
  74. render: function TextLayerBuilder_render(timeout) {
  75. if (!this.divContentDone || this.renderingDone) {
  76. return;
  77. }
  78. if (this.textLayerRenderTask) {
  79. this.textLayerRenderTask.cancel();
  80. this.textLayerRenderTask = null;
  81. }
  82. this.textDivs = [];
  83. var textLayerFrag = document.createDocumentFragment();
  84. this.textLayerRenderTask = pdfjsLib.renderTextLayer({
  85. textContent: this.textContent,
  86. container: textLayerFrag,
  87. viewport: this.viewport,
  88. textDivs: this.textDivs,
  89. timeout: timeout
  90. });
  91. this.textLayerRenderTask.promise.then(function () {
  92. this.textLayerDiv.appendChild(textLayerFrag);
  93. this._finishRendering();
  94. this.updateMatches();
  95. }.bind(this), function (reason) {
  96. // canceled or failed to render text layer -- skipping errors
  97. });
  98. },
  99. setTextContent: function TextLayerBuilder_setTextContent(textContent) {
  100. if (this.textLayerRenderTask) {
  101. this.textLayerRenderTask.cancel();
  102. this.textLayerRenderTask = null;
  103. }
  104. this.textContent = textContent;
  105. this.divContentDone = true;
  106. },
  107. convertMatches: function TextLayerBuilder_convertMatches(matches) {
  108. var i = 0;
  109. var iIndex = 0;
  110. var bidiTexts = this.textContent.items;
  111. var end = bidiTexts.length - 1;
  112. var queryLen = (this.findController === null ?
  113. 0 : this.findController.state.query.length);
  114. var ret = [];
  115. for (var m = 0, len = matches.length; m < len; m++) {
  116. // Calculate the start position.
  117. var matchIdx = matches[m];
  118. // Loop over the divIdxs.
  119. while (i !== end && matchIdx >= (iIndex + bidiTexts[i].str.length)) {
  120. iIndex += bidiTexts[i].str.length;
  121. i++;
  122. }
  123. if (i === bidiTexts.length) {
  124. console.error('Could not find a matching mapping');
  125. }
  126. var match = {
  127. begin: {
  128. divIdx: i,
  129. offset: matchIdx - iIndex
  130. }
  131. };
  132. // Calculate the end position.
  133. matchIdx += queryLen;
  134. // Somewhat the same array as above, but use > instead of >= to get
  135. // the end position right.
  136. while (i !== end && matchIdx > (iIndex + bidiTexts[i].str.length)) {
  137. iIndex += bidiTexts[i].str.length;
  138. i++;
  139. }
  140. match.end = {
  141. divIdx: i,
  142. offset: matchIdx - iIndex
  143. };
  144. ret.push(match);
  145. }
  146. return ret;
  147. },
  148. renderMatches: function TextLayerBuilder_renderMatches(matches) {
  149. // Early exit if there is nothing to render.
  150. if (matches.length === 0) {
  151. return;
  152. }
  153. var bidiTexts = this.textContent.items;
  154. var textDivs = this.textDivs;
  155. var prevEnd = null;
  156. var pageIdx = this.pageIdx;
  157. var isSelectedPage = (this.findController === null ?
  158. false : (pageIdx === this.findController.selected.pageIdx));
  159. var selectedMatchIdx = (this.findController === null ?
  160. -1 : this.findController.selected.matchIdx);
  161. var highlightAll = (this.findController === null ?
  162. false : this.findController.state.highlightAll);
  163. var infinity = {
  164. divIdx: -1,
  165. offset: undefined
  166. };
  167. function beginText(begin, className) {
  168. var divIdx = begin.divIdx;
  169. textDivs[divIdx].textContent = '';
  170. appendTextToDiv(divIdx, 0, begin.offset, className);
  171. }
  172. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  173. var div = textDivs[divIdx];
  174. var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
  175. var node = document.createTextNode(content);
  176. if (className) {
  177. var span = document.createElement('span');
  178. span.className = className;
  179. span.appendChild(node);
  180. div.appendChild(span);
  181. return;
  182. }
  183. div.appendChild(node);
  184. }
  185. var i0 = selectedMatchIdx, i1 = i0 + 1;
  186. if (highlightAll) {
  187. i0 = 0;
  188. i1 = matches.length;
  189. } else if (!isSelectedPage) {
  190. // Not highlighting all and this isn't the selected page, so do nothing.
  191. return;
  192. }
  193. for (var i = i0; i < i1; i++) {
  194. var match = matches[i];
  195. var begin = match.begin;
  196. var end = match.end;
  197. var isSelected = (isSelectedPage && i === selectedMatchIdx);
  198. var highlightSuffix = (isSelected ? ' selected' : '');
  199. if (this.findController) {
  200. this.findController.updateMatchPosition(pageIdx, i, textDivs,
  201. begin.divIdx, end.divIdx);
  202. }
  203. // Match inside new div.
  204. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  205. // If there was a previous div, then add the text at the end.
  206. if (prevEnd !== null) {
  207. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  208. }
  209. // Clear the divs and set the content until the starting point.
  210. beginText(begin);
  211. } else {
  212. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  213. }
  214. if (begin.divIdx === end.divIdx) {
  215. appendTextToDiv(begin.divIdx, begin.offset, end.offset,
  216. 'highlight' + highlightSuffix);
  217. } else {
  218. appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
  219. 'highlight begin' + highlightSuffix);
  220. for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  221. textDivs[n0].className = 'highlight middle' + highlightSuffix;
  222. }
  223. beginText(end, 'highlight end' + highlightSuffix);
  224. }
  225. prevEnd = end;
  226. }
  227. if (prevEnd) {
  228. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  229. }
  230. },
  231. updateMatches: function TextLayerBuilder_updateMatches() {
  232. // Only show matches when all rendering is done.
  233. if (!this.renderingDone) {
  234. return;
  235. }
  236. // Clear all matches.
  237. var matches = this.matches;
  238. var textDivs = this.textDivs;
  239. var bidiTexts = this.textContent.items;
  240. var clearedUntilDivIdx = -1;
  241. // Clear all current matches.
  242. for (var i = 0, len = matches.length; i < len; i++) {
  243. var match = matches[i];
  244. var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  245. for (var n = begin, end = match.end.divIdx; n <= end; n++) {
  246. var div = textDivs[n];
  247. div.textContent = bidiTexts[n].str;
  248. div.className = '';
  249. }
  250. clearedUntilDivIdx = match.end.divIdx + 1;
  251. }
  252. if (this.findController === null || !this.findController.active) {
  253. return;
  254. }
  255. // Convert the matches on the page controller into the match format
  256. // used for the textLayer.
  257. this.matches = this.convertMatches(this.findController === null ?
  258. [] : (this.findController.pageMatches[this.pageIdx] || []));
  259. this.renderMatches(this.matches);
  260. },
  261. /**
  262. * Fixes text selection: adds additional div where mouse was clicked.
  263. * This reduces flickering of the content if mouse slowly dragged down/up.
  264. * @private
  265. */
  266. _bindMouse: function TextLayerBuilder_bindMouse() {
  267. var div = this.textLayerDiv;
  268. div.addEventListener('mousedown', function (e) {
  269. var end = div.querySelector('.endOfContent');
  270. if (!end) {
  271. return;
  272. }
  273. //#if !(MOZCENTRAL || FIREFOX)
  274. // On non-Firefox browsers, the selection will feel better if the height
  275. // of the endOfContent div will be adjusted to start at mouse click
  276. // location -- this will avoid flickering when selections moves up.
  277. // However it does not work when selection started on empty space.
  278. var adjustTop = e.target !== div;
  279. //#if GENERIC
  280. adjustTop = adjustTop && window.getComputedStyle(end).
  281. getPropertyValue('-moz-user-select') !== 'none';
  282. //#endif
  283. if (adjustTop) {
  284. var divBounds = div.getBoundingClientRect();
  285. var r = Math.max(0, (e.pageY - divBounds.top) / divBounds.height);
  286. end.style.top = (r * 100).toFixed(2) + '%';
  287. }
  288. //#endif
  289. end.classList.add('active');
  290. });
  291. div.addEventListener('mouseup', function (e) {
  292. var end = div.querySelector('.endOfContent');
  293. if (!end) {
  294. return;
  295. }
  296. //#if !(MOZCENTRAL || FIREFOX)
  297. end.style.top = '';
  298. //#endif
  299. end.classList.remove('active');
  300. });
  301. },
  302. };
  303. return TextLayerBuilder;
  304. })();
  305. /**
  306. * @constructor
  307. * @implements IPDFTextLayerFactory
  308. */
  309. function DefaultTextLayerFactory() {}
  310. DefaultTextLayerFactory.prototype = {
  311. /**
  312. * @param {HTMLDivElement} textLayerDiv
  313. * @param {number} pageIndex
  314. * @param {PageViewport} viewport
  315. * @returns {TextLayerBuilder}
  316. */
  317. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  318. return new TextLayerBuilder({
  319. textLayerDiv: textLayerDiv,
  320. pageIndex: pageIndex,
  321. viewport: viewport
  322. });
  323. }
  324. };
  325. exports.TextLayerBuilder = TextLayerBuilder;
  326. exports.DefaultTextLayerFactory = DefaultTextLayerFactory;
  327. }));