2
0

pdf_find_controller.js 14 KB

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