2
0

pdf_find_controller.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 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 = void 0;
  27. var _ui_utils = require("./ui_utils.js");
  28. var _pdf = require("../pdf");
  29. var _pdf_find_utils = require("./pdf_find_utils.js");
  30. const FindState = {
  31. FOUND: 0,
  32. NOT_FOUND: 1,
  33. WRAPPED: 2,
  34. PENDING: 3
  35. };
  36. exports.FindState = FindState;
  37. const FIND_TIMEOUT = 250;
  38. const MATCH_SCROLL_OFFSET_TOP = -50;
  39. const MATCH_SCROLL_OFFSET_LEFT = -400;
  40. const CHARACTERS_TO_NORMALIZE = {
  41. "\u2010": "-",
  42. "\u2018": "'",
  43. "\u2019": "'",
  44. "\u201A": "'",
  45. "\u201B": "'",
  46. "\u201C": '"',
  47. "\u201D": '"',
  48. "\u201E": '"',
  49. "\u201F": '"',
  50. "\u00BC": "1/4",
  51. "\u00BD": "1/2",
  52. "\u00BE": "3/4"
  53. };
  54. const DIACRITICS_EXCEPTION = new Set([0x3099, 0x309a, 0x094d, 0x09cd, 0x0a4d, 0x0acd, 0x0b4d, 0x0bcd, 0x0c4d, 0x0ccd, 0x0d3b, 0x0d3c, 0x0d4d, 0x0dca, 0x0e3a, 0x0eba, 0x0f84, 0x1039, 0x103a, 0x1714, 0x1734, 0x17d2, 0x1a60, 0x1b44, 0x1baa, 0x1bab, 0x1bf2, 0x1bf3, 0x2d7f, 0xa806, 0xa82c, 0xa8c4, 0xa953, 0xa9c0, 0xaaf6, 0xabed, 0x0c56, 0x0f71, 0x0f72, 0x0f7a, 0x0f7b, 0x0f7c, 0x0f7d, 0x0f80, 0x0f74]);
  55. const DIACRITICS_EXCEPTION_STR = [...DIACRITICS_EXCEPTION.values()].map(x => String.fromCharCode(x)).join("");
  56. const DIACRITICS_REG_EXP = /\p{M}+/gu;
  57. const SPECIAL_CHARS_REG_EXP = /([.*+?^${}()|[\]\\])|(\p{P})|(\s+)|(\p{M})|(\p{L})/gu;
  58. const NOT_DIACRITIC_FROM_END_REG_EXP = /([^\p{M}])\p{M}*$/u;
  59. const NOT_DIACRITIC_FROM_START_REG_EXP = /^\p{M}*([^\p{M}])/u;
  60. const SYLLABLES_REG_EXP = /[\uAC00-\uD7AF\uFA6C\uFACF-\uFAD1\uFAD5-\uFAD7]+/g;
  61. const SYLLABLES_LENGTHS = new Map();
  62. const FIRST_CHAR_SYLLABLES_REG_EXP = "[\\u1100-\\u1112\\ud7a4-\\ud7af\\ud84a\\ud84c\\ud850\\ud854\\ud857\\ud85f]";
  63. let noSyllablesRegExp = null;
  64. let withSyllablesRegExp = null;
  65. function normalize(text) {
  66. const syllablePositions = [];
  67. let m;
  68. while ((m = SYLLABLES_REG_EXP.exec(text)) !== null) {
  69. let {
  70. index
  71. } = m;
  72. for (const char of m[0]) {
  73. let len = SYLLABLES_LENGTHS.get(char);
  74. if (!len) {
  75. len = char.normalize("NFD").length;
  76. SYLLABLES_LENGTHS.set(char, len);
  77. }
  78. syllablePositions.push([len, index++]);
  79. }
  80. }
  81. let normalizationRegex;
  82. if (syllablePositions.length === 0 && noSyllablesRegExp) {
  83. normalizationRegex = noSyllablesRegExp;
  84. } else if (syllablePositions.length > 0 && withSyllablesRegExp) {
  85. normalizationRegex = withSyllablesRegExp;
  86. } else {
  87. const replace = Object.keys(CHARACTERS_TO_NORMALIZE).join("");
  88. const regexp = `([${replace}])|(\\p{M}+(?:-\\n)?)|(\\S-\\n)|(\\n)`;
  89. if (syllablePositions.length === 0) {
  90. normalizationRegex = noSyllablesRegExp = new RegExp(regexp + "|(\\u0000)", "gum");
  91. } else {
  92. normalizationRegex = withSyllablesRegExp = new RegExp(regexp + `|(${FIRST_CHAR_SYLLABLES_REG_EXP})`, "gum");
  93. }
  94. }
  95. const rawDiacriticsPositions = [];
  96. while ((m = DIACRITICS_REG_EXP.exec(text)) !== null) {
  97. rawDiacriticsPositions.push([m[0].length, m.index]);
  98. }
  99. let normalized = text.normalize("NFD");
  100. const positions = [[0, 0]];
  101. let rawDiacriticsIndex = 0;
  102. let syllableIndex = 0;
  103. let shift = 0;
  104. let shiftOrigin = 0;
  105. let eol = 0;
  106. let hasDiacritics = false;
  107. normalized = normalized.replace(normalizationRegex, (match, p1, p2, p3, p4, p5, i) => {
  108. i -= shiftOrigin;
  109. if (p1) {
  110. const replacement = CHARACTERS_TO_NORMALIZE[match];
  111. const jj = replacement.length;
  112. for (let j = 1; j < jj; j++) {
  113. positions.push([i - shift + j, shift - j]);
  114. }
  115. shift -= jj - 1;
  116. return replacement;
  117. }
  118. if (p2) {
  119. const hasTrailingDashEOL = p2.endsWith("\n");
  120. const len = hasTrailingDashEOL ? p2.length - 2 : p2.length;
  121. hasDiacritics = true;
  122. let jj = len;
  123. if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) {
  124. jj -= rawDiacriticsPositions[rawDiacriticsIndex][0];
  125. ++rawDiacriticsIndex;
  126. }
  127. for (let j = 1; j <= jj; j++) {
  128. positions.push([i - 1 - shift + j, shift - j]);
  129. }
  130. shift -= jj;
  131. shiftOrigin += jj;
  132. if (hasTrailingDashEOL) {
  133. i += len - 1;
  134. positions.push([i - shift + 1, 1 + shift]);
  135. shift += 1;
  136. shiftOrigin += 1;
  137. eol += 1;
  138. return p2.slice(0, len);
  139. }
  140. return p2;
  141. }
  142. if (p3) {
  143. positions.push([i - shift + 1, 1 + shift]);
  144. shift += 1;
  145. shiftOrigin += 1;
  146. eol += 1;
  147. return p3.charAt(0);
  148. }
  149. if (p4) {
  150. positions.push([i - shift + 1, shift - 1]);
  151. shift -= 1;
  152. shiftOrigin += 1;
  153. eol += 1;
  154. return " ";
  155. }
  156. if (i + eol === syllablePositions[syllableIndex]?.[1]) {
  157. const newCharLen = syllablePositions[syllableIndex][0] - 1;
  158. ++syllableIndex;
  159. for (let j = 1; j <= newCharLen; j++) {
  160. positions.push([i - (shift - j), shift - j]);
  161. }
  162. shift -= newCharLen;
  163. shiftOrigin += newCharLen;
  164. }
  165. return p5;
  166. });
  167. positions.push([normalized.length, shift]);
  168. return [normalized, positions, hasDiacritics];
  169. }
  170. function getOriginalIndex(diffs, pos, len) {
  171. if (!diffs) {
  172. return [pos, len];
  173. }
  174. const start = pos;
  175. const end = pos + len;
  176. let i = (0, _ui_utils.binarySearchFirstItem)(diffs, x => x[0] >= start);
  177. if (diffs[i][0] > start) {
  178. --i;
  179. }
  180. let j = (0, _ui_utils.binarySearchFirstItem)(diffs, x => x[0] >= end, i);
  181. if (diffs[j][0] > end) {
  182. --j;
  183. }
  184. return [start + diffs[i][1], len + diffs[j][1] - diffs[i][1]];
  185. }
  186. class PDFFindController {
  187. constructor({
  188. linkService,
  189. eventBus
  190. }) {
  191. this._linkService = linkService;
  192. this._eventBus = eventBus;
  193. this.#reset();
  194. eventBus._on("find", this.#onFind.bind(this));
  195. eventBus._on("findbarclose", this.#onFindBarClose.bind(this));
  196. }
  197. get highlightMatches() {
  198. return this._highlightMatches;
  199. }
  200. get pageMatches() {
  201. return this._pageMatches;
  202. }
  203. get pageMatchesLength() {
  204. return this._pageMatchesLength;
  205. }
  206. get selected() {
  207. return this._selected;
  208. }
  209. get state() {
  210. return this._state;
  211. }
  212. setDocument(pdfDocument) {
  213. if (this._pdfDocument) {
  214. this.#reset();
  215. }
  216. if (!pdfDocument) {
  217. return;
  218. }
  219. this._pdfDocument = pdfDocument;
  220. this._firstPageCapability.resolve();
  221. }
  222. #onFind(state) {
  223. if (!state) {
  224. return;
  225. }
  226. const pdfDocument = this._pdfDocument;
  227. const {
  228. type
  229. } = state;
  230. if (this._state === null || this.#shouldDirtyMatch(state)) {
  231. this._dirtyMatch = true;
  232. }
  233. this._state = state;
  234. if (type !== "highlightallchange") {
  235. this.#updateUIState(FindState.PENDING);
  236. }
  237. this._firstPageCapability.promise.then(() => {
  238. if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) {
  239. return;
  240. }
  241. this.#extractText();
  242. const findbarClosed = !this._highlightMatches;
  243. const pendingTimeout = !!this._findTimeout;
  244. if (this._findTimeout) {
  245. clearTimeout(this._findTimeout);
  246. this._findTimeout = null;
  247. }
  248. if (!type) {
  249. this._findTimeout = setTimeout(() => {
  250. this.#nextMatch();
  251. this._findTimeout = null;
  252. }, FIND_TIMEOUT);
  253. } else if (this._dirtyMatch) {
  254. this.#nextMatch();
  255. } else if (type === "again") {
  256. this.#nextMatch();
  257. if (findbarClosed && this._state.highlightAll) {
  258. this.#updateAllPages();
  259. }
  260. } else if (type === "highlightallchange") {
  261. if (pendingTimeout) {
  262. this.#nextMatch();
  263. } else {
  264. this._highlightMatches = true;
  265. }
  266. this.#updateAllPages();
  267. } else {
  268. this.#nextMatch();
  269. }
  270. });
  271. }
  272. scrollMatchIntoView({
  273. element = null,
  274. selectedLeft = 0,
  275. pageIndex = -1,
  276. matchIndex = -1
  277. }) {
  278. if (!this._scrollMatches || !element) {
  279. return;
  280. } else if (matchIndex === -1 || matchIndex !== this._selected.matchIdx) {
  281. return;
  282. } else if (pageIndex === -1 || pageIndex !== this._selected.pageIdx) {
  283. return;
  284. }
  285. this._scrollMatches = false;
  286. const spot = {
  287. top: MATCH_SCROLL_OFFSET_TOP,
  288. left: selectedLeft + MATCH_SCROLL_OFFSET_LEFT
  289. };
  290. (0, _ui_utils.scrollIntoView)(element, spot, true);
  291. }
  292. #reset() {
  293. this._highlightMatches = false;
  294. this._scrollMatches = false;
  295. this._pdfDocument = null;
  296. this._pageMatches = [];
  297. this._pageMatchesLength = [];
  298. this._state = null;
  299. this._selected = {
  300. pageIdx: -1,
  301. matchIdx: -1
  302. };
  303. this._offset = {
  304. pageIdx: null,
  305. matchIdx: null,
  306. wrapped: false
  307. };
  308. this._extractTextPromises = [];
  309. this._pageContents = [];
  310. this._pageDiffs = [];
  311. this._hasDiacritics = [];
  312. this._matchesCountTotal = 0;
  313. this._pagesToSearch = null;
  314. this._pendingFindMatches = new Set();
  315. this._resumePageIdx = null;
  316. this._dirtyMatch = false;
  317. clearTimeout(this._findTimeout);
  318. this._findTimeout = null;
  319. this._firstPageCapability = (0, _pdf.createPromiseCapability)();
  320. }
  321. get #query() {
  322. if (this._state.query !== this._rawQuery) {
  323. this._rawQuery = this._state.query;
  324. [this._normalizedQuery] = normalize(this._state.query);
  325. }
  326. return this._normalizedQuery;
  327. }
  328. #shouldDirtyMatch(state) {
  329. if (state.query !== this._state.query) {
  330. return true;
  331. }
  332. switch (state.type) {
  333. case "again":
  334. const pageNumber = this._selected.pageIdx + 1;
  335. const linkService = this._linkService;
  336. if (pageNumber >= 1 && pageNumber <= linkService.pagesCount && pageNumber !== linkService.page && !linkService.isPageVisible(pageNumber)) {
  337. return true;
  338. }
  339. return false;
  340. case "highlightallchange":
  341. return false;
  342. }
  343. return true;
  344. }
  345. #isEntireWord(content, startIdx, length) {
  346. let match = content.slice(0, startIdx).match(NOT_DIACRITIC_FROM_END_REG_EXP);
  347. if (match) {
  348. const first = content.charCodeAt(startIdx);
  349. const limit = match[1].charCodeAt(0);
  350. if ((0, _pdf_find_utils.getCharacterType)(first) === (0, _pdf_find_utils.getCharacterType)(limit)) {
  351. return false;
  352. }
  353. }
  354. match = content.slice(startIdx + length).match(NOT_DIACRITIC_FROM_START_REG_EXP);
  355. if (match) {
  356. const last = content.charCodeAt(startIdx + length - 1);
  357. const limit = match[1].charCodeAt(0);
  358. if ((0, _pdf_find_utils.getCharacterType)(last) === (0, _pdf_find_utils.getCharacterType)(limit)) {
  359. return false;
  360. }
  361. }
  362. return true;
  363. }
  364. #calculateRegExpMatch(query, entireWord, pageIndex, pageContent) {
  365. const matches = [],
  366. matchesLength = [];
  367. const diffs = this._pageDiffs[pageIndex];
  368. let match;
  369. while ((match = query.exec(pageContent)) !== null) {
  370. if (entireWord && !this.#isEntireWord(pageContent, match.index, match[0].length)) {
  371. continue;
  372. }
  373. const [matchPos, matchLen] = getOriginalIndex(diffs, match.index, match[0].length);
  374. if (matchLen) {
  375. matches.push(matchPos);
  376. matchesLength.push(matchLen);
  377. }
  378. }
  379. this._pageMatches[pageIndex] = matches;
  380. this._pageMatchesLength[pageIndex] = matchesLength;
  381. }
  382. #convertToRegExpString(query, hasDiacritics) {
  383. const {
  384. matchDiacritics
  385. } = this._state;
  386. let isUnicode = false;
  387. query = query.replace(SPECIAL_CHARS_REG_EXP, (match, p1, p2, p3, p4, p5) => {
  388. if (p1) {
  389. return `[ ]*\\${p1}[ ]*`;
  390. }
  391. if (p2) {
  392. return `[ ]*${p2}[ ]*`;
  393. }
  394. if (p3) {
  395. return "[ ]+";
  396. }
  397. if (matchDiacritics) {
  398. return p4 || p5;
  399. }
  400. if (p4) {
  401. return DIACRITICS_EXCEPTION.has(p4.charCodeAt(0)) ? p4 : "";
  402. }
  403. if (hasDiacritics) {
  404. isUnicode = true;
  405. return `${p5}\\p{M}*`;
  406. }
  407. return p5;
  408. });
  409. const trailingSpaces = "[ ]*";
  410. if (query.endsWith(trailingSpaces)) {
  411. query = query.slice(0, query.length - trailingSpaces.length);
  412. }
  413. if (matchDiacritics) {
  414. if (hasDiacritics) {
  415. isUnicode = true;
  416. query = `${query}(?=[${DIACRITICS_EXCEPTION_STR}]|[^\\p{M}]|$)`;
  417. }
  418. }
  419. return [isUnicode, query];
  420. }
  421. #calculateMatch(pageIndex) {
  422. let query = this.#query;
  423. if (query.length === 0) {
  424. return;
  425. }
  426. const {
  427. caseSensitive,
  428. entireWord,
  429. phraseSearch
  430. } = this._state;
  431. const pageContent = this._pageContents[pageIndex];
  432. const hasDiacritics = this._hasDiacritics[pageIndex];
  433. let isUnicode = false;
  434. if (phraseSearch) {
  435. [isUnicode, query] = this.#convertToRegExpString(query, hasDiacritics);
  436. } else {
  437. const match = query.match(/\S+/g);
  438. if (match) {
  439. query = match.sort().reverse().map(q => {
  440. const [isUnicodePart, queryPart] = this.#convertToRegExpString(q, hasDiacritics);
  441. isUnicode ||= isUnicodePart;
  442. return `(${queryPart})`;
  443. }).join("|");
  444. }
  445. }
  446. const flags = `g${isUnicode ? "u" : ""}${caseSensitive ? "" : "i"}`;
  447. query = new RegExp(query, flags);
  448. this.#calculateRegExpMatch(query, entireWord, pageIndex, pageContent);
  449. if (this._state.highlightAll) {
  450. this.#updatePage(pageIndex);
  451. }
  452. if (this._resumePageIdx === pageIndex) {
  453. this._resumePageIdx = null;
  454. this.#nextPageMatch();
  455. }
  456. const pageMatchesCount = this._pageMatches[pageIndex].length;
  457. if (pageMatchesCount > 0) {
  458. this._matchesCountTotal += pageMatchesCount;
  459. this.#updateUIResultsCount();
  460. }
  461. }
  462. #extractText() {
  463. if (this._extractTextPromises.length > 0) {
  464. return;
  465. }
  466. let promise = Promise.resolve();
  467. for (let i = 0, ii = this._linkService.pagesCount; i < ii; i++) {
  468. const extractTextCapability = (0, _pdf.createPromiseCapability)();
  469. this._extractTextPromises[i] = extractTextCapability.promise;
  470. promise = promise.then(() => {
  471. return this._pdfDocument.getPage(i + 1).then(pdfPage => {
  472. return pdfPage.getTextContent();
  473. }).then(textContent => {
  474. const strBuf = [];
  475. for (const textItem of textContent.items) {
  476. strBuf.push(textItem.str);
  477. if (textItem.hasEOL) {
  478. strBuf.push("\n");
  479. }
  480. }
  481. [this._pageContents[i], this._pageDiffs[i], this._hasDiacritics[i]] = normalize(strBuf.join(""));
  482. extractTextCapability.resolve();
  483. }, reason => {
  484. console.error(`Unable to get text content for page ${i + 1}`, reason);
  485. this._pageContents[i] = "";
  486. this._pageDiffs[i] = null;
  487. this._hasDiacritics[i] = false;
  488. extractTextCapability.resolve();
  489. });
  490. });
  491. }
  492. }
  493. #updatePage(index) {
  494. if (this._scrollMatches && this._selected.pageIdx === index) {
  495. this._linkService.page = index + 1;
  496. }
  497. this._eventBus.dispatch("updatetextlayermatches", {
  498. source: this,
  499. pageIndex: index
  500. });
  501. }
  502. #updateAllPages() {
  503. this._eventBus.dispatch("updatetextlayermatches", {
  504. source: this,
  505. pageIndex: -1
  506. });
  507. }
  508. #nextMatch() {
  509. const previous = this._state.findPrevious;
  510. const currentPageIndex = this._linkService.page - 1;
  511. const numPages = this._linkService.pagesCount;
  512. this._highlightMatches = true;
  513. if (this._dirtyMatch) {
  514. this._dirtyMatch = false;
  515. this._selected.pageIdx = this._selected.matchIdx = -1;
  516. this._offset.pageIdx = currentPageIndex;
  517. this._offset.matchIdx = null;
  518. this._offset.wrapped = false;
  519. this._resumePageIdx = null;
  520. this._pageMatches.length = 0;
  521. this._pageMatchesLength.length = 0;
  522. this._matchesCountTotal = 0;
  523. this.#updateAllPages();
  524. for (let i = 0; i < numPages; i++) {
  525. if (this._pendingFindMatches.has(i)) {
  526. continue;
  527. }
  528. this._pendingFindMatches.add(i);
  529. this._extractTextPromises[i].then(() => {
  530. this._pendingFindMatches.delete(i);
  531. this.#calculateMatch(i);
  532. });
  533. }
  534. }
  535. if (this.#query === "") {
  536. this.#updateUIState(FindState.FOUND);
  537. return;
  538. }
  539. if (this._resumePageIdx) {
  540. return;
  541. }
  542. const offset = this._offset;
  543. this._pagesToSearch = numPages;
  544. if (offset.matchIdx !== null) {
  545. const numPageMatches = this._pageMatches[offset.pageIdx].length;
  546. if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) {
  547. offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1;
  548. this.#updateMatch(true);
  549. return;
  550. }
  551. this.#advanceOffsetPage(previous);
  552. }
  553. this.#nextPageMatch();
  554. }
  555. #matchesReady(matches) {
  556. const offset = this._offset;
  557. const numMatches = matches.length;
  558. const previous = this._state.findPrevious;
  559. if (numMatches) {
  560. offset.matchIdx = previous ? numMatches - 1 : 0;
  561. this.#updateMatch(true);
  562. return true;
  563. }
  564. this.#advanceOffsetPage(previous);
  565. if (offset.wrapped) {
  566. offset.matchIdx = null;
  567. if (this._pagesToSearch < 0) {
  568. this.#updateMatch(false);
  569. return true;
  570. }
  571. }
  572. return false;
  573. }
  574. #nextPageMatch() {
  575. if (this._resumePageIdx !== null) {
  576. console.error("There can only be one pending page.");
  577. }
  578. let matches = null;
  579. do {
  580. const pageIdx = this._offset.pageIdx;
  581. matches = this._pageMatches[pageIdx];
  582. if (!matches) {
  583. this._resumePageIdx = pageIdx;
  584. break;
  585. }
  586. } while (!this.#matchesReady(matches));
  587. }
  588. #advanceOffsetPage(previous) {
  589. const offset = this._offset;
  590. const numPages = this._linkService.pagesCount;
  591. offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1;
  592. offset.matchIdx = null;
  593. this._pagesToSearch--;
  594. if (offset.pageIdx >= numPages || offset.pageIdx < 0) {
  595. offset.pageIdx = previous ? numPages - 1 : 0;
  596. offset.wrapped = true;
  597. }
  598. }
  599. #updateMatch(found = false) {
  600. let state = FindState.NOT_FOUND;
  601. const wrapped = this._offset.wrapped;
  602. this._offset.wrapped = false;
  603. if (found) {
  604. const previousPage = this._selected.pageIdx;
  605. this._selected.pageIdx = this._offset.pageIdx;
  606. this._selected.matchIdx = this._offset.matchIdx;
  607. state = wrapped ? FindState.WRAPPED : FindState.FOUND;
  608. if (previousPage !== -1 && previousPage !== this._selected.pageIdx) {
  609. this.#updatePage(previousPage);
  610. }
  611. }
  612. this.#updateUIState(state, this._state.findPrevious);
  613. if (this._selected.pageIdx !== -1) {
  614. this._scrollMatches = true;
  615. this.#updatePage(this._selected.pageIdx);
  616. }
  617. }
  618. #onFindBarClose(evt) {
  619. const pdfDocument = this._pdfDocument;
  620. this._firstPageCapability.promise.then(() => {
  621. if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) {
  622. return;
  623. }
  624. if (this._findTimeout) {
  625. clearTimeout(this._findTimeout);
  626. this._findTimeout = null;
  627. }
  628. if (this._resumePageIdx) {
  629. this._resumePageIdx = null;
  630. this._dirtyMatch = true;
  631. }
  632. this.#updateUIState(FindState.FOUND);
  633. this._highlightMatches = false;
  634. this.#updateAllPages();
  635. });
  636. }
  637. #requestMatchesCount() {
  638. const {
  639. pageIdx,
  640. matchIdx
  641. } = this._selected;
  642. let current = 0,
  643. total = this._matchesCountTotal;
  644. if (matchIdx !== -1) {
  645. for (let i = 0; i < pageIdx; i++) {
  646. current += this._pageMatches[i]?.length || 0;
  647. }
  648. current += matchIdx + 1;
  649. }
  650. if (current < 1 || current > total) {
  651. current = total = 0;
  652. }
  653. return {
  654. current,
  655. total
  656. };
  657. }
  658. #updateUIResultsCount() {
  659. this._eventBus.dispatch("updatefindmatchescount", {
  660. source: this,
  661. matchesCount: this.#requestMatchesCount()
  662. });
  663. }
  664. #updateUIState(state, previous = false) {
  665. this._eventBus.dispatch("updatefindcontrolstate", {
  666. source: this,
  667. state,
  668. previous,
  669. matchesCount: this.#requestMatchesCount(),
  670. rawQuery: this._state?.query ?? null
  671. });
  672. }
  673. }
  674. exports.PDFFindController = PDFFindController;