pdf_find_controller.js 21 KB

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