pdf_find_controller.js 21 KB

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