pdf_find_controller.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2017 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.PDFFindController = exports.FindState = undefined;
  27. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  28. var _pdf = require('../pdf');
  29. var _ui_utils = require('./ui_utils');
  30. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31. var FindState = {
  32. FOUND: 0,
  33. NOT_FOUND: 1,
  34. WRAPPED: 2,
  35. PENDING: 3
  36. };
  37. var FIND_SCROLL_OFFSET_TOP = -50;
  38. var FIND_SCROLL_OFFSET_LEFT = -400;
  39. var FIND_TIMEOUT = 250;
  40. var CHARACTERS_TO_NORMALIZE = {
  41. '\u2018': '\'',
  42. '\u2019': '\'',
  43. '\u201A': '\'',
  44. '\u201B': '\'',
  45. '\u201C': '"',
  46. '\u201D': '"',
  47. '\u201E': '"',
  48. '\u201F': '"',
  49. '\xBC': '1/4',
  50. '\xBD': '1/2',
  51. '\xBE': '3/4'
  52. };
  53. var PDFFindController = function () {
  54. function PDFFindController(_ref) {
  55. var pdfViewer = _ref.pdfViewer;
  56. _classCallCheck(this, PDFFindController);
  57. this.pdfViewer = pdfViewer;
  58. this.onUpdateResultsCount = null;
  59. this.onUpdateState = null;
  60. this.reset();
  61. var replace = Object.keys(CHARACTERS_TO_NORMALIZE).join('');
  62. this.normalizationRegex = new RegExp('[' + replace + ']', 'g');
  63. }
  64. _createClass(PDFFindController, [{
  65. key: 'reset',
  66. value: function reset() {
  67. var _this = this;
  68. this.startedTextExtraction = false;
  69. this.extractTextPromises = [];
  70. this.pendingFindMatches = Object.create(null);
  71. this.active = false;
  72. this.pageContents = [];
  73. this.pageMatches = [];
  74. this.pageMatchesLength = null;
  75. this.matchCount = 0;
  76. this.selected = {
  77. pageIdx: -1,
  78. matchIdx: -1
  79. };
  80. this.offset = {
  81. pageIdx: null,
  82. matchIdx: null
  83. };
  84. this.pagesToSearch = null;
  85. this.resumePageIdx = null;
  86. this.state = null;
  87. this.dirtyMatch = false;
  88. this.findTimeout = null;
  89. this._firstPagePromise = new Promise(function (resolve) {
  90. _this.resolveFirstPage = resolve;
  91. });
  92. }
  93. }, {
  94. key: 'normalize',
  95. value: function normalize(text) {
  96. return text.replace(this.normalizationRegex, function (ch) {
  97. return CHARACTERS_TO_NORMALIZE[ch];
  98. });
  99. }
  100. }, {
  101. key: '_prepareMatches',
  102. value: function _prepareMatches(matchesWithLength, matches, matchesLength) {
  103. function isSubTerm(matchesWithLength, currentIndex) {
  104. var currentElem = matchesWithLength[currentIndex];
  105. var nextElem = matchesWithLength[currentIndex + 1];
  106. if (currentIndex < matchesWithLength.length - 1 && currentElem.match === nextElem.match) {
  107. currentElem.skipped = true;
  108. return true;
  109. }
  110. for (var i = currentIndex - 1; i >= 0; i--) {
  111. var prevElem = matchesWithLength[i];
  112. if (prevElem.skipped) {
  113. continue;
  114. }
  115. if (prevElem.match + prevElem.matchLength < currentElem.match) {
  116. break;
  117. }
  118. if (prevElem.match + prevElem.matchLength >= currentElem.match + currentElem.matchLength) {
  119. currentElem.skipped = true;
  120. return true;
  121. }
  122. }
  123. return false;
  124. }
  125. matchesWithLength.sort(function (a, b) {
  126. return a.match === b.match ? a.matchLength - b.matchLength : a.match - b.match;
  127. });
  128. for (var i = 0, len = matchesWithLength.length; i < len; i++) {
  129. if (isSubTerm(matchesWithLength, i)) {
  130. continue;
  131. }
  132. matches.push(matchesWithLength[i].match);
  133. matchesLength.push(matchesWithLength[i].matchLength);
  134. }
  135. }
  136. }, {
  137. key: 'calcFindPhraseMatch',
  138. value: function calcFindPhraseMatch(query, pageIndex, pageContent) {
  139. var matches = [];
  140. var queryLen = query.length;
  141. var matchIdx = -queryLen;
  142. while (true) {
  143. matchIdx = pageContent.indexOf(query, matchIdx + queryLen);
  144. if (matchIdx === -1) {
  145. break;
  146. }
  147. matches.push(matchIdx);
  148. }
  149. this.pageMatches[pageIndex] = matches;
  150. }
  151. }, {
  152. key: 'calcFindWordMatch',
  153. value: function calcFindWordMatch(query, pageIndex, pageContent) {
  154. var matchesWithLength = [];
  155. var queryArray = query.match(/\S+/g);
  156. for (var i = 0, len = queryArray.length; i < len; i++) {
  157. var subquery = queryArray[i];
  158. var subqueryLen = subquery.length;
  159. var matchIdx = -subqueryLen;
  160. while (true) {
  161. matchIdx = pageContent.indexOf(subquery, matchIdx + subqueryLen);
  162. if (matchIdx === -1) {
  163. break;
  164. }
  165. matchesWithLength.push({
  166. match: matchIdx,
  167. matchLength: subqueryLen,
  168. skipped: false
  169. });
  170. }
  171. }
  172. if (!this.pageMatchesLength) {
  173. this.pageMatchesLength = [];
  174. }
  175. this.pageMatchesLength[pageIndex] = [];
  176. this.pageMatches[pageIndex] = [];
  177. this._prepareMatches(matchesWithLength, this.pageMatches[pageIndex], this.pageMatchesLength[pageIndex]);
  178. }
  179. }, {
  180. key: 'calcFindMatch',
  181. value: function calcFindMatch(pageIndex) {
  182. var pageContent = this.normalize(this.pageContents[pageIndex]);
  183. var query = this.normalize(this.state.query);
  184. var caseSensitive = this.state.caseSensitive;
  185. var phraseSearch = this.state.phraseSearch;
  186. var queryLen = query.length;
  187. if (queryLen === 0) {
  188. return;
  189. }
  190. if (!caseSensitive) {
  191. pageContent = pageContent.toLowerCase();
  192. query = query.toLowerCase();
  193. }
  194. if (phraseSearch) {
  195. this.calcFindPhraseMatch(query, pageIndex, pageContent);
  196. } else {
  197. this.calcFindWordMatch(query, pageIndex, pageContent);
  198. }
  199. this.updatePage(pageIndex);
  200. if (this.resumePageIdx === pageIndex) {
  201. this.resumePageIdx = null;
  202. this.nextPageMatch();
  203. }
  204. if (this.pageMatches[pageIndex].length > 0) {
  205. this.matchCount += this.pageMatches[pageIndex].length;
  206. this.updateUIResultsCount();
  207. }
  208. }
  209. }, {
  210. key: 'extractText',
  211. value: function extractText() {
  212. var _this2 = this;
  213. if (this.startedTextExtraction) {
  214. return;
  215. }
  216. this.startedTextExtraction = true;
  217. this.pageContents.length = 0;
  218. var promise = Promise.resolve();
  219. var _loop = function _loop(i, ii) {
  220. var extractTextCapability = (0, _pdf.createPromiseCapability)();
  221. _this2.extractTextPromises[i] = extractTextCapability.promise;
  222. promise = promise.then(function () {
  223. return _this2.pdfViewer.getPageTextContent(i).then(function (textContent) {
  224. var textItems = textContent.items;
  225. var strBuf = [];
  226. for (var j = 0, jj = textItems.length; j < jj; j++) {
  227. strBuf.push(textItems[j].str);
  228. }
  229. _this2.pageContents[i] = strBuf.join('');
  230. extractTextCapability.resolve(i);
  231. }, function (reason) {
  232. console.error('Unable to get page ' + (i + 1) + ' text content', reason);
  233. _this2.pageContents[i] = '';
  234. extractTextCapability.resolve(i);
  235. });
  236. });
  237. };
  238. for (var i = 0, ii = this.pdfViewer.pagesCount; i < ii; i++) {
  239. _loop(i, ii);
  240. }
  241. }
  242. }, {
  243. key: 'executeCommand',
  244. value: function executeCommand(cmd, state) {
  245. var _this3 = this;
  246. if (this.state === null || cmd !== 'findagain') {
  247. this.dirtyMatch = true;
  248. }
  249. this.state = state;
  250. this.updateUIState(FindState.PENDING);
  251. this._firstPagePromise.then(function () {
  252. _this3.extractText();
  253. clearTimeout(_this3.findTimeout);
  254. if (cmd === 'find') {
  255. _this3.findTimeout = setTimeout(_this3.nextMatch.bind(_this3), FIND_TIMEOUT);
  256. } else {
  257. _this3.nextMatch();
  258. }
  259. });
  260. }
  261. }, {
  262. key: 'updatePage',
  263. value: function updatePage(index) {
  264. if (this.selected.pageIdx === index) {
  265. this.pdfViewer.currentPageNumber = index + 1;
  266. }
  267. var page = this.pdfViewer.getPageView(index);
  268. if (page.textLayer) {
  269. page.textLayer.updateMatches();
  270. }
  271. }
  272. }, {
  273. key: 'nextMatch',
  274. value: function nextMatch() {
  275. var _this4 = this;
  276. var previous = this.state.findPrevious;
  277. var currentPageIndex = this.pdfViewer.currentPageNumber - 1;
  278. var numPages = this.pdfViewer.pagesCount;
  279. this.active = true;
  280. if (this.dirtyMatch) {
  281. this.dirtyMatch = false;
  282. this.selected.pageIdx = this.selected.matchIdx = -1;
  283. this.offset.pageIdx = currentPageIndex;
  284. this.offset.matchIdx = null;
  285. this.hadMatch = false;
  286. this.resumePageIdx = null;
  287. this.pageMatches = [];
  288. this.matchCount = 0;
  289. this.pageMatchesLength = null;
  290. for (var i = 0; i < numPages; i++) {
  291. this.updatePage(i);
  292. if (!(i in this.pendingFindMatches)) {
  293. this.pendingFindMatches[i] = true;
  294. this.extractTextPromises[i].then(function (pageIdx) {
  295. delete _this4.pendingFindMatches[pageIdx];
  296. _this4.calcFindMatch(pageIdx);
  297. });
  298. }
  299. }
  300. }
  301. if (this.state.query === '') {
  302. this.updateUIState(FindState.FOUND);
  303. return;
  304. }
  305. if (this.resumePageIdx) {
  306. return;
  307. }
  308. var offset = this.offset;
  309. this.pagesToSearch = numPages;
  310. if (offset.matchIdx !== null) {
  311. var numPageMatches = this.pageMatches[offset.pageIdx].length;
  312. if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) {
  313. this.hadMatch = true;
  314. offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1;
  315. this.updateMatch(true);
  316. return;
  317. }
  318. this.advanceOffsetPage(previous);
  319. }
  320. this.nextPageMatch();
  321. }
  322. }, {
  323. key: 'matchesReady',
  324. value: function matchesReady(matches) {
  325. var offset = this.offset;
  326. var numMatches = matches.length;
  327. var previous = this.state.findPrevious;
  328. if (numMatches) {
  329. this.hadMatch = true;
  330. offset.matchIdx = previous ? numMatches - 1 : 0;
  331. this.updateMatch(true);
  332. return true;
  333. }
  334. this.advanceOffsetPage(previous);
  335. if (offset.wrapped) {
  336. offset.matchIdx = null;
  337. if (this.pagesToSearch < 0) {
  338. this.updateMatch(false);
  339. return true;
  340. }
  341. }
  342. return false;
  343. }
  344. }, {
  345. key: 'updateMatchPosition',
  346. value: function updateMatchPosition(pageIndex, matchIndex, elements, beginIdx) {
  347. if (this.selected.matchIdx === matchIndex && this.selected.pageIdx === pageIndex) {
  348. var spot = {
  349. top: FIND_SCROLL_OFFSET_TOP,
  350. left: FIND_SCROLL_OFFSET_LEFT
  351. };
  352. (0, _ui_utils.scrollIntoView)(elements[beginIdx], spot, true);
  353. }
  354. }
  355. }, {
  356. key: 'nextPageMatch',
  357. value: function nextPageMatch() {
  358. if (this.resumePageIdx !== null) {
  359. console.error('There can only be one pending page.');
  360. }
  361. var matches = null;
  362. do {
  363. var pageIdx = this.offset.pageIdx;
  364. matches = this.pageMatches[pageIdx];
  365. if (!matches) {
  366. this.resumePageIdx = pageIdx;
  367. break;
  368. }
  369. } while (!this.matchesReady(matches));
  370. }
  371. }, {
  372. key: 'advanceOffsetPage',
  373. value: function advanceOffsetPage(previous) {
  374. var offset = this.offset;
  375. var numPages = this.extractTextPromises.length;
  376. offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1;
  377. offset.matchIdx = null;
  378. this.pagesToSearch--;
  379. if (offset.pageIdx >= numPages || offset.pageIdx < 0) {
  380. offset.pageIdx = previous ? numPages - 1 : 0;
  381. offset.wrapped = true;
  382. }
  383. }
  384. }, {
  385. key: 'updateMatch',
  386. value: function updateMatch() {
  387. var found = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  388. var state = FindState.NOT_FOUND;
  389. var wrapped = this.offset.wrapped;
  390. this.offset.wrapped = false;
  391. if (found) {
  392. var previousPage = this.selected.pageIdx;
  393. this.selected.pageIdx = this.offset.pageIdx;
  394. this.selected.matchIdx = this.offset.matchIdx;
  395. state = wrapped ? FindState.WRAPPED : FindState.FOUND;
  396. if (previousPage !== -1 && previousPage !== this.selected.pageIdx) {
  397. this.updatePage(previousPage);
  398. }
  399. }
  400. this.updateUIState(state, this.state.findPrevious);
  401. if (this.selected.pageIdx !== -1) {
  402. this.updatePage(this.selected.pageIdx);
  403. }
  404. }
  405. }, {
  406. key: 'updateUIResultsCount',
  407. value: function updateUIResultsCount() {
  408. if (this.onUpdateResultsCount) {
  409. this.onUpdateResultsCount(this.matchCount);
  410. }
  411. }
  412. }, {
  413. key: 'updateUIState',
  414. value: function updateUIState(state, previous) {
  415. if (this.onUpdateState) {
  416. this.onUpdateState(state, previous, this.matchCount);
  417. }
  418. }
  419. }]);
  420. return PDFFindController;
  421. }();
  422. exports.FindState = FindState;
  423. exports.PDFFindController = PDFFindController;