From d67b9a24f0bce25fefccc08904bcac1713e52452 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Fri, 6 Dec 2024 22:20:12 +0000 Subject: [PATCH 01/37] Make the interface a bit more "brutalist" --- shortlister/controller.py | 111 ++++++++++++++++++++------------------ shortlister/view.py | 53 ++++++++---------- 2 files changed, 83 insertions(+), 81 deletions(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index 1bfa1cc..5d81924 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -1,3 +1,4 @@ +import string from pathlib import Path import sys from typing import List @@ -34,56 +35,58 @@ def __init__(self, path): self.shortlist = load_shortlist(path) self.applicant_index: int = 0 self.current_criterion = None - self.current_applicant_view = "List" + self.current_applicant_view = "Table" self.selected_applicants = self.shortlist.applicants self.view = View() self.options = None + self.available_keys = string.digits + string.ascii_letters + self.options_home = { - "a": (self.show_applicants_list_table, "applicants"), - "r": (self.show_role_info, "role"), - "q": (self.quit, "quit"), + "a": (self.show_applicants_list_table, "APPLICANTS"), + "r": (self.show_role_info, "ROLE"), + "q": (self.quit, "QUIT"), } self.options_applicant_list = { - "d": (self.show_applicant_details, "applicant"), - "S": (self.sort, "sort"), - "f":(self.filter_applicants,"filter"), - "c":(self.clear_filter,"remove all filter"), - "t": (self.show_applicants_list_table, "applicant table"), - "r":(self.rank_selected_applicants,"rank applicants"), - "q": (self.show_home_message, "home"), + "d": (self.show_applicant_details, "CHOOSE APPLICANT"), + "s": (self.sort, "SORT"), + "f": (self.filter_applicants,"FILTER"), + "c": (self.clear_filter,"CLEAR FILTER"), + "t": (self.show_applicants_list_table, "SWITCH TABLE"), + "r": (self.rank_selected_applicants,"RANK"), + "q": (self.show_home_message, "HOME"), } self.options_sort = { - "a": (self.sort, "alphabetically"), - "s": (self.sort, "sort (ascending)"), - "d": (self.sort, "sort (descending)"), + "a": (self.sort, "ALPHABETICAL"), + "s": (self.sort, "SCORE ASCENDING"), + "d": (self.sort, "SCORE DESCENDING"), } self.options_applicant_detail = { - "e": (self.edit_score_start, "score"), - "N": (self.create_applicant_note, "add note"), - "O": (self.open_applicant_pdf, "open CV"), - "n": (self.switch_applicant, "next"), - "p": (self.switch_applicant, "previous"), - "q": (self.show_applicants_list_table, "applicants"), + "e": (self.edit_score_start, "SCORE"), + "N": (self.create_applicant_note, "NOTE"), + "O": (self.open_applicant_pdf, "OPEN CV"), + "n": (self.switch_applicant, "NEXT"), + "p": (self.switch_applicant, "PREVIOUS"), + "q": (self.show_applicants_list_table, "APPLICANTS"), } def quit(self, k=None): # if we've activated quit if k == "q": # ask for confirmation - print("Are you sure? (y/n)") + print("ARE YOU SURE?") print() self.options = { - "n": (self.quit, "no"), - "y": (self.quit, "yes"), + "n": (self.quit, "NO"), + "y": (self.quit, "YES"), } elif k == "y": # quit confirmed - save and exit save_shortlist(self.path, self.shortlist) - print("Goodbye.") + print("GOODBYE.") sys.exit(0) else: # quit cancelled - back to home - print("Quit aborted") + print("QUIT CANCELLED") print() self.options = self.options_home @@ -92,10 +95,6 @@ def show_home_message(self, k=None): self.view.home_message(self.path, len(self.shortlist.applicants)) self.options = self.options_home - def show_criteria(self, k=None): - """Display criteria information.""" - self.view.view_criteria(self.shortlist.role, self.shortlist.role.criteria) - def show_role_info(self, k=None): """Display role information.""" self.view.view_role(self.shortlist.role) @@ -110,7 +109,7 @@ def show_applicants(self): def show_applicant_details(self, k=None): """Select an applicant via input and view details.""" try: - i = int(input("#")) + i = int(input("№> ")) print() self.applicant_index = i - 1 # Compensates for index self.view_applicant_details() @@ -140,13 +139,15 @@ def open_applicant_pdf(self, k=None): def edit_score_start(self, k=None): """select a criteria to edit score for.""" - self.view.view_criteria(self.shortlist.role, self.shortlist.role.criteria) + self.options = { - str(i): (self.edit_criteria_select, c.name) + str(self.available_keys[i]): (self.edit_criteria_select, c.name) for i, c in enumerate(self.shortlist.role.criteria) } + scored_criteria = [c.name for c in self.applicant(self.applicant_index).scores] + self.view.view_criteria(self.options, scored_criteria) # press q to quit at next step - self.options["q"] = (self.edit_criteria_select,"applicant detail") + self.options["q"] = (self.edit_criteria_select, "APPLICANT") def edit_criteria_select(self, k=None): """Select score to change to for previously selected criteria.""" @@ -155,27 +156,27 @@ def edit_criteria_select(self, k=None): self.view_applicant_details() self.options = self.options_applicant_detail else: - self.current_criterion = self.shortlist.role.criteria[int(k)] + offset = self.available_keys.index(k) + self.current_criterion = self.shortlist.role.criteria[offset] self.options = { str(i): (self.edit_score_confirm, s) for i, s in enumerate(RANK_AND_SCORE) } self.options["c"] = ( self.clear_score, - "clear score", + "CLEAR", ) # returns to criterion selection - self.options["q"] = (self.edit_score_start,"return to criterion selection") + self.options["q"] = (self.edit_score_start, "CRITERION") self.view.view_selection_options(self.current_criterion,self.options) def edit_score_confirm(self, k=None): """Updates the selected score of previously select criteria.""" - self.view.view_update(self.current_criterion.name, list(RANK_AND_SCORE)[int(k)]) update_applicant_score( self.applicant(self.applicant_index), self.current_criterion, int(k) ) - self.view_applicant_details() self.options = self.options_applicant_detail + self.view_applicant_details() def switch_applicant(self, k=None): """Move to next or previous applicant""" @@ -194,22 +195,22 @@ def switch_applicant(self, k=None): def create_applicant_note(self, k=None): """Adds a new note to applicant's note section.""" - note = input("Add note: ") + note = input("ADD NOTE> ") + print() update_applicant_notes(self.applicant(self.applicant_index), note) self.view_applicant_details() def clear_score(self, k=None): clear_score(self.applicant(self.applicant_index), self.current_criterion) - self.view_applicant_details() self.options = self.options_applicant_detail - self.view_applicant_details() def sort(self, k=None): """Activates sort""" - if k == "S": # activate sort - print("Sort applicants") + if k == "s": # activate sort + print("SORT> ", end="") self.options = self.options_sort + self.print_options(self.options) return elif k == "a": sort_alpha(self.selected_applicants) @@ -222,19 +223,23 @@ def sort(self, k=None): def filter_applicants(self,k=None): """Allows user to filter applicants by with condition statement""" - filter = input("Filter:") + filter = input("FILTER> ") try: selected_applicants = eval(f"[applicant for applicant in self.shortlist.applicants if {filter}]") except Exception as e: - print(f"ERROR: {e}") - selected_applicants = [] + print(f"ERROR: {str(e).upper()}") + print() + return if selected_applicants: self.selected_applicants = selected_applicants + + print() self.show_applicants_list_table() else: - print("No matches found") + print("NO MATCHES") + print() def clear_filter(self,k=None): self.selected_applicants = self.shortlist.applicants @@ -266,6 +271,13 @@ def view_applicant_details(self): total_applicant, ) + def print_options(self, options): + # show available keypress options + for keypress, func in options.items(): + print(f"{keypress}:{func[1]} ", end="") + print() + print() + def run(self): """Start the program and accepts keypress as argument for calling other functions.""" self.view.title() @@ -276,10 +288,7 @@ def run(self): # print(k) if k == "?": - # show available keypress options - for keypress, func in self.options.items(): - print(f"{keypress}: {func[1]}") - print() + self.print_options(self.options) else: # get and execute the action for this keypress action = self.options.get(k) diff --git a/shortlister/view.py b/shortlister/view.py index 2532e8b..5cf6c2a 100644 --- a/shortlister/view.py +++ b/shortlister/view.py @@ -27,15 +27,15 @@ def title(self): def home_message(self, role, num_applicants): """Prints overview of shortlist to console.""" - print(f"Shortlist for {role} loaded:") - print(f"{num_applicants} applicants found") - print("('?' to show list of avaliable shortcuts)") + print(f"PATH: {role}") + print(f"APPLICANTS: {num_applicants}") + print("? FOR HELP") print() def view_role(self, role: Role): """Prints overview of role to console.""" - print(f"Role title: {role.job_title}") - print(f"Role ID: {role.job_id}") + print(f"PATH: {role.job_title}") + print(f" ID: {role.job_id}") print() def view_applicant_details( @@ -47,24 +47,18 @@ def view_applicant_details( total_applicant, ): """Prints details of applicant to console.""" - print(f"** {applicant_number}/{total_applicant} {applicant.name} **") - print(f"CV Path: {applicant.cv}") - print(f"Email:{applicant.email}") - print(f"Phone:{applicant.phone}") - print(f"Postcode:{applicant.postcode}") - print(f"Country/Region:{applicant.country_region}") - print(f"Right to work: {applicant.right_to_work}- {applicant.visa_requirement}") + print(f"{applicant_number: >2} {applicant.name}") + if not applicant.right_to_work: + print(f" RIGHT TO WORK: NO ({applicant.visa_requirement})") + + if applicant.notes: + print(f" NOTES: {applicant.notes}") if applicant.scores: - print(f"Scores: ({total_score})") + print(" SCORES:") for order in criteria: if order in applicant.scores: - print(f"{order.name:^20}: {applicant.scores[order]:^20}") - else: - print("No scores") - - if applicant.notes: - print(f"Notes: {applicant.notes}") + print(f" {order.name}: {applicant.scores[order]}") print() @@ -81,7 +75,7 @@ def view_applicant_table( # creates heading criteria_headings = abbreviate([criterion.name for criterion in criteria]) - header = ["No.", "Name"] + criteria_headings + header = ["№", "NAME"] + criteria_headings # creates applicant and score data applicant_data = applicant_table(applicants, criteria) @@ -90,14 +84,16 @@ def view_applicant_table( # left align only for applicant names and center aligns all other strings(rest of applicant scores) pydoc.pager(tabulate(applicant_data, headers=header,stralign="center",colalign=("center","left"))) print() + print() - def view_criteria(self, role: Role, criteria: list[Criterion]): + def view_criteria(self, criteria_options, scored_criteria): """Prints list of all criterion for the role to console.""" - print(f"The criteria for {role.job_title} are:") + for key, (_, criterion) in criteria_options.items(): + if criterion in scored_criteria: + print(f"\033[9m{key}: {criterion}\033[29m ", end="") + else: + print(f"{key}: {criterion} ", end="") print() - - for index, criterion in enumerate(criteria): - print(f"{index}. {criterion.name}: {criterion.description}") print() def view_selection_options( @@ -106,13 +102,10 @@ def view_selection_options( options: Dict[str,tuple] ): """Prints list of avaliable scoring option for selected criterion to console.""" - print( - f"You selected {criterion.name}. Select the score you want to change to:\n" - ) # prints all of the available options for index, action in options.items(): - print(f"{index}: {action[1]}") - + print(f"{index}: {action[1]} ", end="") + print() print() def view_update(self, attribute, change): From 0917e76a0c731b4220a23fa3ae517edb5334bf03 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Fri, 6 Dec 2024 22:44:32 +0000 Subject: [PATCH 02/37] Add handler to drop into REPL --- shortlister/controller.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index 5d81924..a9f150a 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -44,6 +44,7 @@ def __init__(self, path): self.options_home = { "a": (self.show_applicants_list_table, "APPLICANTS"), "r": (self.show_role_info, "ROLE"), + "R": (self.repl, "REPL"), "q": (self.quit, "QUIT"), } self.options_applicant_list = { @@ -69,6 +70,12 @@ def __init__(self, path): "q": (self.show_applicants_list_table, "APPLICANTS"), } + def repl(self, k=None): + banner = "VARIABLES:\n shortlist\n controller" + import code + code.interact(banner=banner, local={"shortlist": self.shortlist, "controller": self}, exitmsg="EXITING") + print() + def quit(self, k=None): # if we've activated quit if k == "q": @@ -285,7 +292,6 @@ def run(self): while True: k = readkey() - # print(k) if k == "?": self.print_options(self.options) @@ -293,5 +299,4 @@ def run(self): # get and execute the action for this keypress action = self.options.get(k) if action is not None: - # print(action) action[0](k=k) From 539ebacaa59a019e3a72335224a3ec934ed901dd Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Fri, 6 Dec 2024 22:58:38 +0000 Subject: [PATCH 03/37] Add condition to check sort isn't activated to allow 'ss' to sort ascending --- shortlister/controller.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index a9f150a..484004b 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -89,7 +89,7 @@ def quit(self, k=None): elif k == "y": # quit confirmed - save and exit save_shortlist(self.path, self.shortlist) - print("GOODBYE.") + print("GOODBYE") sys.exit(0) else: # quit cancelled - back to home @@ -214,7 +214,7 @@ def clear_score(self, k=None): def sort(self, k=None): """Activates sort""" - if k == "s": # activate sort + if self.options != self.options_sort and k == "s": # activate sort print("SORT> ", end="") self.options = self.options_sort self.print_options(self.options) From f061c837ebc0a72d0998b247fb0a75747cf50013 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Fri, 6 Dec 2024 23:06:03 +0000 Subject: [PATCH 04/37] Add readline and some history to make filter easier to use --- shortlister/controller.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/shortlister/controller.py b/shortlister/controller.py index 484004b..adac398 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -1,5 +1,6 @@ import string from pathlib import Path +import readline import sys from typing import List @@ -41,6 +42,11 @@ def __init__(self, path): self.options = None self.available_keys = string.digits + string.ascii_letters + # add common filtering commands to readline history for easy access + readline.add_history("score(applicant, \"criterion-name\", \"score\")") + readline.add_history("cv(applicant, \"regex\")") + readline.add_history("name(applicant, \"name\"") + self.options_home = { "a": (self.show_applicants_list_table, "APPLICANTS"), "r": (self.show_role_info, "ROLE"), From 0dc5d5a8a09cc0d89d70a5f4c5552fd319d9a42f Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Fri, 6 Dec 2024 23:26:37 +0000 Subject: [PATCH 05/37] Tidy up comparison function, create and return result if we don't have one already --- shortlister/controller.py | 5 ++--- shortlister/tournament.py | 45 ++++++++++++++++++++++++++++----------- 2 files changed, 35 insertions(+), 15 deletions(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index adac398..f7dc6a5 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -259,10 +259,9 @@ def clear_filter(self,k=None): self.show_applicants_list_table() def rank_selected_applicants(self,k=None): - result = get_existing_result(Path(COMPARISON_RESULT_FILE_NAME)) - - comparison(self.selected_applicants,result) + result = comparison(self.selected_applicants, result) + ranked_list = rank(self.selected_applicants,result) print([applicant.name for applicant in ranked_list]) diff --git a/shortlister/tournament.py b/shortlister/tournament.py index ceb40b0..588e151 100644 --- a/shortlister/tournament.py +++ b/shortlister/tournament.py @@ -6,33 +6,54 @@ COMPARISON_RESULT_FILE_NAME = "ranked.pickle" -def comparison(list_to_rank, result: Dict): +def comparison(list_to_rank, result: Dict=None): """Starts pair comparison for a list of items. The result parameter could be dictionary with existing results or empty dictionary""" - # Queue is a list of pair that has not been compared yet + print("TOURNAMENT COMPARISON") + print() + + # start with an empty dict if we don't have existing results + if result is None: + result = {} + + # Queue is a list of pairs that have not been compared yet queue = get_pair(list_to_rank, result) - # Loop when there are still pairs to be compared in the queue + # Loop while there are still pairs to be compared in the queue while len(queue) > 0: # Remove the first pair in the queue and start the comparison - pair = tuple(queue.pop(0)) - print(f"1. {pair[0]}") - print(f"2. {pair[1]}") + pair = queue.pop(0) + first, second = tuple(pair) + + print(f"1. {first}") + print(f"2. {second}") + print() - # Limits key choice to "u","1","2" so there is no need for exception checking + print("1 OR 2?") + print() + + # Limits key choice to "u", "1", "2" so there is no need for exception checking while True: choice = readkey() - if choice in ["1", "2"] or choice == "u" and result: + if choice in ["1", "2", "q"] or choice == "u" and result: break - # if the choice is undo - if choice == "u": + + if choice == "q": + print("EXITING TOURNAMENT COMPARISON") + print() + return + # if undo last choice + elif choice == "u": # take the key and requeue the pair pair = result.popitem()[0] queue.insert(0, pair) # otherwise it can be evaluate by choose() function to get the winner, and the result is saved else: - winner = choose(choice, pair) - save_results(frozenset(pair), winner, result) + winner = choose(choice, (first, second)) + save_results(pair, winner, result) + + # all comparisons done + return result def get_pair(list_to_rank, result): From 16838c8624f567ea07e4b8d70b0c152369db7b36 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Fri, 6 Dec 2024 23:47:28 +0000 Subject: [PATCH 06/37] Many tournament references a bit clearer --- shortlister/controller.py | 15 +++++++-------- shortlister/tournament.py | 2 +- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index f7dc6a5..0d6e39d 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -2,7 +2,6 @@ from pathlib import Path import readline import sys -from typing import List from shortlister.view import View from shortlister.model import ( @@ -22,10 +21,9 @@ rtw, cv, notes, - ) -from shortlister.tournament import comparison,rank,get_existing_result,COMPARISON_RESULT_FILE_NAME +import shortlister.tournament as tournament from readchar import readkey from startfile import startfile @@ -87,7 +85,6 @@ def quit(self, k=None): if k == "q": # ask for confirmation print("ARE YOU SURE?") - print() self.options = { "n": (self.quit, "NO"), "y": (self.quit, "YES"), @@ -96,6 +93,7 @@ def quit(self, k=None): # quit confirmed - save and exit save_shortlist(self.path, self.shortlist) print("GOODBYE") + print() sys.exit(0) else: # quit cancelled - back to home @@ -259,11 +257,12 @@ def clear_filter(self,k=None): self.show_applicants_list_table() def rank_selected_applicants(self,k=None): - result = get_existing_result(Path(COMPARISON_RESULT_FILE_NAME)) - result = comparison(self.selected_applicants, result) + result = tournament.get_existing_result(Path(tournament.COMPARISON_RESULT_FILE_NAME)) + result = tournament.comparison(self.selected_applicants, result) - ranked_list = rank(self.selected_applicants,result) - print([applicant.name for applicant in ranked_list]) + ranked_list = tournament.rank(self.selected_applicants,result) + print("RESULT:", [applicant.name for applicant in ranked_list]) + print() # Utilities def applicant(self, index: int) -> Applicant: diff --git a/shortlister/tournament.py b/shortlister/tournament.py index 588e151..77565d6 100644 --- a/shortlister/tournament.py +++ b/shortlister/tournament.py @@ -70,7 +70,7 @@ def choose(choice, candidates: tuple): """Get user choice of which object out of the pair they prefer.""" if choice == "1": winner = candidates[0] - elif choice == "2": + else: winner = candidates[1] return winner From de9d59c4429ff9ca6fb26b38dd9c7f98d9b588c3 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Fri, 6 Dec 2024 23:48:58 +0000 Subject: [PATCH 07/37] ruff format --- shortlister/controller.py | 50 ++++++++++++++++++++++++--------------- shortlister/model.py | 46 +++++++++++++++++++++-------------- shortlister/tournament.py | 3 ++- shortlister/view.py | 19 ++++++++------- 4 files changed, 72 insertions(+), 46 deletions(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index 0d6e39d..2a6849d 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -41,9 +41,9 @@ def __init__(self, path): self.available_keys = string.digits + string.ascii_letters # add common filtering commands to readline history for easy access - readline.add_history("score(applicant, \"criterion-name\", \"score\")") - readline.add_history("cv(applicant, \"regex\")") - readline.add_history("name(applicant, \"name\"") + readline.add_history('score(applicant, "criterion-name", "score")') + readline.add_history('cv(applicant, "regex")') + readline.add_history('name(applicant, "name"') self.options_home = { "a": (self.show_applicants_list_table, "APPLICANTS"), @@ -54,10 +54,10 @@ def __init__(self, path): self.options_applicant_list = { "d": (self.show_applicant_details, "CHOOSE APPLICANT"), "s": (self.sort, "SORT"), - "f": (self.filter_applicants,"FILTER"), - "c": (self.clear_filter,"CLEAR FILTER"), + "f": (self.filter_applicants, "FILTER"), + "c": (self.clear_filter, "CLEAR FILTER"), "t": (self.show_applicants_list_table, "SWITCH TABLE"), - "r": (self.rank_selected_applicants,"RANK"), + "r": (self.rank_selected_applicants, "RANK"), "q": (self.show_home_message, "HOME"), } self.options_sort = { @@ -77,7 +77,12 @@ def __init__(self, path): def repl(self, k=None): banner = "VARIABLES:\n shortlist\n controller" import code - code.interact(banner=banner, local={"shortlist": self.shortlist, "controller": self}, exitmsg="EXITING") + + code.interact( + banner=banner, + local={"shortlist": self.shortlist, "controller": self}, + exitmsg="EXITING", + ) print() def quit(self, k=None): @@ -115,7 +120,9 @@ def show_applicants(self): if self.current_applicant_view == "List": self.view.view_applicants_list(self.selected_applicants) else: - self.view.view_applicant_table(self.selected_applicants,self.shortlist.role.criteria) + self.view.view_applicant_table( + self.selected_applicants, self.shortlist.role.criteria + ) def show_applicant_details(self, k=None): """Select an applicant via input and view details.""" @@ -137,7 +144,7 @@ def switch_applicants_list_table(self): # display applicant list if the above doesn't apply self.current_applicant_view = "List" - def show_applicants_list_table(self,k=None): + def show_applicants_list_table(self, k=None): """Switches view only if already displaying applicants list or table""" if k == "t": self.switch_applicants_list_table() @@ -170,7 +177,8 @@ def edit_criteria_select(self, k=None): offset = self.available_keys.index(k) self.current_criterion = self.shortlist.role.criteria[offset] self.options = { - str(i): (self.edit_score_confirm, s) for i, s in enumerate(RANK_AND_SCORE) + str(i): (self.edit_score_confirm, s) + for i, s in enumerate(RANK_AND_SCORE) } self.options["c"] = ( self.clear_score, @@ -178,7 +186,7 @@ def edit_criteria_select(self, k=None): ) # returns to criterion selection self.options["q"] = (self.edit_score_start, "CRITERION") - self.view.view_selection_options(self.current_criterion,self.options) + self.view.view_selection_options(self.current_criterion, self.options) def edit_score_confirm(self, k=None): """Updates the selected score of previously select criteria.""" @@ -232,17 +240,19 @@ def sort(self, k=None): self.show_applicants_list_table() - def filter_applicants(self,k=None): + def filter_applicants(self, k=None): """Allows user to filter applicants by with condition statement""" filter = input("FILTER> ") try: - selected_applicants = eval(f"[applicant for applicant in self.shortlist.applicants if {filter}]") + selected_applicants = eval( + f"[applicant for applicant in self.shortlist.applicants if {filter}]" + ) except Exception as e: print(f"ERROR: {str(e).upper()}") print() return - + if selected_applicants: self.selected_applicants = selected_applicants @@ -251,16 +261,18 @@ def filter_applicants(self,k=None): else: print("NO MATCHES") print() - - def clear_filter(self,k=None): + + def clear_filter(self, k=None): self.selected_applicants = self.shortlist.applicants self.show_applicants_list_table() - def rank_selected_applicants(self,k=None): - result = tournament.get_existing_result(Path(tournament.COMPARISON_RESULT_FILE_NAME)) + def rank_selected_applicants(self, k=None): + result = tournament.get_existing_result( + Path(tournament.COMPARISON_RESULT_FILE_NAME) + ) result = tournament.comparison(self.selected_applicants, result) - ranked_list = tournament.rank(self.selected_applicants,result) + ranked_list = tournament.rank(self.selected_applicants, result) print("RESULT:", [applicant.name for applicant in ranked_list]) print() diff --git a/shortlister/model.py b/shortlister/model.py index f3284fe..d1d6505 100644 --- a/shortlister/model.py +++ b/shortlister/model.py @@ -6,6 +6,7 @@ import pymupdf import re + @dataclass(frozen=True) class Criterion: """A property of Role - contained within the attribute criteria(list of Criterion objects).""" @@ -16,13 +17,14 @@ class Criterion: def __repr__(self) -> str: return self.name -@dataclass (eq=False) + +@dataclass(eq=False) class Applicant: """A property of Shortlist - contained within the attribute applicants(list of Applicant objects).""" - name: str =field(compare=True) - cv: str # path to cv - email: str + name: str = field(compare=True) + cv: str # path to cv + email: str phone: str postcode: str country_region: str @@ -34,6 +36,7 @@ class Applicant: def __repr__(self): return f"Applicant(name={self.name}, scores={self.scores}, notes={self.notes})" + def __hash__(self): return hash(self.cv) @@ -110,7 +113,7 @@ def load_applicants(path: Path): for file in files: applicant = load_applicants_from_pdf(file) applicants.append(applicant) - + sort_alpha(applicants) return applicants @@ -119,10 +122,10 @@ def load_applicants_from_pdf(file: Path): """Create a single Applicant instance from candidate pack within the parsed in PDF file""" doc = pymupdf.open(file) - # takes the first page of the pdf (the candidate pack) + # takes the first page of the pdf (the candidate pack) cover = doc[0] rest_of_pages = doc[1:] - # extract the remaining pdf pages + # extract the remaining pdf pages remaining_pdf = "\n".join([page.get_text(sort=True) for page in rest_of_pages]) # extract text in reading order text = cover.get_text(sort=True) @@ -288,7 +291,7 @@ def applicant_table(applicants: List[Applicant], criteria: List[Criterion]) -> L applicant_info.append(i) # applicant number # truncate name of applicant if name is more than 15 chars long if len(applicant.name) > 15: - applicant_info.append(applicant.name[0:15]+"...") + applicant_info.append(applicant.name[0:15] + "...") else: applicant_info.append(applicant.name) # append criterion score in the order criteria @@ -318,39 +321,46 @@ def abbreviate(list_of_strings: List[str]) -> list[str]: abbreviations.append(string) return abbreviations + # filter functions -def name(applicant:Applicant, name:str): +def name(applicant: Applicant, name: str): """Filter by matching name pattern applicant name. Example usage: name(applicant,"Emma")""" - return re.search(name,applicant.name) + return re.search(name, applicant.name) -def score(applicant:Applicant,name,score): + +def score(applicant: Applicant, name, score): """Filter by matching applicant score. Example usage: score(applicant,"PhD","Excellent")""" # checks that (criterion) name does not match any criterion in applicant scores if score == None: - return name.lower() not in [getattr(criterion,"name").lower() for criterion in applicant.scores] - + return name.lower() not in [ + getattr(criterion, "name").lower() for criterion in applicant.scores + ] + # checks if (criterion) name and score matches the saved applicant scores for criterion in applicant.scores: - if getattr(criterion,"name").lower() == name.lower(): + if getattr(criterion, "name").lower() == name.lower(): return applicant.scores[criterion].lower() == score.lower() # handles no match cases return False -def rtw(applicant:Applicant): + +def rtw(applicant: Applicant): """Filter out applicants without the right to work. Example usage: rtw(applicant)""" return applicant.right_to_work -def cv(applicant:Applicant,pattern:str): + +def cv(applicant: Applicant, pattern: str): """Filter by matching regex pattern in applicant's CV. Example usage: cv(applicant,"Engineer")""" return re.search(pattern, applicant.application_text) -def notes(applicant:Applicant,pattern:str): + +def notes(applicant: Applicant, pattern: str): """Filter by matching regex pattern in applicant note. Example usage: notes(applicant,"Engineer") """ - return re.search(pattern, applicant.notes) \ No newline at end of file + return re.search(pattern, applicant.notes) diff --git a/shortlister/tournament.py b/shortlister/tournament.py index 77565d6..f9a7b48 100644 --- a/shortlister/tournament.py +++ b/shortlister/tournament.py @@ -6,7 +6,8 @@ COMPARISON_RESULT_FILE_NAME = "ranked.pickle" -def comparison(list_to_rank, result: Dict=None): + +def comparison(list_to_rank, result: Dict = None): """Starts pair comparison for a list of items. The result parameter could be dictionary with existing results or empty dictionary""" print("TOURNAMENT COMPARISON") diff --git a/shortlister/view.py b/shortlister/view.py index 5cf6c2a..b481bbc 100644 --- a/shortlister/view.py +++ b/shortlister/view.py @@ -62,7 +62,7 @@ def view_applicant_details( print() - def view_applicants_list(self, applicants:List[Applicant]): + def view_applicants_list(self, applicants: List[Applicant]): """Prints list of all applicants to console.""" for index, applicant in enumerate(applicants): print(f"{index+1}. {applicant.name}") @@ -81,8 +81,15 @@ def view_applicant_table( applicant_data = applicant_table(applicants, criteria) # displays table - # left align only for applicant names and center aligns all other strings(rest of applicant scores) - pydoc.pager(tabulate(applicant_data, headers=header,stralign="center",colalign=("center","left"))) + # left align only for applicant names and center aligns all other strings(rest of applicant scores) + pydoc.pager( + tabulate( + applicant_data, + headers=header, + stralign="center", + colalign=("center", "left"), + ) + ) print() print() @@ -96,11 +103,7 @@ def view_criteria(self, criteria_options, scored_criteria): print() print() - def view_selection_options( - self, - criterion: Criterion, - options: Dict[str,tuple] - ): + def view_selection_options(self, criterion: Criterion, options: Dict[str, tuple]): """Prints list of avaliable scoring option for selected criterion to console.""" # prints all of the available options for index, action in options.items(): From f48889b8220e2c7a63c003d38aa280a83c074b66 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Sat, 7 Dec 2024 00:04:18 +0000 Subject: [PATCH 08/37] Minor improvements for clarity --- shortlister/controller.py | 85 +++++++++++++++++++++------------------ 1 file changed, 45 insertions(+), 40 deletions(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index 2a6849d..fa4da37 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -1,4 +1,5 @@ import string +from enum import Enum from pathlib import Path import readline import sys @@ -28,18 +29,25 @@ from startfile import startfile +class ApplicantsView(Enum): + LIST, TABLE = 1, 2 + class Controller: def __init__(self, path): self.path = path self.shortlist = load_shortlist(path) - self.applicant_index: int = 0 - self.current_criterion = None - self.current_applicant_view = "Table" - self.selected_applicants = self.shortlist.applicants + + # basic setup self.view = View() self.options = None self.available_keys = string.digits + string.ascii_letters + # application context + self.selected_applicants = self.shortlist.applicants + self.selected_applicant_index: int = 0 + self.selected_criterion = None + self.selected_applicant_view = ApplicantsView.TABLE + # add common filtering commands to readline history for easy access readline.add_history('score(applicant, "criterion-name", "score")') readline.add_history('cv(applicant, "regex")') @@ -66,7 +74,7 @@ def __init__(self, path): "d": (self.sort, "SCORE DESCENDING"), } self.options_applicant_detail = { - "e": (self.edit_score_start, "SCORE"), + "e": (self.score_applicant_step_1, "SCORE"), "N": (self.create_applicant_note, "NOTE"), "O": (self.open_applicant_pdf, "OPEN CV"), "n": (self.switch_applicant, "NEXT"), @@ -117,7 +125,7 @@ def show_role_info(self, k=None): def show_applicants(self): """Show applicants in either list or table view.""" - if self.current_applicant_view == "List": + if self.selected_applicant_view == ApplicantsView.LIST: self.view.view_applicants_list(self.selected_applicants) else: self.view.view_applicant_table( @@ -129,7 +137,7 @@ def show_applicant_details(self, k=None): try: i = int(input("№> ")) print() - self.applicant_index = i - 1 # Compensates for index + self.selected_applicant_index = i - 1 # Compensates for index self.view_applicant_details() self.options = self.options_applicant_detail except (ValueError, IndexError): @@ -137,12 +145,12 @@ def show_applicant_details(self, k=None): def switch_applicants_list_table(self): """Switch between list and table view of applicants""" - if self.current_applicant_view == "List": + if self.selected_applicant_view == ApplicantsView.LIST: # switch to table view if already displaying applicant list - self.current_applicant_view = "Table" + self.selected_applicant_view = ApplicantsView.TABLE else: # display applicant list if the above doesn't apply - self.current_applicant_view = "List" + self.selected_applicant_view = ApplicantsView.LIST def show_applicants_list_table(self, k=None): """Switches view only if already displaying applicants list or table""" @@ -153,46 +161,48 @@ def show_applicants_list_table(self, k=None): def open_applicant_pdf(self, k=None): """Open selected applicant's CV.""" - startfile(self.applicant(self.applicant_index).cv) - - def edit_score_start(self, k=None): - """select a criteria to edit score for.""" + startfile(self.applicant(self.selected_applicant_index).cv) + def score_applicant_step_1(self, k=None): + """Select a criteria to edit score for.""" self.options = { - str(self.available_keys[i]): (self.edit_criteria_select, c.name) + str(self.available_keys[i]): (self.score_applicant_step_2, c.name) for i, c in enumerate(self.shortlist.role.criteria) } - scored_criteria = [c.name for c in self.applicant(self.applicant_index).scores] + scored_criteria = [c.name for c in self.applicant(self.selected_applicant_index).scores] self.view.view_criteria(self.options, scored_criteria) # press q to quit at next step - self.options["q"] = (self.edit_criteria_select, "APPLICANT") + self.options["q"] = (self.score_applicant_step_2, "APPLICANT") - def edit_criteria_select(self, k=None): - """Select score to change to for previously selected criteria.""" + def score_applicant_step_2(self, k=None): + """Select score for the selected criteria.""" # return to applicant detail if key was "q", else continue to select criterion to score if k == "q": self.view_applicant_details() self.options = self.options_applicant_detail else: offset = self.available_keys.index(k) - self.current_criterion = self.shortlist.role.criteria[offset] + self.selected_criterion = self.shortlist.role.criteria[offset] self.options = { - str(i): (self.edit_score_confirm, s) + str(i): (self.score_applicant_step_3, s) for i, s in enumerate(RANK_AND_SCORE) } self.options["c"] = ( - self.clear_score, + self.score_applicant_step_3, "CLEAR", ) # returns to criterion selection - self.options["q"] = (self.edit_score_start, "CRITERION") - self.view.view_selection_options(self.current_criterion, self.options) + self.options["q"] = (self.score_applicant_step_1, "CRITERION") + self.view.view_selection_options(self.selected_criterion, self.options) - def edit_score_confirm(self, k=None): + def score_applicant_step_3(self, k=None): """Updates the selected score of previously select criteria.""" - update_applicant_score( - self.applicant(self.applicant_index), self.current_criterion, int(k) - ) + if k == "c": + clear_score(self.applicant(self.selected_applicant_index), self.selected_criterion) + else: + update_applicant_score( + self.applicant(self.selected_applicant_index), self.selected_criterion, int(k) + ) self.options = self.options_applicant_detail self.view_applicant_details() @@ -201,11 +211,11 @@ def switch_applicant(self, k=None): """Move to next or previous applicant""" # if next applicant, and not already at last - if k == "n" and (self.applicant_index < len(self.selected_applicants) - 1): - self.applicant_index += 1 + if k == "n" and (self.selected_applicant_index < len(self.selected_applicants) - 1): + self.selected_applicant_index += 1 # if previous and not already at first - elif k == "p" and (self.applicant_index > 0): - self.applicant_index -= 1 + elif k == "p" and (self.selected_applicant_index > 0): + self.selected_applicant_index -= 1 # otherwise do nothing else: return @@ -216,12 +226,7 @@ def create_applicant_note(self, k=None): """Adds a new note to applicant's note section.""" note = input("ADD NOTE> ") print() - update_applicant_notes(self.applicant(self.applicant_index), note) - self.view_applicant_details() - - def clear_score(self, k=None): - clear_score(self.applicant(self.applicant_index), self.current_criterion) - self.options = self.options_applicant_detail + update_applicant_notes(self.applicant(self.selected_applicant_index), note) self.view_applicant_details() def sort(self, k=None): @@ -282,9 +287,9 @@ def applicant(self, index: int) -> Applicant: return self.selected_applicants[index] def view_applicant_details(self): - applicant: Applicant = self.applicant(self.applicant_index) + applicant: Applicant = self.applicant(self.selected_applicant_index) total = total_score(applicant.scores) - applicant_number = self.applicant_index + 1 + applicant_number = self.selected_applicant_index + 1 total_applicant = len(self.selected_applicants) self.view.view_applicant_details( applicant, From 5240896583eee2158b86e9f214bf8e2fc9330ddb Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Sat, 7 Dec 2024 00:07:34 +0000 Subject: [PATCH 09/37] Fix errors from static analysis --- shortlister/controller.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index fa4da37..f95820d 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -17,16 +17,16 @@ sort_alpha, sort_ascending_score, sort_descending_score, - name, - score, - rtw, - cv, - notes, + name, # noqa + score, # noqa + rtw, # noqa + cv, # noqa + notes, # noqa ) import shortlister.tournament as tournament from readchar import readkey -from startfile import startfile +from startfile import startfile # noqa - universal-startfile class ApplicantsView(Enum): @@ -247,11 +247,11 @@ def sort(self, k=None): def filter_applicants(self, k=None): """Allows user to filter applicants by with condition statement""" - filter = input("FILTER> ") + condition = input("FILTER> ") try: selected_applicants = eval( - f"[applicant for applicant in self.shortlist.applicants if {filter}]" + f"[applicant for applicant in self.shortlist.applicants if {condition}]" ) except Exception as e: print(f"ERROR: {str(e).upper()}") @@ -299,7 +299,8 @@ def view_applicant_details(self): total_applicant, ) - def print_options(self, options): + @staticmethod + def print_options(options): # show available keypress options for keypress, func in options.items(): print(f"{keypress}:{func[1]} ", end="") From 10eb74b5c8e98ccf90a54b14ecc4b74164a6610e Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Sat, 7 Dec 2024 00:08:16 +0000 Subject: [PATCH 10/37] readkeys not used --- requirements.txt | Bin 248 -> 214 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/requirements.txt b/requirements.txt index c4ae5d76229de59ef2e418bed71c0aef18a57c4a..477c8dd7b45ff8fc2e9b57cd0daa2ca4277b8166 100644 GIT binary patch delta 9 Qcmeytc#UyF#>B2X02WRJQUCw| delta 37 pcmcb{_=9mmhIA@JB0~y8HbW{yB||ZTEf5+q=rI@ovC+iDQUJPi2$}!@ From 6a63ff3d153d98e62788bc41f97da5f7a01c58be Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Sat, 7 Dec 2024 00:19:12 +0000 Subject: [PATCH 11/37] Fix some type errors --- shortlister/model.py | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/shortlister/model.py b/shortlister/model.py index d1d6505..7c18e4c 100644 --- a/shortlister/model.py +++ b/shortlister/model.py @@ -10,7 +10,6 @@ @dataclass(frozen=True) class Criterion: """A property of Role - contained within the attribute criteria(list of Criterion objects).""" - name: str description: str @@ -21,9 +20,8 @@ def __repr__(self) -> str: @dataclass(eq=False) class Applicant: """A property of Shortlist - contained within the attribute applicants(list of Applicant objects).""" - name: str = field(compare=True) - cv: str # path to cv + cv: Path email: str phone: str postcode: str @@ -44,7 +42,6 @@ def __hash__(self): @dataclass class Role: """A property of Shortlist.""" - job_title: str job_id: str criteria: List[Criterion] @@ -53,7 +50,6 @@ class Role: @dataclass class Shortlist: """Major class object containing all relevant role, applicant, criteria information for shortlisting.""" - role: Role applicants: List[Applicant] @@ -71,7 +67,6 @@ class Shortlist: # Functions - def load_pickle(file_path): """Load shortlist from existing pickle file.""" with open(file_path, "rb") as f: @@ -90,7 +85,6 @@ def load_shortlist(path: Path): file = path / PICKLE_FILE_NAME if file.exists(): shortlist = load_pickle(file) - else: criteria = load_criteria(path / CRITERIA_FILE_NAME) role = load_role(path, criteria) @@ -144,7 +138,7 @@ def load_applicants_from_pdf(file: Path): phone=info["Preferred Phone Number"], postcode=info["Postcode"], country_region=info["Country & Region"], - right_to_work=info["Right To Work"], + right_to_work=bool(info["Right To Work"]), visa_requirement=info["Visa Requirements"], application_text=remaining_pdf, scores={}, From 952993ca48a06fe8f8c8bff8a35a7d9db2941639 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Sat, 7 Dec 2024 10:58:45 +0000 Subject: [PATCH 12/37] Print a message whether shortlist was restored or created --- shortlister/controller.py | 3 ++- shortlister/model.py | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index f95820d..c5cfeec 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -35,7 +35,8 @@ class ApplicantsView(Enum): class Controller: def __init__(self, path): self.path = path - self.shortlist = load_shortlist(path) + self.shortlist, msg = load_shortlist(path) + print(msg) # basic setup self.view = View() diff --git a/shortlister/model.py b/shortlister/model.py index 7c18e4c..0e999ea 100644 --- a/shortlister/model.py +++ b/shortlister/model.py @@ -80,18 +80,20 @@ def save_shortlist(path, shortlist): pickle.dump(shortlist, f) -def load_shortlist(path: Path): +def load_shortlist(path: Path) -> (Shortlist, str): """Import shortlist data from either: 1. Pickle file or 2. Role directory (when there is no existing pickle data).""" file = path / PICKLE_FILE_NAME if file.exists(): shortlist = load_pickle(file) + msg = f"SHORTLIST RESTORED FROM FILE" else: criteria = load_criteria(path / CRITERIA_FILE_NAME) role = load_role(path, criteria) applicants = load_applicants(path) shortlist = Shortlist(role, applicants) + msg = f"SHORTLIST CREATED FROM PACKS" - return shortlist + return shortlist, msg def load_role(path, criteria): From 95453c18d5a832869736eabbdeacc9d4880f9660 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Sat, 7 Dec 2024 12:29:52 +0000 Subject: [PATCH 13/37] Rationalise applicants table view and put collect context variables together --- shortlister/controller.py | 127 +++++++++++++++++++------------------- shortlister/model.py | 47 ++++++++++---- shortlister/view.py | 23 +------ 3 files changed, 101 insertions(+), 96 deletions(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index c5cfeec..17cf9dc 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -17,11 +17,11 @@ sort_alpha, sort_ascending_score, sort_descending_score, - name, # noqa - score, # noqa - rtw, # noqa - cv, # noqa - notes, # noqa + name, # noqa + score, # noqa + rtw, # noqa + cv, # noqa + notes, applicant_table, Criterion, # noqa ) import shortlister.tournament as tournament @@ -29,8 +29,14 @@ from startfile import startfile # noqa - universal-startfile -class ApplicantsView(Enum): - LIST, TABLE = 1, 2 +class ViewWidth(Enum): + NARROW, WIDE = 1, 2 + +class Context: + applicants: list[Applicant] + applicant_index: int + criterion: Criterion + table_view: ViewWidth class Controller: def __init__(self, path): @@ -44,10 +50,11 @@ def __init__(self, path): self.available_keys = string.digits + string.ascii_letters # application context - self.selected_applicants = self.shortlist.applicants - self.selected_applicant_index: int = 0 - self.selected_criterion = None - self.selected_applicant_view = ApplicantsView.TABLE + self.ctx = Context() + self.ctx.applicants = self.shortlist.applicants + self.ctx.applicant_index: int = 0 + self.ctx.criterion = None + self.ctx.table_view = ViewWidth.WIDE # add common filtering commands to readline history for easy access readline.add_history('score(applicant, "criterion-name", "score")') @@ -55,17 +62,17 @@ def __init__(self, path): readline.add_history('name(applicant, "name"') self.options_home = { - "a": (self.show_applicants_list_table, "APPLICANTS"), + "a": (self.show_applicants_table, "APPLICANTS"), "r": (self.show_role_info, "ROLE"), "R": (self.repl, "REPL"), "q": (self.quit, "QUIT"), } - self.options_applicant_list = { + self.options_applicant_table = { "d": (self.show_applicant_details, "CHOOSE APPLICANT"), "s": (self.sort, "SORT"), "f": (self.filter_applicants, "FILTER"), "c": (self.clear_filter, "CLEAR FILTER"), - "t": (self.show_applicants_list_table, "SWITCH TABLE"), + "t": (self.show_applicants_table, "SWITCH TABLE"), "r": (self.rank_selected_applicants, "RANK"), "q": (self.show_home_message, "HOME"), } @@ -80,7 +87,7 @@ def __init__(self, path): "O": (self.open_applicant_pdf, "OPEN CV"), "n": (self.switch_applicant, "NEXT"), "p": (self.switch_applicant, "PREVIOUS"), - "q": (self.show_applicants_list_table, "APPLICANTS"), + "q": (self.show_applicants_table, "APPLICANTS"), } def repl(self, k=None): @@ -124,45 +131,39 @@ def show_role_info(self, k=None): """Display role information.""" self.view.view_role(self.shortlist.role) - def show_applicants(self): - """Show applicants in either list or table view.""" - if self.selected_applicant_view == ApplicantsView.LIST: - self.view.view_applicants_list(self.selected_applicants) - else: - self.view.view_applicant_table( - self.selected_applicants, self.shortlist.role.criteria - ) - def show_applicant_details(self, k=None): """Select an applicant via input and view details.""" try: i = int(input("№> ")) print() - self.selected_applicant_index = i - 1 # Compensates for index + self.ctx.applicant_index = i - 1 # Compensates for index self.view_applicant_details() self.options = self.options_applicant_detail except (ValueError, IndexError): pass - def switch_applicants_list_table(self): - """Switch between list and table view of applicants""" - if self.selected_applicant_view == ApplicantsView.LIST: - # switch to table view if already displaying applicant list - self.selected_applicant_view = ApplicantsView.TABLE - else: - # display applicant list if the above doesn't apply - self.selected_applicant_view = ApplicantsView.LIST - - def show_applicants_list_table(self, k=None): + def show_applicants_table(self, k=None): """Switches view only if already displaying applicants list or table""" + + # toggle the table view width, if requested if k == "t": - self.switch_applicants_list_table() - self.show_applicants() - self.options = self.options_applicant_list + if self.ctx.table_view == ViewWidth.WIDE: + self.ctx.table_view = ViewWidth.NARROW + else: + self.ctx.table_view = ViewWidth.WIDE + + table = applicant_table( + self.ctx.applicants, + self.shortlist.role.criteria, + "wide" if self.ctx.table_view == ViewWidth.WIDE else "narrow" + ) + + self.view.view_applicant_table(table) + self.options = self.options_applicant_table def open_applicant_pdf(self, k=None): """Open selected applicant's CV.""" - startfile(self.applicant(self.selected_applicant_index).cv) + startfile(self.applicant(self.ctx.applicant_index).cv) def score_applicant_step_1(self, k=None): """Select a criteria to edit score for.""" @@ -170,7 +171,7 @@ def score_applicant_step_1(self, k=None): str(self.available_keys[i]): (self.score_applicant_step_2, c.name) for i, c in enumerate(self.shortlist.role.criteria) } - scored_criteria = [c.name for c in self.applicant(self.selected_applicant_index).scores] + scored_criteria = [c.name for c in self.applicant(self.ctx.applicant_index).scores] self.view.view_criteria(self.options, scored_criteria) # press q to quit at next step self.options["q"] = (self.score_applicant_step_2, "APPLICANT") @@ -183,7 +184,7 @@ def score_applicant_step_2(self, k=None): self.options = self.options_applicant_detail else: offset = self.available_keys.index(k) - self.selected_criterion = self.shortlist.role.criteria[offset] + self.ctx.criterion = self.shortlist.role.criteria[offset] self.options = { str(i): (self.score_applicant_step_3, s) for i, s in enumerate(RANK_AND_SCORE) @@ -194,15 +195,15 @@ def score_applicant_step_2(self, k=None): ) # returns to criterion selection self.options["q"] = (self.score_applicant_step_1, "CRITERION") - self.view.view_selection_options(self.selected_criterion, self.options) + self.view.view_selection_options(self.ctx.criterion, self.options) def score_applicant_step_3(self, k=None): """Updates the selected score of previously select criteria.""" if k == "c": - clear_score(self.applicant(self.selected_applicant_index), self.selected_criterion) + clear_score(self.applicant(self.ctx.applicant_index), self.ctx.criterion) else: update_applicant_score( - self.applicant(self.selected_applicant_index), self.selected_criterion, int(k) + self.applicant(self.ctx.applicant_index), self.ctx.criterion, int(k) ) self.options = self.options_applicant_detail @@ -212,11 +213,11 @@ def switch_applicant(self, k=None): """Move to next or previous applicant""" # if next applicant, and not already at last - if k == "n" and (self.selected_applicant_index < len(self.selected_applicants) - 1): - self.selected_applicant_index += 1 + if k == "n" and (self.ctx.applicant_index < len(self.ctx.applicants) - 1): + self.ctx.applicant_index += 1 # if previous and not already at first - elif k == "p" and (self.selected_applicant_index > 0): - self.selected_applicant_index -= 1 + elif k == "p" and (self.ctx.applicant_index > 0): + self.ctx.applicant_index -= 1 # otherwise do nothing else: return @@ -227,7 +228,7 @@ def create_applicant_note(self, k=None): """Adds a new note to applicant's note section.""" note = input("ADD NOTE> ") print() - update_applicant_notes(self.applicant(self.selected_applicant_index), note) + update_applicant_notes(self.applicant(self.ctx.applicant_index), note) self.view_applicant_details() def sort(self, k=None): @@ -238,13 +239,13 @@ def sort(self, k=None): self.print_options(self.options) return elif k == "a": - sort_alpha(self.selected_applicants) + sort_alpha(self.ctx.applicants) elif k == "s": - sort_ascending_score(self.selected_applicants) + sort_ascending_score(self.ctx.applicants) elif k == "d": - sort_descending_score(self.selected_applicants) + sort_descending_score(self.ctx.applicants) - self.show_applicants_list_table() + self.show_applicants_table() def filter_applicants(self, k=None): """Allows user to filter applicants by with condition statement""" @@ -260,38 +261,38 @@ def filter_applicants(self, k=None): return if selected_applicants: - self.selected_applicants = selected_applicants + self.ctx.applicants = selected_applicants print() - self.show_applicants_list_table() + self.show_applicants_table() else: print("NO MATCHES") print() def clear_filter(self, k=None): - self.selected_applicants = self.shortlist.applicants - self.show_applicants_list_table() + self.ctx.applicants = self.shortlist.applicants + self.show_applicants_table() def rank_selected_applicants(self, k=None): result = tournament.get_existing_result( Path(tournament.COMPARISON_RESULT_FILE_NAME) ) - result = tournament.comparison(self.selected_applicants, result) + result = tournament.comparison(self.ctx.applicants, result) - ranked_list = tournament.rank(self.selected_applicants, result) + ranked_list = tournament.rank(self.ctx.applicants, result) print("RESULT:", [applicant.name for applicant in ranked_list]) print() # Utilities def applicant(self, index: int) -> Applicant: """Returns applicant using its index in applicants.""" - return self.selected_applicants[index] + return self.ctx.applicants[index] def view_applicant_details(self): - applicant: Applicant = self.applicant(self.selected_applicant_index) + applicant: Applicant = self.applicant(self.ctx.applicant_index) total = total_score(applicant.scores) - applicant_number = self.selected_applicant_index + 1 - total_applicant = len(self.selected_applicants) + applicant_number = self.ctx.applicant_index + 1 + total_applicant = len(self.ctx.applicants) self.view.view_applicant_details( applicant, self.shortlist.role.criteria, diff --git a/shortlister/model.py b/shortlister/model.py index 0e999ea..7c90fdb 100644 --- a/shortlister/model.py +++ b/shortlister/model.py @@ -6,6 +6,8 @@ import pymupdf import re +from tabulate import tabulate + @dataclass(frozen=True) class Criterion: @@ -275,30 +277,51 @@ def extract_info_from_text(lines: List[str]): # creating tabular data -def applicant_table(applicants: List[Applicant], criteria: List[Criterion]) -> List: +def applicant_table(applicants: List[Applicant], criteria: List[Criterion], table_type="wide") -> (List, List): """Generates applicant and score data for summary table""" # tab is a list of lists: # each list in tab has the format of ["1","name1","score1","score2","score3","score*n"] tab = [] + + # creates heading + header = ["№", "NAME", "Σ"] + if table_type == "wide": + criteria_headings = abbreviate([criterion.name for criterion in criteria]) + header = header + criteria_headings + else: + header = header + ["SCORES"] + i = 0 # sets the applicant number for applicant in applicants: i += 1 - applicant_info = [] # list with correct information format for each row - applicant_info.append(i) # applicant number - # truncate name of applicant if name is more than 15 chars long + row = [i] if len(applicant.name) > 15: - applicant_info.append(applicant.name[0:15] + "...") + row.append(applicant.name[0:15] + "...") else: - applicant_info.append(applicant.name) - # append criterion score in the order criteria + row.append(applicant.name) + + row.append(total_score(applicant.scores)) + + scores = [] for criterion in criteria: if criterion in applicant.scores: - applicant_info.append(applicant.scores.get(criterion)[0]) + scores.append(applicant.scores.get(criterion)[0]) else: - # placeholder for unmarked criterion - applicant_info.append("·") - tab.append(applicant_info) - return tab + scores.append("·") + + if table_type == "wide": + row += scores + else: + row += ["".join(scores)] + tab.append(row) + + table = tabulate( + tab, + headers=header, + stralign="center", + colalign=("center", "left"), + ) + return table def abbreviate(list_of_strings: List[str]) -> list[str]: diff --git a/shortlister/view.py b/shortlister/view.py index b481bbc..4868562 100644 --- a/shortlister/view.py +++ b/shortlister/view.py @@ -68,28 +68,9 @@ def view_applicants_list(self, applicants: List[Applicant]): print(f"{index+1}. {applicant.name}") print() - def view_applicant_table( - self, applicants: List[Applicant], criteria: List[Criterion] - ): + def view_applicant_table(self, table: str): """Prints a table summary of applicants and their scores""" - - # creates heading - criteria_headings = abbreviate([criterion.name for criterion in criteria]) - header = ["№", "NAME"] + criteria_headings - - # creates applicant and score data - applicant_data = applicant_table(applicants, criteria) - - # displays table - # left align only for applicant names and center aligns all other strings(rest of applicant scores) - pydoc.pager( - tabulate( - applicant_data, - headers=header, - stralign="center", - colalign=("center", "left"), - ) - ) + pydoc.pager(table) print() print() From 90b203276e496be35cc9d0770445cb90527bdf84 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Sat, 7 Dec 2024 21:47:53 +0000 Subject: [PATCH 14/37] Tidy up context --- shortlister/controller.py | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index 17cf9dc..fca88af 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -1,4 +1,5 @@ import string +from dataclasses import dataclass from enum import Enum from pathlib import Path import readline @@ -32,13 +33,15 @@ class ViewWidth(Enum): NARROW, WIDE = 1, 2 +@dataclass class Context: - applicants: list[Applicant] - applicant_index: int - criterion: Criterion - table_view: ViewWidth + applicants: list[Applicant] # selected applicants + applicant_index: int # selected applicant + criterion: Criterion | None # selected criterion to score + table_view: ViewWidth # selected applicants' table view class Controller: + def __init__(self, path): self.path = path self.shortlist, msg = load_shortlist(path) @@ -50,11 +53,12 @@ def __init__(self, path): self.available_keys = string.digits + string.ascii_letters # application context - self.ctx = Context() - self.ctx.applicants = self.shortlist.applicants - self.ctx.applicant_index: int = 0 - self.ctx.criterion = None - self.ctx.table_view = ViewWidth.WIDE + self.ctx = Context( + self.shortlist.applicants, + 0, + None, + ViewWidth.WIDE + ) # add common filtering commands to readline history for easy access readline.add_history('score(applicant, "criterion-name", "score")') From 499fe97ebef43a62ccafad83572208b352170bcd Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Sun, 8 Dec 2024 17:06:30 +0000 Subject: [PATCH 15/37] Loop with enumerate so user can filter by number --- shortlister/controller.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index fca88af..55afda3 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -257,7 +257,7 @@ def filter_applicants(self, k=None): try: selected_applicants = eval( - f"[applicant for applicant in self.shortlist.applicants if {condition}]" + f"[applicant for i, applicant in enumerate(self.shortlist.applicants) if {condition}]" ) except Exception as e: print(f"ERROR: {str(e).upper()}") From 2897fb49407ea0ca6a3b38d23df45992d1b2838b Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Sun, 8 Dec 2024 17:55:23 +0000 Subject: [PATCH 16/37] Add filtering help --- shortlister/controller.py | 4 ++++ shortlister/view.py | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/shortlister/controller.py b/shortlister/controller.py index 55afda3..6592d61 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -255,6 +255,10 @@ def filter_applicants(self, k=None): """Allows user to filter applicants by with condition statement""" condition = input("FILTER> ") + if condition == "?": + self.view.view_filter_help() + return + try: selected_applicants = eval( f"[applicant for i, applicant in enumerate(self.shortlist.applicants) if {condition}]" diff --git a/shortlister/view.py b/shortlister/view.py index 4868562..91ad272 100644 --- a/shortlister/view.py +++ b/shortlister/view.py @@ -95,3 +95,22 @@ def view_selection_options(self, criterion: Criterion, options: Dict[str, tuple] def view_update(self, attribute, change): print(f"Updated: {attribute} to: {change}\n") print() + + def view_filter_help(self): + print(""" + VARIABLES: + applicant # APPLICANT OBJECT + i # APPLICANT INDEX + + FUNCTIONS: + name(applicant, "") + cv(applicant, "") + score(applicant, "", "") + rtw(applicant, "") [right to work] + + EXAMPLES: + cv(applicant, "(?i)nvidia") + score(applicant, "Professional experience", "Excellent") + score(applicant, "Cover letter", None) + i < 10 and not rtw(applicant) + """) From b4151a4680e1b9db619cf8cd3a1d6e87477ae455 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Sun, 8 Dec 2024 17:58:43 +0000 Subject: [PATCH 17/37] Add `total_score` example --- shortlister/view.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/shortlister/view.py b/shortlister/view.py index 91ad272..61641ff 100644 --- a/shortlister/view.py +++ b/shortlister/view.py @@ -107,9 +107,11 @@ def view_filter_help(self): cv(applicant, "") score(applicant, "", "") rtw(applicant, "") [right to work] + total_score(applicant.scores) EXAMPLES: cv(applicant, "(?i)nvidia") + total_score(applicant.scores) >= 50 score(applicant, "Professional experience", "Excellent") score(applicant, "Cover letter", None) i < 10 and not rtw(applicant) From 2545d453983ce0b9f71427e73d3085f89d24004b Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Sun, 8 Dec 2024 22:36:07 +0000 Subject: [PATCH 18/37] Add an interactive sorter and add it as a sort option --- shortlister/controller.py | 30 ++++++++++++++++++++++++++++++ shortlister/model.py | 27 +++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/shortlister/controller.py b/shortlister/controller.py index 6592d61..b35b609 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -4,6 +4,7 @@ from pathlib import Path import readline import sys +from typing import List from shortlister.view import View from shortlister.model import ( @@ -23,6 +24,7 @@ rtw, # noqa cv, # noqa notes, applicant_table, Criterion, # noqa + InteractiveSorter ) import shortlister.tournament as tournament @@ -84,6 +86,7 @@ def __init__(self, path): "a": (self.sort, "ALPHABETICAL"), "s": (self.sort, "SCORE ASCENDING"), "d": (self.sort, "SCORE DESCENDING"), + "c": (self.sort, "COMPARISON"), } self.options_applicant_detail = { "e": (self.score_applicant_step_1, "SCORE"), @@ -248,6 +251,33 @@ def sort(self, k=None): sort_ascending_score(self.ctx.applicants) elif k == "d": sort_descending_score(self.ctx.applicants) + elif k == "c": + sorter = InteractiveSorter() + + print("FOR EACH PAIR, SELECT 1 OR 2") + print() + + for first, second in sorter.sort(self.ctx.applicants): + print(f"(1) {first.name} or (2) {second.name}?") + + choice = None + while choice not in ["1", "2", "q"]: + choice = readkey() + + if choice == "1": + sorter.selected = first + elif choice == "2": + sorter.selected = second + elif choice == "q": + print("CANCELED") + print() + self.show_applicants_table() + return + + result: List = sorter.sorted + result.reverse() + self.ctx.applicants = result + print() self.show_applicants_table() diff --git a/shortlister/model.py b/shortlister/model.py index 7c90fdb..9927cf5 100644 --- a/shortlister/model.py +++ b/shortlister/model.py @@ -383,3 +383,30 @@ def notes(applicant: Applicant, pattern: str): Example usage: notes(applicant,"Engineer") """ return re.search(pattern, applicant.notes) + + +class InteractiveSorter: + def __init__(self): + self.selected = None + self.sorted = None + + def sort(self, items): + """Insertion sort, but yields the items to compare. The caller says which is greater.""" + + # We sort the items inplace, so don't change the input + self.sorted = items.copy() + + # Insertion sort from https://www.w3schools.com/dsa/dsa_algo_insertionsort.php + for i in range(1, len(self.sorted)): + insert_index = i + value = self.sorted[i] + for j in range(i - 1, -1, -1): + # self.selected is set by the caller for the yielded pair + self.selected = None + yield self.sorted[j], value + if self.selected == self.sorted[j]: + self.sorted[j + 1] = self.sorted[j] + insert_index = j + else: + break + self.sorted[insert_index] = value From a54a8228f7c3fcf5fa4d3314d10d2964e07201b7 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Mon, 9 Dec 2024 12:02:37 +0000 Subject: [PATCH 19/37] Add table legend and option to redisplay applicant (e.g. if scrolls off screen) --- shortlister/controller.py | 7 ++++++- shortlister/model.py | 2 +- shortlister/view.py | 13 ++++++++++++- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index b35b609..6ff9d00 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -78,8 +78,10 @@ def __init__(self, path): "s": (self.sort, "SORT"), "f": (self.filter_applicants, "FILTER"), "c": (self.clear_filter, "CLEAR FILTER"), - "t": (self.show_applicants_table, "SWITCH TABLE"), "r": (self.rank_selected_applicants, "RANK"), + "t": (self.show_applicants_table, "SWITCH TABLE"), + "l": (self.show_table_legend, "LEGEND"), + "a": (self.show_applicants_table, "APPLICANTS"), "q": (self.show_home_message, "HOME"), } self.options_sort = { @@ -168,6 +170,9 @@ def show_applicants_table(self, k=None): self.view.view_applicant_table(table) self.options = self.options_applicant_table + def show_table_legend(self, k=None): + self.view.view_table_legend(self.shortlist.role.criteria) + def open_applicant_pdf(self, k=None): """Open selected applicant's CV.""" startfile(self.applicant(self.ctx.applicant_index).cv) diff --git a/shortlister/model.py b/shortlister/model.py index 9927cf5..45e3c3f 100644 --- a/shortlister/model.py +++ b/shortlister/model.py @@ -153,7 +153,7 @@ def load_applicants_from_pdf(file: Path): if "" in applicant.name: name_parts = file.stem.split("_") applicant.name = " ".join(name_parts[0:2]) - print(f"Couldn't retrieve applicant data from: {file}") + print(f"ERROR READING: {file.name}") return applicant diff --git a/shortlister/view.py b/shortlister/view.py index 61641ff..ec4af12 100644 --- a/shortlister/view.py +++ b/shortlister/view.py @@ -106,7 +106,7 @@ def view_filter_help(self): name(applicant, "") cv(applicant, "") score(applicant, "", "") - rtw(applicant, "") [right to work] + rtw(applicant) [has right to work] total_score(applicant.scores) EXAMPLES: @@ -116,3 +116,14 @@ def view_filter_help(self): score(applicant, "Cover letter", None) i < 10 and not rtw(applicant) """) + + def view_table_legend(self, criteria): + criteria_names = [criteria.name for criteria in criteria] + abbreviations = abbreviate(criteria_names) + legend = dict(zip(abbreviations, criteria_names)) + legend = dict(sorted(legend.items())) + for line in legend.items(): + print(f"{line[0]}: {line[1]}") + print() + + From 99466333c0de7a575a55f0ae764972a38908373e Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Mon, 9 Dec 2024 12:40:20 +0000 Subject: [PATCH 20/37] Improve display of applicants comparison sorting --- shortlister/controller.py | 34 +++++++++++++++++++--------------- shortlister/view.py | 9 +-------- 2 files changed, 20 insertions(+), 23 deletions(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index 6ff9d00..e0fa91c 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -259,25 +259,35 @@ def sort(self, k=None): elif k == "c": sorter = InteractiveSorter() - print("FOR EACH PAIR, SELECT 1 OR 2") + print("FOR EACH PAIR, CHOOSE 1 OR 2") print() + criteria = self.shortlist.role.criteria + for first, second in sorter.sort(self.ctx.applicants): - print(f"(1) {first.name} or (2) {second.name}?") + self.view.view_applicant_details(first, criteria, 1) + self.view.view_applicant_details(second, criteria, 2) + print("CHOICE> ", end="", flush=True) choice = None - while choice not in ["1", "2", "q"]: + while choice not in ["1", "2"]: choice = readkey() + if choice == "O": + print("DISPLAY CVs") + choice = None # user still needs to choose applicant + elif choice == "q": + print("CANCELED") + print() + self.show_applicants_table() + return if choice == "1": sorter.selected = first elif choice == "2": sorter.selected = second - elif choice == "q": - print("CANCELED") - print() - self.show_applicants_table() - return + + print(sorter.selected.name) + print() result: List = sorter.sorted result.reverse() @@ -336,13 +346,7 @@ def view_applicant_details(self): total = total_score(applicant.scores) applicant_number = self.ctx.applicant_index + 1 total_applicant = len(self.ctx.applicants) - self.view.view_applicant_details( - applicant, - self.shortlist.role.criteria, - total, - applicant_number, - total_applicant, - ) + self.view.view_applicant_details(applicant, self.shortlist.role.criteria, applicant_number) @staticmethod def print_options(options): diff --git a/shortlister/view.py b/shortlister/view.py index ec4af12..c7b4ba5 100644 --- a/shortlister/view.py +++ b/shortlister/view.py @@ -38,14 +38,7 @@ def view_role(self, role: Role): print(f" ID: {role.job_id}") print() - def view_applicant_details( - self, - applicant: Applicant, - criteria: List[Criterion], - total_score, - applicant_number, - total_applicant, - ): + def view_applicant_details(self, applicant: Applicant, criteria: List[Criterion], applicant_number): """Prints details of applicant to console.""" print(f"{applicant_number: >2} {applicant.name}") if not applicant.right_to_work: From a05be3e57cbb52864c4f38895cd0c8f42467bb84 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Mon, 9 Dec 2024 23:16:21 +0000 Subject: [PATCH 21/37] Use pywebview to display applicant PDFs --- shortlister/controller.py | 31 ++++++++++++++++++++++--------- shortlister/main.py | 37 +++++++++++++++++++++++++++++-------- 2 files changed, 51 insertions(+), 17 deletions(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index e0fa91c..c5dbee6 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -3,13 +3,11 @@ from enum import Enum from pathlib import Path import readline -import sys from typing import List from shortlister.view import View from shortlister.model import ( Applicant, - total_score, load_shortlist, save_shortlist, update_applicant_score, @@ -44,7 +42,7 @@ class Context: class Controller: - def __init__(self, path): + def __init__(self, path, wv_window=None): self.path = path self.shortlist, msg = load_shortlist(path) print(msg) @@ -62,6 +60,9 @@ def __init__(self, path): ViewWidth.WIDE ) + # a window from pywebview to display PDFs + self.wv_window = wv_window + # add common filtering commands to readline history for easy access readline.add_history('score(applicant, "criterion-name", "score")') readline.add_history('cv(applicant, "regex")') @@ -124,7 +125,7 @@ def quit(self, k=None): save_shortlist(self.path, self.shortlist) print("GOODBYE") print() - sys.exit(0) + return True else: # quit cancelled - back to home print("QUIT CANCELLED") @@ -175,7 +176,12 @@ def show_table_legend(self, k=None): def open_applicant_pdf(self, k=None): """Open selected applicant's CV.""" - startfile(self.applicant(self.ctx.applicant_index).cv) + url = self.applicant(self.ctx.applicant_index).cv + if self.wv_window is not None: + url = f"file://{url}" + self.wv_window.load_url(url) + else: + startfile(self.applicant(self.ctx.applicant_index).cv) def score_applicant_step_1(self, k=None): """Select a criteria to edit score for.""" @@ -273,7 +279,8 @@ def sort(self, k=None): while choice not in ["1", "2"]: choice = readkey() if choice == "O": - print("DISPLAY CVs") + startfile(first.cv) + startfile(second.cv) choice = None # user still needs to choose applicant elif choice == "q": print("CANCELED") @@ -343,11 +350,15 @@ def applicant(self, index: int) -> Applicant: def view_applicant_details(self): applicant: Applicant = self.applicant(self.ctx.applicant_index) - total = total_score(applicant.scores) applicant_number = self.ctx.applicant_index + 1 - total_applicant = len(self.ctx.applicants) self.view.view_applicant_details(applicant, self.shortlist.role.criteria, applicant_number) + if self.wv_window is not None: + url = self.applicant(self.ctx.applicant_index).cv + url = f"file://{url}" + if self.wv_window.get_current_url() != url: + self.wv_window.load_url(url) + @staticmethod def print_options(options): # show available keypress options @@ -370,4 +381,6 @@ def run(self): # get and execute the action for this keypress action = self.options.get(k) if action is not None: - action[0](k=k) + quit_request = action[0](k=k) + if quit_request: + break diff --git a/shortlister/main.py b/shortlister/main.py index 4186ff2..ff9abb5 100644 --- a/shortlister/main.py +++ b/shortlister/main.py @@ -2,21 +2,42 @@ import argparse from pathlib import Path +try: + import webview +except ImportError: + webview = None + # this creates an instance of parser parser = argparse.ArgumentParser(description="loads shortlist data from role directory") # creates some argument you can use when running the file parser.add_argument("rolepath", type=Path) +parser.add_argument("-w", "--webview", action="store_true") # set the value of the argument parsed in so it can be accessed later args = parser.parse_args() -# accesses the rolepath from argument parsed -try: - control = Controller(args.rolepath) - control.run() -except FileNotFoundError: - print( - "Sorry, relevant files cannot be found in the directory, exiting the program..." - ) +def run_controller(wv_window=None): + if args.rolepath.is_dir(): + control = Controller(args.rolepath, wv_window) + control.run() + else: + print("ERROR: PATH DOES NOT EXIST") + + if wv_window is not None: + wv_window.destroy() + + +if args.webview and webview is not None: + + def on_closing(): + """Disable closing of the webview window""" + return False + + window = webview.create_window('Shortlister', html='

Shortlister

') + window.events.closing += on_closing + webview.start(run_controller, args=[window]) +else: + run_controller(None) + From 9f09673a43975ca331e96b7b534d676dc8d1883d Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Tue, 10 Dec 2024 00:03:10 +0000 Subject: [PATCH 22/37] Serving httpd in thread (for serving pdf.js) --- shortlister/main.py | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/shortlister/main.py b/shortlister/main.py index ff9abb5..cfaac05 100644 --- a/shortlister/main.py +++ b/shortlister/main.py @@ -1,6 +1,10 @@ -from shortlister.controller import Controller import argparse +import http +from http.server import HTTPServer from pathlib import Path +from threading import Thread + +from shortlister.controller import Controller try: import webview @@ -15,12 +19,29 @@ parser.add_argument("-w", "--webview", action="store_true") # set the value of the argument parsed in so it can be accessed later -args = parser.parse_args() +cli_args = parser.parse_args() + + +def start_httpd(): + def serve_forever(): + class Handler(http.server.SimpleHTTPRequestHandler): + def __init__(self, *args, **kwargs): + super().__init__(*args, directory="/Users/tamuri/", **kwargs) + + httpd = HTTPServer(("localhost", 8000), Handler) + httpd.serve_forever() + + http_thread = Thread(target=serve_forever) + http_thread.daemon = True + http_thread.start() def run_controller(wv_window=None): - if args.rolepath.is_dir(): - control = Controller(args.rolepath, wv_window) + if cli_args.rolepath.is_dir(): + if wv_window is not None: + start_httpd() + + control = Controller(cli_args.rolepath, wv_window) control.run() else: print("ERROR: PATH DOES NOT EXIST") @@ -29,15 +50,14 @@ def run_controller(wv_window=None): wv_window.destroy() -if args.webview and webview is not None: +if cli_args.webview and webview is not None: def on_closing(): """Disable closing of the webview window""" return False - window = webview.create_window('Shortlister', html='

Shortlister

') + window = webview.create_window("Shortlister", html="

Shortlister

") window.events.closing += on_closing webview.start(run_controller, args=[window]) else: run_controller(None) - From 00126de967e9d652d678397055195be5781bea92 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Tue, 10 Dec 2024 01:31:01 +0000 Subject: [PATCH 23/37] present pdfs in webview window using pdf.js - requires running flask with routes to applicant cvs and pdf.js --- shortlister/controller.py | 10 ++++++---- shortlister/main.py | 20 ++------------------ shortlister/web.py | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 22 deletions(-) create mode 100644 shortlister/web.py diff --git a/shortlister/controller.py b/shortlister/controller.py index c5dbee6..879764e 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -29,6 +29,8 @@ from readchar import readkey from startfile import startfile # noqa - universal-startfile +from shortlister.web import get_url_for_cv + class ViewWidth(Enum): NARROW, WIDE = 1, 2 @@ -176,9 +178,9 @@ def show_table_legend(self, k=None): def open_applicant_pdf(self, k=None): """Open selected applicant's CV.""" - url = self.applicant(self.ctx.applicant_index).cv + path = self.applicant(self.ctx.applicant_index).cv if self.wv_window is not None: - url = f"file://{url}" + url = get_url_for_cv(path.name) self.wv_window.load_url(url) else: startfile(self.applicant(self.ctx.applicant_index).cv) @@ -354,8 +356,8 @@ def view_applicant_details(self): self.view.view_applicant_details(applicant, self.shortlist.role.criteria, applicant_number) if self.wv_window is not None: - url = self.applicant(self.ctx.applicant_index).cv - url = f"file://{url}" + path = self.applicant(self.ctx.applicant_index).cv + url = get_url_for_cv(path.name) if self.wv_window.get_current_url() != url: self.wv_window.load_url(url) diff --git a/shortlister/main.py b/shortlister/main.py index cfaac05..efd92d1 100644 --- a/shortlister/main.py +++ b/shortlister/main.py @@ -1,10 +1,8 @@ import argparse -import http -from http.server import HTTPServer from pathlib import Path -from threading import Thread from shortlister.controller import Controller +from shortlister.web import start_httpd try: import webview @@ -22,24 +20,10 @@ cli_args = parser.parse_args() -def start_httpd(): - def serve_forever(): - class Handler(http.server.SimpleHTTPRequestHandler): - def __init__(self, *args, **kwargs): - super().__init__(*args, directory="/Users/tamuri/", **kwargs) - - httpd = HTTPServer(("localhost", 8000), Handler) - httpd.serve_forever() - - http_thread = Thread(target=serve_forever) - http_thread.daemon = True - http_thread.start() - - def run_controller(wv_window=None): if cli_args.rolepath.is_dir(): if wv_window is not None: - start_httpd() + start_httpd(cli_args.rolepath) control = Controller(cli_args.rolepath, wv_window) control.run() diff --git a/shortlister/web.py b/shortlister/web.py new file mode 100644 index 0000000..43d0cd6 --- /dev/null +++ b/shortlister/web.py @@ -0,0 +1,38 @@ +import urllib +from pathlib import Path +from threading import Thread + +from flask import Flask, send_file, send_from_directory + +ROUTE_PDFJS = "pdfjs" +ROUTE_CVS = "cvs" +ABS_PATH_PDFJS = "/Users/tamuri/Documents/2024/shiying-shortlister/pdfjs-4.6.82-dist/" +PDFJS_VIEWER_URL = f"http://127.0.0.1:8000/{ROUTE_PDFJS}/web/viewer.html" +CVS_URL = f"http://127.0.0.1:8000/{ROUTE_CVS}" + + +def get_url_for_cv(pdf_file): + url = f"{CVS_URL}/{pdf_file}" + url = urllib.parse.quote(url) + url = f"{PDFJS_VIEWER_URL}?file={url}" + return url + + +def start_httpd(role_path: Path): + def serve_forever(): + app = Flask(__name__) + + @app.route(f"/{ROUTE_PDFJS}/") + def pdfjs(path): + # Using request args for path will expose you to directory traversal attacks + return send_from_directory(ABS_PATH_PDFJS, path) + + @app.route(f"/{ROUTE_CVS}/") + def get_pdf(file_name): + return send_file(f"{role_path / file_name}", mimetype="application/pdf") + + app.run(host="0.0.0.0", port=8000, debug=False, use_reloader=False) + + http_thread = Thread(target=serve_forever) + http_thread.daemon = True + http_thread.start() From 35f53bfc0e436e07fe6d4ca2e592bd8090a9a5b7 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Tue, 10 Dec 2024 10:14:27 +0000 Subject: [PATCH 24/37] tidy-up webview usage --- shortlister/main.py | 12 +++--------- shortlister/view.py | 17 +++++++++-------- shortlister/web.py | 44 +++++++++++++++++++++++++++++++++----------- 3 files changed, 45 insertions(+), 28 deletions(-) diff --git a/shortlister/main.py b/shortlister/main.py index efd92d1..e3d9793 100644 --- a/shortlister/main.py +++ b/shortlister/main.py @@ -2,7 +2,7 @@ from pathlib import Path from shortlister.controller import Controller -from shortlister.web import start_httpd +from shortlister.web import start_httpd, setup_webview try: import webview @@ -20,7 +20,7 @@ cli_args = parser.parse_args() -def run_controller(wv_window=None): +def run_controller(wv_window: webview.Window=None): if cli_args.rolepath.is_dir(): if wv_window is not None: start_httpd(cli_args.rolepath) @@ -35,13 +35,7 @@ def run_controller(wv_window=None): if cli_args.webview and webview is not None: - - def on_closing(): - """Disable closing of the webview window""" - return False - - window = webview.create_window("Shortlister", html="

Shortlister

") - window.events.closing += on_closing + window = setup_webview() webview.start(run_controller, args=[window]) else: run_controller(None) diff --git a/shortlister/view.py b/shortlister/view.py index c7b4ba5..069889a 100644 --- a/shortlister/view.py +++ b/shortlister/view.py @@ -10,20 +10,21 @@ import pydoc from typing import Dict, List - -class View: - def __init__(self): - return - - def title(self): - print(r""" +BANNER = r""" _ _ _ _ _ ___| |__ ___ _ __| |_| (_)___| |_ ___ _ __ / __| '_ \ / _ \| '__| __| | / __| __/ _ \ '__| \__ \ | | | (_) | | | |_| | \__ \ || __/ | |___/_| |_|\___/|_| \__|_|_|___/\__\___|_| -""") +""" + +class View: + def __init__(self): + return + + def title(self): + print(BANNER) def home_message(self, role, num_applicants): """Prints overview of shortlist to console.""" diff --git a/shortlister/web.py b/shortlister/web.py index 43d0cd6..c36b0d6 100644 --- a/shortlister/web.py +++ b/shortlister/web.py @@ -2,34 +2,56 @@ from pathlib import Path from threading import Thread +import webview from flask import Flask, send_file, send_from_directory +from shortlister.view import BANNER + +ORIGIN = "http://localhost:8000" ROUTE_PDFJS = "pdfjs" ROUTE_CVS = "cvs" -ABS_PATH_PDFJS = "/Users/tamuri/Documents/2024/shiying-shortlister/pdfjs-4.6.82-dist/" -PDFJS_VIEWER_URL = f"http://127.0.0.1:8000/{ROUTE_PDFJS}/web/viewer.html" -CVS_URL = f"http://127.0.0.1:8000/{ROUTE_CVS}" +ABS_PATH_PDFJS = "../pdfjs-4.6.82-dist/" +PDFJS_VIEWER_URL = f"{ORIGIN}/{ROUTE_PDFJS}/web/viewer.html" +CVS_URL = f"{ORIGIN}/{ROUTE_CVS}" + +BANNER_HTML = f"
{BANNER}
" + +def setup_webview(): + """Create the pywebview window(s) for displaying applicant information. + We disable closing the window using window decorations/CMD+q etc. + Exiting the application in the terminal will close the window.""" + window = webview.create_window("shortlister", html=BANNER_HTML) + window.events.closing += lambda: False + return window -def get_url_for_cv(pdf_file): - url = f"{CVS_URL}/{pdf_file}" - url = urllib.parse.quote(url) - url = f"{PDFJS_VIEWER_URL}?file={url}" - return url +def get_url_for_cv(pdf_filename): + """Return the URL for the pdf.js viewer and supplied PDF file""" + pdf_url = f"{CVS_URL}/{pdf_filename}" + pdf_url = urllib.parse.quote(pdf_url) + viewer_url = f"{PDFJS_VIEWER_URL}?file={pdf_url}" + return viewer_url -def start_httpd(role_path: Path): + +def start_httpd(path_to_pdfs: Path): + """Start a Flask server to serve pdf.js and PDF files for pywebview. + We use Flask instead of Python's built-in http.server because we want + route pdf.js and applicant CVs to different paths.""" def serve_forever(): app = Flask(__name__) + @app.route("/") + def index(): + return BANNER_HTML + @app.route(f"/{ROUTE_PDFJS}/") def pdfjs(path): - # Using request args for path will expose you to directory traversal attacks return send_from_directory(ABS_PATH_PDFJS, path) @app.route(f"/{ROUTE_CVS}/") def get_pdf(file_name): - return send_file(f"{role_path / file_name}", mimetype="application/pdf") + return send_file(f"{path_to_pdfs / file_name}", mimetype="application/pdf") app.run(host="0.0.0.0", port=8000, debug=False, use_reloader=False) From 97e22fb94b04e875e0edf4bfb88bc744cdc0aa7d Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Tue, 10 Dec 2024 10:40:02 +0000 Subject: [PATCH 25/37] change to always open in external viewer --- shortlister/controller.py | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index 879764e..033fe68 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -177,13 +177,8 @@ def show_table_legend(self, k=None): self.view.view_table_legend(self.shortlist.role.criteria) def open_applicant_pdf(self, k=None): - """Open selected applicant's CV.""" - path = self.applicant(self.ctx.applicant_index).cv - if self.wv_window is not None: - url = get_url_for_cv(path.name) - self.wv_window.load_url(url) - else: - startfile(self.applicant(self.ctx.applicant_index).cv) + """Open selected applicant's CV in default viewer.""" + startfile(self.applicant(self.ctx.applicant_index).cv) def score_applicant_step_1(self, k=None): """Select a criteria to edit score for.""" From f56af3b545523b1857d80d4607b068450bff8dde Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Tue, 10 Dec 2024 22:48:34 +0000 Subject: [PATCH 26/37] don't override built-in keyword `object` --- shortlister/tournament.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/shortlister/tournament.py b/shortlister/tournament.py index f9a7b48..6b96cae 100644 --- a/shortlister/tournament.py +++ b/shortlister/tournament.py @@ -88,11 +88,11 @@ def rank(list_to_rank: List, result: Dict): wins = {} outcome = list(result.values()) - for object in list_to_rank: + for obj in list_to_rank: # Count how many wins an object got - score = outcome.count(object) + score = outcome.count(obj) # create an entry in wins dictionary of the object and the score it earned - wins[object] = score + wins[obj] = score # sort the list by highest scored to lowest ranked = sorted(list_to_rank, key=lambda item: wins[item], reverse=True) From 8a2ad5b52df3371bd413218220d83a0656af304f Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Tue, 10 Dec 2024 22:51:33 +0000 Subject: [PATCH 27/37] Remove unused argument --- shortlister/controller.py | 2 +- shortlister/view.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index 033fe68..00d2137 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -210,7 +210,7 @@ def score_applicant_step_2(self, k=None): ) # returns to criterion selection self.options["q"] = (self.score_applicant_step_1, "CRITERION") - self.view.view_selection_options(self.ctx.criterion, self.options) + self.view.view_selection_options(self.options) def score_applicant_step_3(self, k=None): """Updates the selected score of previously select criteria.""" diff --git a/shortlister/view.py b/shortlister/view.py index 069889a..e9b9a85 100644 --- a/shortlister/view.py +++ b/shortlister/view.py @@ -78,7 +78,7 @@ def view_criteria(self, criteria_options, scored_criteria): print() print() - def view_selection_options(self, criterion: Criterion, options: Dict[str, tuple]): + def view_selection_options(self, options: Dict[str, tuple]): """Prints list of avaliable scoring option for selected criterion to console.""" # prints all of the available options for index, action in options.items(): From cda256e4e6714624142b1c7ede1ccc3fb9e038c4 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Tue, 10 Dec 2024 22:52:03 +0000 Subject: [PATCH 28/37] Fix imports --- shortlister/controller.py | 33 ++++++++++----------------------- shortlister/view.py | 11 ++--------- 2 files changed, 12 insertions(+), 32 deletions(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index 00d2137..b3253db 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -1,34 +1,21 @@ +import readline import string from dataclasses import dataclass from enum import Enum from pathlib import Path -import readline from typing import List -from shortlister.view import View -from shortlister.model import ( - Applicant, - load_shortlist, - save_shortlist, - update_applicant_score, - update_applicant_notes, - clear_score, - RANK_AND_SCORE, - sort_alpha, - sort_ascending_score, - sort_descending_score, - name, # noqa - score, # noqa - rtw, # noqa - cv, # noqa - notes, applicant_table, Criterion, # noqa - InteractiveSorter -) - -import shortlister.tournament as tournament from readchar import readkey -from startfile import startfile # noqa - universal-startfile +from startfile import startfile # noqa - package name: universal-startfile +import shortlister.tournament as tournament +from shortlister.model import (RANK_AND_SCORE, Applicant, Criterion, # noqa + InteractiveSorter, applicant_table, clear_score, + cv, load_shortlist, name, notes, rtw, + save_shortlist, score, sort_alpha, + sort_ascending_score, sort_descending_score, + update_applicant_notes, update_applicant_score) +from shortlister.view import View from shortlister.web import get_url_for_cv diff --git a/shortlister/view.py b/shortlister/view.py index e9b9a85..8e51063 100644 --- a/shortlister/view.py +++ b/shortlister/view.py @@ -1,15 +1,8 @@ -from shortlister.model import ( - Applicant, - Role, - Criterion, - Shortlist, - applicant_table, - abbreviate, -) -from tabulate import tabulate import pydoc from typing import Dict, List +from shortlister.model import Applicant, Criterion, Role, abbreviate + BANNER = r""" _ _ _ _ _ ___| |__ ___ _ __| |_| (_)___| |_ ___ _ __ From 41de72d310f050ef3b1140fd1635928d80dfa2a1 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Tue, 10 Dec 2024 22:57:39 +0000 Subject: [PATCH 29/37] Small linter fixes --- shortlister/model.py | 40 +++++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/shortlister/model.py b/shortlister/model.py index 45e3c3f..3cef2c9 100644 --- a/shortlister/model.py +++ b/shortlister/model.py @@ -87,13 +87,13 @@ def load_shortlist(path: Path) -> (Shortlist, str): file = path / PICKLE_FILE_NAME if file.exists(): shortlist = load_pickle(file) - msg = f"SHORTLIST RESTORED FROM FILE" + msg = "SHORTLIST RESTORED FROM FILE" else: criteria = load_criteria(path / CRITERIA_FILE_NAME) role = load_role(path, criteria) applicants = load_applicants(path) shortlist = Shortlist(role, applicants) - msg = f"SHORTLIST CREATED FROM PACKS" + msg = "SHORTLIST CREATED FROM PACKS" return shortlist, msg @@ -161,7 +161,7 @@ def load_applicants_from_pdf(file: Path): def load_criteria(csv_file): """Generate criteria(list of criterion instances) from csv file.""" criteria = [] - with open(csv_file) as file: + with open(csv_file, "r", encoding="UTF-8") as file: reader = csv.reader(file) next(reader) @@ -223,8 +223,8 @@ def clear_score(applicant: Applicant, criterion: Criterion): def extract_info_from_text(lines: List[str]): """gets the section containing applicant information from extracted text""" - # fields names to get related applicant information - fields = dict.fromkeys( + # fields labels to get related applicant information + labels: Dict[str, str|bool] = dict.fromkeys( [ "First Name", "Last Name", @@ -243,18 +243,20 @@ def extract_info_from_text(lines: List[str]): right_to_work = lines[-5:-1] # filter out the field name and retain only the info to applicant - for field in fields: + for label in labels: for line in applicant_info: - if line.startswith(field): + if line.startswith(label): data = line.removeprefix( - field + label ) # removes the field and leaves only the information - fields[field] = data.strip() # removes whitespaces + labels[label] = data.strip() # removes whitespaces break else: continue # finds where the question is and checks the next index which contains the answer to the question + applicant_right_to_work = None + visa_req_text = None if "Do you have the unrestricted right to work in the UK?" in right_to_work: i = right_to_work.index("Do you have the unrestricted right to work in the UK?") if right_to_work[i + 1] == "No": @@ -268,10 +270,10 @@ def extract_info_from_text(lines: List[str]): applicant_right_to_work = True visa_req_text = None - fields["Right To Work"] = applicant_right_to_work - fields["Visa Requirements"] = visa_req_text + labels["Right To Work"] = applicant_right_to_work + labels["Visa Requirements"] = visa_req_text - return fields + return labels # creating tabular data @@ -342,26 +344,26 @@ def abbreviate(list_of_strings: List[str]) -> list[str]: # filter functions -def name(applicant: Applicant, name: str): +def name(applicant: Applicant, _name: str): """Filter by matching name pattern applicant name. Example usage: name(applicant,"Emma")""" - return re.search(name, applicant.name) + return re.search(_name, applicant.name) -def score(applicant: Applicant, name, score): +def score(applicant: Applicant, _name, _score): """Filter by matching applicant score. Example usage: score(applicant,"PhD","Excellent")""" # checks that (criterion) name does not match any criterion in applicant scores - if score == None: - return name.lower() not in [ + if _score is None: + return _name.lower() not in [ getattr(criterion, "name").lower() for criterion in applicant.scores ] # checks if (criterion) name and score matches the saved applicant scores for criterion in applicant.scores: - if getattr(criterion, "name").lower() == name.lower(): - return applicant.scores[criterion].lower() == score.lower() + if getattr(criterion, "name").lower() == _name.lower(): + return applicant.scores[criterion].lower() == _score.lower() # handles no match cases return False From ca92732b7c6dece31a42643f2af3d05bc6a5e39e Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Tue, 10 Dec 2024 23:02:21 +0000 Subject: [PATCH 30/37] Catch more specific errors for eval --- shortlister/controller.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index b3253db..765122b 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -299,7 +299,7 @@ def filter_applicants(self, k=None): selected_applicants = eval( f"[applicant for i, applicant in enumerate(self.shortlist.applicants) if {condition}]" ) - except Exception as e: + except (NameError, SyntaxError) as e: print(f"ERROR: {str(e).upper()}") print() return From d9974dafe1ac9fc9cfd92a10180cffe4cf4fe53c Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Tue, 10 Dec 2024 23:02:31 +0000 Subject: [PATCH 31/37] Add docstring --- shortlister/web.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/shortlister/web.py b/shortlister/web.py index c36b0d6..7dafc25 100644 --- a/shortlister/web.py +++ b/shortlister/web.py @@ -1,3 +1,8 @@ +""" +Functions to work with pywebview and pdf.js to present applicant CVs. This +is an optional feature, and can be activated with the "-w" option when starting +shortlister. +""" import urllib from pathlib import Path from threading import Thread From 263fe3595c78c17853ccf7382d7ed7f49865f3cf Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Tue, 10 Dec 2024 23:20:13 +0000 Subject: [PATCH 32/37] Slightly dim background of start page --- shortlister/web.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/shortlister/web.py b/shortlister/web.py index 7dafc25..003320e 100644 --- a/shortlister/web.py +++ b/shortlister/web.py @@ -19,7 +19,12 @@ PDFJS_VIEWER_URL = f"{ORIGIN}/{ROUTE_PDFJS}/web/viewer.html" CVS_URL = f"{ORIGIN}/{ROUTE_CVS}" -BANNER_HTML = f"
{BANNER}
" +BANNER_HTML = f""" + + +
{BANNER}
+ +""" def setup_webview(): From 2a138b3bf4c6c465029abfb0c5b026d38a95c245 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Tue, 10 Dec 2024 23:21:47 +0000 Subject: [PATCH 33/37] Only listen on loopback --- shortlister/web.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shortlister/web.py b/shortlister/web.py index 003320e..6d7687c 100644 --- a/shortlister/web.py +++ b/shortlister/web.py @@ -63,7 +63,7 @@ def pdfjs(path): def get_pdf(file_name): return send_file(f"{path_to_pdfs / file_name}", mimetype="application/pdf") - app.run(host="0.0.0.0", port=8000, debug=False, use_reloader=False) + app.run(host="127.0.0.1", port=8000, debug=False, use_reloader=False) http_thread = Thread(target=serve_forever) http_thread.daemon = True From bf6c179fe2a247e9a3fc1d269d4c865344ba5bba Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Tue, 10 Dec 2024 23:23:03 +0000 Subject: [PATCH 34/37] use keyword arguments clarity --- shortlister/controller.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index 765122b..3aa341a 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -43,10 +43,10 @@ def __init__(self, path, wv_window=None): # application context self.ctx = Context( - self.shortlist.applicants, - 0, - None, - ViewWidth.WIDE + applicants=self.shortlist.applicants, + applicant_index=0, + criterion=None, + table_view=ViewWidth.WIDE ) # a window from pywebview to display PDFs From b5d0df07102d03537d6e35ceb63a99facd5ebc25 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Wed, 11 Dec 2024 11:55:58 +0000 Subject: [PATCH 35/37] webview might not be available, so we can't load things from shortlister.web either --- shortlister/controller.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/shortlister/controller.py b/shortlister/controller.py index 3aa341a..0860542 100644 --- a/shortlister/controller.py +++ b/shortlister/controller.py @@ -16,7 +16,14 @@ sort_ascending_score, sort_descending_score, update_applicant_notes, update_applicant_score) from shortlister.view import View -from shortlister.web import get_url_for_cv + +try: + import webview + + from shortlister.web import get_url_for_cv +except ImportError: + webview = None + get_url_for_cv = None class ViewWidth(Enum): From f83e49067c9abf23d9ec595a94ac277290942f79 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Wed, 11 Dec 2024 23:11:40 +0000 Subject: [PATCH 36/37] use a better word (than the word I made up - unretrievable) --- shortlister/model.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/shortlister/model.py b/shortlister/model.py index 3cef2c9..03d9911 100644 --- a/shortlister/model.py +++ b/shortlister/model.py @@ -150,7 +150,7 @@ def load_applicants_from_pdf(file: Path): ) # if either of the name field can't be extracted, get applicant's name from their cv filename - if "" in applicant.name: + if "" in applicant.name: name_parts = file.stem.split("_") applicant.name = " ".join(name_parts[0:2]) print(f"ERROR READING: {file.name}") @@ -235,7 +235,7 @@ def extract_info_from_text(lines: List[str]): "Right To Work", "Visa Requirements", ], - "", + "", ) # removes header/footer and other irrelevant info From 4b1c15f581dc91d6d07dbe9e87664df9673e73a2 Mon Sep 17 00:00:00 2001 From: Asif Tamuri Date: Fri, 13 Dec 2024 02:40:09 +0000 Subject: [PATCH 37/37] Add pdfjs-4.9.155-dist --- pdfjs/LICENSE | 177 + pdfjs/build/pdf.mjs | 21337 ++++++ pdfjs/build/pdf.mjs.map | 1 + pdfjs/build/pdf.sandbox.mjs | 242 + pdfjs/build/pdf.sandbox.mjs.map | 1 + pdfjs/build/pdf.worker.mjs | 56901 ++++++++++++++++ pdfjs/build/pdf.worker.mjs.map | 1 + pdfjs/web/cmaps/78-EUC-H.bcmap | Bin 0 -> 2404 bytes pdfjs/web/cmaps/78-EUC-V.bcmap | Bin 0 -> 173 bytes pdfjs/web/cmaps/78-H.bcmap | Bin 0 -> 2379 bytes pdfjs/web/cmaps/78-RKSJ-H.bcmap | Bin 0 -> 2398 bytes pdfjs/web/cmaps/78-RKSJ-V.bcmap | Bin 0 -> 173 bytes pdfjs/web/cmaps/78-V.bcmap | Bin 0 -> 169 bytes pdfjs/web/cmaps/78ms-RKSJ-H.bcmap | Bin 0 -> 2651 bytes pdfjs/web/cmaps/78ms-RKSJ-V.bcmap | Bin 0 -> 290 bytes pdfjs/web/cmaps/83pv-RKSJ-H.bcmap | Bin 0 -> 905 bytes pdfjs/web/cmaps/90ms-RKSJ-H.bcmap | Bin 0 -> 721 bytes pdfjs/web/cmaps/90ms-RKSJ-V.bcmap | Bin 0 -> 290 bytes pdfjs/web/cmaps/90msp-RKSJ-H.bcmap | Bin 0 -> 715 bytes pdfjs/web/cmaps/90msp-RKSJ-V.bcmap | Bin 0 -> 291 bytes pdfjs/web/cmaps/90pv-RKSJ-H.bcmap | Bin 0 -> 982 bytes pdfjs/web/cmaps/90pv-RKSJ-V.bcmap | Bin 0 -> 260 bytes pdfjs/web/cmaps/Add-H.bcmap | Bin 0 -> 2419 bytes pdfjs/web/cmaps/Add-RKSJ-H.bcmap | Bin 0 -> 2413 bytes pdfjs/web/cmaps/Add-RKSJ-V.bcmap | Bin 0 -> 287 bytes pdfjs/web/cmaps/Add-V.bcmap | Bin 0 -> 282 bytes pdfjs/web/cmaps/Adobe-CNS1-0.bcmap | Bin 0 -> 317 bytes pdfjs/web/cmaps/Adobe-CNS1-1.bcmap | Bin 0 -> 371 bytes pdfjs/web/cmaps/Adobe-CNS1-2.bcmap | Bin 0 -> 376 bytes pdfjs/web/cmaps/Adobe-CNS1-3.bcmap | Bin 0 -> 401 bytes pdfjs/web/cmaps/Adobe-CNS1-4.bcmap | Bin 0 -> 405 bytes pdfjs/web/cmaps/Adobe-CNS1-5.bcmap | Bin 0 -> 406 bytes pdfjs/web/cmaps/Adobe-CNS1-6.bcmap | Bin 0 -> 406 bytes pdfjs/web/cmaps/Adobe-CNS1-UCS2.bcmap | Bin 0 -> 41193 bytes pdfjs/web/cmaps/Adobe-GB1-0.bcmap | Bin 0 -> 217 bytes pdfjs/web/cmaps/Adobe-GB1-1.bcmap | Bin 0 -> 250 bytes pdfjs/web/cmaps/Adobe-GB1-2.bcmap | Bin 0 -> 465 bytes pdfjs/web/cmaps/Adobe-GB1-3.bcmap | Bin 0 -> 470 bytes pdfjs/web/cmaps/Adobe-GB1-4.bcmap | Bin 0 -> 601 bytes pdfjs/web/cmaps/Adobe-GB1-5.bcmap | Bin 0 -> 625 bytes pdfjs/web/cmaps/Adobe-GB1-UCS2.bcmap | Bin 0 -> 33974 bytes pdfjs/web/cmaps/Adobe-Japan1-0.bcmap | Bin 0 -> 225 bytes pdfjs/web/cmaps/Adobe-Japan1-1.bcmap | Bin 0 -> 226 bytes pdfjs/web/cmaps/Adobe-Japan1-2.bcmap | Bin 0 -> 233 bytes pdfjs/web/cmaps/Adobe-Japan1-3.bcmap | Bin 0 -> 242 bytes pdfjs/web/cmaps/Adobe-Japan1-4.bcmap | Bin 0 -> 337 bytes pdfjs/web/cmaps/Adobe-Japan1-5.bcmap | Bin 0 -> 430 bytes pdfjs/web/cmaps/Adobe-Japan1-6.bcmap | Bin 0 -> 485 bytes pdfjs/web/cmaps/Adobe-Japan1-UCS2.bcmap | Bin 0 -> 40951 bytes pdfjs/web/cmaps/Adobe-Korea1-0.bcmap | Bin 0 -> 241 bytes pdfjs/web/cmaps/Adobe-Korea1-1.bcmap | Bin 0 -> 386 bytes pdfjs/web/cmaps/Adobe-Korea1-2.bcmap | Bin 0 -> 391 bytes pdfjs/web/cmaps/Adobe-Korea1-UCS2.bcmap | Bin 0 -> 23293 bytes pdfjs/web/cmaps/B5-H.bcmap | Bin 0 -> 1086 bytes pdfjs/web/cmaps/B5-V.bcmap | Bin 0 -> 142 bytes pdfjs/web/cmaps/B5pc-H.bcmap | Bin 0 -> 1099 bytes pdfjs/web/cmaps/B5pc-V.bcmap | Bin 0 -> 144 bytes pdfjs/web/cmaps/CNS-EUC-H.bcmap | Bin 0 -> 1780 bytes pdfjs/web/cmaps/CNS-EUC-V.bcmap | Bin 0 -> 1920 bytes pdfjs/web/cmaps/CNS1-H.bcmap | Bin 0 -> 706 bytes pdfjs/web/cmaps/CNS1-V.bcmap | Bin 0 -> 143 bytes pdfjs/web/cmaps/CNS2-H.bcmap | Bin 0 -> 504 bytes pdfjs/web/cmaps/CNS2-V.bcmap | 3 + pdfjs/web/cmaps/ETHK-B5-H.bcmap | Bin 0 -> 4426 bytes pdfjs/web/cmaps/ETHK-B5-V.bcmap | Bin 0 -> 158 bytes pdfjs/web/cmaps/ETen-B5-H.bcmap | Bin 0 -> 1125 bytes pdfjs/web/cmaps/ETen-B5-V.bcmap | Bin 0 -> 158 bytes pdfjs/web/cmaps/ETenms-B5-H.bcmap | 3 + pdfjs/web/cmaps/ETenms-B5-V.bcmap | Bin 0 -> 172 bytes pdfjs/web/cmaps/EUC-H.bcmap | Bin 0 -> 578 bytes pdfjs/web/cmaps/EUC-V.bcmap | Bin 0 -> 170 bytes pdfjs/web/cmaps/Ext-H.bcmap | Bin 0 -> 2536 bytes pdfjs/web/cmaps/Ext-RKSJ-H.bcmap | Bin 0 -> 2542 bytes pdfjs/web/cmaps/Ext-RKSJ-V.bcmap | Bin 0 -> 218 bytes pdfjs/web/cmaps/Ext-V.bcmap | Bin 0 -> 215 bytes pdfjs/web/cmaps/GB-EUC-H.bcmap | Bin 0 -> 549 bytes pdfjs/web/cmaps/GB-EUC-V.bcmap | Bin 0 -> 179 bytes pdfjs/web/cmaps/GB-H.bcmap | 4 + pdfjs/web/cmaps/GB-V.bcmap | Bin 0 -> 175 bytes pdfjs/web/cmaps/GBK-EUC-H.bcmap | Bin 0 -> 14692 bytes pdfjs/web/cmaps/GBK-EUC-V.bcmap | Bin 0 -> 180 bytes pdfjs/web/cmaps/GBK2K-H.bcmap | Bin 0 -> 19662 bytes pdfjs/web/cmaps/GBK2K-V.bcmap | Bin 0 -> 219 bytes pdfjs/web/cmaps/GBKp-EUC-H.bcmap | Bin 0 -> 14686 bytes pdfjs/web/cmaps/GBKp-EUC-V.bcmap | Bin 0 -> 181 bytes pdfjs/web/cmaps/GBT-EUC-H.bcmap | Bin 0 -> 7290 bytes pdfjs/web/cmaps/GBT-EUC-V.bcmap | Bin 0 -> 180 bytes pdfjs/web/cmaps/GBT-H.bcmap | Bin 0 -> 7269 bytes pdfjs/web/cmaps/GBT-V.bcmap | Bin 0 -> 176 bytes pdfjs/web/cmaps/GBTpc-EUC-H.bcmap | Bin 0 -> 7298 bytes pdfjs/web/cmaps/GBTpc-EUC-V.bcmap | Bin 0 -> 182 bytes pdfjs/web/cmaps/GBpc-EUC-H.bcmap | Bin 0 -> 557 bytes pdfjs/web/cmaps/GBpc-EUC-V.bcmap | Bin 0 -> 181 bytes pdfjs/web/cmaps/H.bcmap | Bin 0 -> 553 bytes pdfjs/web/cmaps/HKdla-B5-H.bcmap | Bin 0 -> 2654 bytes pdfjs/web/cmaps/HKdla-B5-V.bcmap | Bin 0 -> 148 bytes pdfjs/web/cmaps/HKdlb-B5-H.bcmap | Bin 0 -> 2414 bytes pdfjs/web/cmaps/HKdlb-B5-V.bcmap | Bin 0 -> 148 bytes pdfjs/web/cmaps/HKgccs-B5-H.bcmap | Bin 0 -> 2292 bytes pdfjs/web/cmaps/HKgccs-B5-V.bcmap | Bin 0 -> 149 bytes pdfjs/web/cmaps/HKm314-B5-H.bcmap | Bin 0 -> 1772 bytes pdfjs/web/cmaps/HKm314-B5-V.bcmap | Bin 0 -> 149 bytes pdfjs/web/cmaps/HKm471-B5-H.bcmap | Bin 0 -> 2171 bytes pdfjs/web/cmaps/HKm471-B5-V.bcmap | Bin 0 -> 149 bytes pdfjs/web/cmaps/HKscs-B5-H.bcmap | Bin 0 -> 4437 bytes pdfjs/web/cmaps/HKscs-B5-V.bcmap | Bin 0 -> 159 bytes pdfjs/web/cmaps/Hankaku.bcmap | Bin 0 -> 132 bytes pdfjs/web/cmaps/Hiragana.bcmap | Bin 0 -> 124 bytes pdfjs/web/cmaps/KSC-EUC-H.bcmap | Bin 0 -> 1848 bytes pdfjs/web/cmaps/KSC-EUC-V.bcmap | Bin 0 -> 164 bytes pdfjs/web/cmaps/KSC-H.bcmap | Bin 0 -> 1831 bytes pdfjs/web/cmaps/KSC-Johab-H.bcmap | Bin 0 -> 16791 bytes pdfjs/web/cmaps/KSC-Johab-V.bcmap | Bin 0 -> 166 bytes pdfjs/web/cmaps/KSC-V.bcmap | Bin 0 -> 160 bytes pdfjs/web/cmaps/KSCms-UHC-H.bcmap | Bin 0 -> 2787 bytes pdfjs/web/cmaps/KSCms-UHC-HW-H.bcmap | Bin 0 -> 2789 bytes pdfjs/web/cmaps/KSCms-UHC-HW-V.bcmap | Bin 0 -> 169 bytes pdfjs/web/cmaps/KSCms-UHC-V.bcmap | Bin 0 -> 166 bytes pdfjs/web/cmaps/KSCpc-EUC-H.bcmap | Bin 0 -> 2024 bytes pdfjs/web/cmaps/KSCpc-EUC-V.bcmap | Bin 0 -> 166 bytes pdfjs/web/cmaps/Katakana.bcmap | Bin 0 -> 100 bytes pdfjs/web/cmaps/LICENSE | 36 + pdfjs/web/cmaps/NWP-H.bcmap | Bin 0 -> 2765 bytes pdfjs/web/cmaps/NWP-V.bcmap | Bin 0 -> 252 bytes pdfjs/web/cmaps/RKSJ-H.bcmap | Bin 0 -> 534 bytes pdfjs/web/cmaps/RKSJ-V.bcmap | Bin 0 -> 170 bytes pdfjs/web/cmaps/Roman.bcmap | Bin 0 -> 96 bytes pdfjs/web/cmaps/UniCNS-UCS2-H.bcmap | Bin 0 -> 48280 bytes pdfjs/web/cmaps/UniCNS-UCS2-V.bcmap | Bin 0 -> 156 bytes pdfjs/web/cmaps/UniCNS-UTF16-H.bcmap | Bin 0 -> 50419 bytes pdfjs/web/cmaps/UniCNS-UTF16-V.bcmap | Bin 0 -> 156 bytes pdfjs/web/cmaps/UniCNS-UTF32-H.bcmap | Bin 0 -> 52679 bytes pdfjs/web/cmaps/UniCNS-UTF32-V.bcmap | Bin 0 -> 160 bytes pdfjs/web/cmaps/UniCNS-UTF8-H.bcmap | Bin 0 -> 53629 bytes pdfjs/web/cmaps/UniCNS-UTF8-V.bcmap | Bin 0 -> 157 bytes pdfjs/web/cmaps/UniGB-UCS2-H.bcmap | Bin 0 -> 43366 bytes pdfjs/web/cmaps/UniGB-UCS2-V.bcmap | Bin 0 -> 193 bytes pdfjs/web/cmaps/UniGB-UTF16-H.bcmap | Bin 0 -> 44086 bytes pdfjs/web/cmaps/UniGB-UTF16-V.bcmap | Bin 0 -> 178 bytes pdfjs/web/cmaps/UniGB-UTF32-H.bcmap | Bin 0 -> 45738 bytes pdfjs/web/cmaps/UniGB-UTF32-V.bcmap | Bin 0 -> 182 bytes pdfjs/web/cmaps/UniGB-UTF8-H.bcmap | Bin 0 -> 46837 bytes pdfjs/web/cmaps/UniGB-UTF8-V.bcmap | Bin 0 -> 181 bytes pdfjs/web/cmaps/UniJIS-UCS2-H.bcmap | Bin 0 -> 25439 bytes pdfjs/web/cmaps/UniJIS-UCS2-HW-H.bcmap | Bin 0 -> 119 bytes pdfjs/web/cmaps/UniJIS-UCS2-HW-V.bcmap | Bin 0 -> 680 bytes pdfjs/web/cmaps/UniJIS-UCS2-V.bcmap | Bin 0 -> 664 bytes pdfjs/web/cmaps/UniJIS-UTF16-H.bcmap | Bin 0 -> 39443 bytes pdfjs/web/cmaps/UniJIS-UTF16-V.bcmap | Bin 0 -> 643 bytes pdfjs/web/cmaps/UniJIS-UTF32-H.bcmap | Bin 0 -> 40539 bytes pdfjs/web/cmaps/UniJIS-UTF32-V.bcmap | Bin 0 -> 677 bytes pdfjs/web/cmaps/UniJIS-UTF8-H.bcmap | Bin 0 -> 41695 bytes pdfjs/web/cmaps/UniJIS-UTF8-V.bcmap | Bin 0 -> 678 bytes pdfjs/web/cmaps/UniJIS2004-UTF16-H.bcmap | Bin 0 -> 39534 bytes pdfjs/web/cmaps/UniJIS2004-UTF16-V.bcmap | Bin 0 -> 647 bytes pdfjs/web/cmaps/UniJIS2004-UTF32-H.bcmap | Bin 0 -> 40630 bytes pdfjs/web/cmaps/UniJIS2004-UTF32-V.bcmap | Bin 0 -> 681 bytes pdfjs/web/cmaps/UniJIS2004-UTF8-H.bcmap | Bin 0 -> 41779 bytes pdfjs/web/cmaps/UniJIS2004-UTF8-V.bcmap | Bin 0 -> 682 bytes pdfjs/web/cmaps/UniJISPro-UCS2-HW-V.bcmap | Bin 0 -> 705 bytes pdfjs/web/cmaps/UniJISPro-UCS2-V.bcmap | Bin 0 -> 689 bytes pdfjs/web/cmaps/UniJISPro-UTF8-V.bcmap | Bin 0 -> 726 bytes pdfjs/web/cmaps/UniJISX0213-UTF32-H.bcmap | Bin 0 -> 40517 bytes pdfjs/web/cmaps/UniJISX0213-UTF32-V.bcmap | Bin 0 -> 684 bytes pdfjs/web/cmaps/UniJISX02132004-UTF32-H.bcmap | Bin 0 -> 40608 bytes pdfjs/web/cmaps/UniJISX02132004-UTF32-V.bcmap | Bin 0 -> 688 bytes pdfjs/web/cmaps/UniKS-UCS2-H.bcmap | Bin 0 -> 25783 bytes pdfjs/web/cmaps/UniKS-UCS2-V.bcmap | Bin 0 -> 178 bytes pdfjs/web/cmaps/UniKS-UTF16-H.bcmap | Bin 0 -> 26327 bytes pdfjs/web/cmaps/UniKS-UTF16-V.bcmap | Bin 0 -> 164 bytes pdfjs/web/cmaps/UniKS-UTF32-H.bcmap | Bin 0 -> 26451 bytes pdfjs/web/cmaps/UniKS-UTF32-V.bcmap | Bin 0 -> 168 bytes pdfjs/web/cmaps/UniKS-UTF8-H.bcmap | Bin 0 -> 27790 bytes pdfjs/web/cmaps/UniKS-UTF8-V.bcmap | Bin 0 -> 169 bytes pdfjs/web/cmaps/V.bcmap | Bin 0 -> 166 bytes pdfjs/web/cmaps/WP-Symbol.bcmap | Bin 0 -> 179 bytes pdfjs/web/compressed.tracemonkey-pldi-09.pdf | Bin 0 -> 1016315 bytes pdfjs/web/debugger.css | 111 + pdfjs/web/debugger.mjs | 623 + pdfjs/web/images/altText_add.svg | 3 + pdfjs/web/images/altText_disclaimer.svg | 3 + pdfjs/web/images/altText_done.svg | 3 + pdfjs/web/images/altText_spinner.svg | 30 + pdfjs/web/images/altText_warning.svg | 3 + pdfjs/web/images/annotation-check.svg | 11 + pdfjs/web/images/annotation-comment.svg | 16 + pdfjs/web/images/annotation-help.svg | 26 + pdfjs/web/images/annotation-insert.svg | 10 + pdfjs/web/images/annotation-key.svg | 11 + pdfjs/web/images/annotation-newparagraph.svg | 11 + pdfjs/web/images/annotation-noicon.svg | 7 + pdfjs/web/images/annotation-note.svg | 42 + pdfjs/web/images/annotation-paperclip.svg | 6 + pdfjs/web/images/annotation-paragraph.svg | 16 + pdfjs/web/images/annotation-pushpin.svg | 7 + .../web/images/cursor-editorFreeHighlight.svg | 6 + pdfjs/web/images/cursor-editorFreeText.svg | 3 + pdfjs/web/images/cursor-editorInk.svg | 4 + .../web/images/cursor-editorTextHighlight.svg | 8 + pdfjs/web/images/editor-toolbar-delete.svg | 5 + pdfjs/web/images/findbarButton-next.svg | 3 + pdfjs/web/images/findbarButton-previous.svg | 3 + .../web/images/gv-toolbarButton-download.svg | 3 + pdfjs/web/images/loading-icon.gif | Bin 0 -> 2545 bytes pdfjs/web/images/loading.svg | 1 + pdfjs/web/images/messageBar_closingButton.svg | 3 + pdfjs/web/images/messageBar_warning.svg | 3 + ...ondaryToolbarButton-documentProperties.svg | 3 + .../secondaryToolbarButton-firstPage.svg | 3 + .../secondaryToolbarButton-handTool.svg | 3 + .../secondaryToolbarButton-lastPage.svg | 3 + .../secondaryToolbarButton-rotateCcw.svg | 3 + .../secondaryToolbarButton-rotateCw.svg | 3 + ...econdaryToolbarButton-scrollHorizontal.svg | 3 + .../secondaryToolbarButton-scrollPage.svg | 3 + .../secondaryToolbarButton-scrollVertical.svg | 3 + .../secondaryToolbarButton-scrollWrapped.svg | 3 + .../secondaryToolbarButton-selectTool.svg | 3 + .../secondaryToolbarButton-spreadEven.svg | 3 + .../secondaryToolbarButton-spreadNone.svg | 3 + .../secondaryToolbarButton-spreadOdd.svg | 3 + pdfjs/web/images/toolbarButton-bookmark.svg | 3 + .../toolbarButton-currentOutlineItem.svg | 3 + pdfjs/web/images/toolbarButton-download.svg | 4 + .../images/toolbarButton-editorFreeText.svg | 5 + .../images/toolbarButton-editorHighlight.svg | 6 + pdfjs/web/images/toolbarButton-editorInk.svg | 4 + .../web/images/toolbarButton-editorStamp.svg | 8 + pdfjs/web/images/toolbarButton-menuArrow.svg | 3 + pdfjs/web/images/toolbarButton-openFile.svg | 3 + pdfjs/web/images/toolbarButton-pageDown.svg | 3 + pdfjs/web/images/toolbarButton-pageUp.svg | 3 + .../images/toolbarButton-presentationMode.svg | 3 + pdfjs/web/images/toolbarButton-print.svg | 3 + pdfjs/web/images/toolbarButton-search.svg | 3 + .../toolbarButton-secondaryToolbarToggle.svg | 3 + .../images/toolbarButton-sidebarToggle.svg | 3 + .../images/toolbarButton-viewAttachments.svg | 3 + pdfjs/web/images/toolbarButton-viewLayers.svg | 3 + .../web/images/toolbarButton-viewOutline.svg | 3 + .../images/toolbarButton-viewThumbnail.svg | 3 + pdfjs/web/images/toolbarButton-zoomIn.svg | 3 + pdfjs/web/images/toolbarButton-zoomOut.svg | 3 + pdfjs/web/images/treeitem-collapsed.svg | 1 + pdfjs/web/images/treeitem-expanded.svg | 1 + pdfjs/web/locale/ach/viewer.ftl | 225 + pdfjs/web/locale/af/viewer.ftl | 212 + pdfjs/web/locale/an/viewer.ftl | 257 + pdfjs/web/locale/ar/viewer.ftl | 425 + pdfjs/web/locale/ast/viewer.ftl | 201 + pdfjs/web/locale/az/viewer.ftl | 257 + pdfjs/web/locale/be/viewer.ftl | 497 + pdfjs/web/locale/bg/viewer.ftl | 418 + pdfjs/web/locale/bn/viewer.ftl | 247 + pdfjs/web/locale/bo/viewer.ftl | 247 + pdfjs/web/locale/br/viewer.ftl | 340 + pdfjs/web/locale/brx/viewer.ftl | 218 + pdfjs/web/locale/bs/viewer.ftl | 223 + pdfjs/web/locale/ca/viewer.ftl | 313 + pdfjs/web/locale/cak/viewer.ftl | 291 + pdfjs/web/locale/ckb/viewer.ftl | 242 + pdfjs/web/locale/cs/viewer.ftl | 499 + pdfjs/web/locale/cy/viewer.ftl | 503 + pdfjs/web/locale/da/viewer.ftl | 495 + pdfjs/web/locale/de/viewer.ftl | 495 + pdfjs/web/locale/dsb/viewer.ftl | 499 + pdfjs/web/locale/el/viewer.ftl | 495 + pdfjs/web/locale/en-CA/viewer.ftl | 481 + pdfjs/web/locale/en-GB/viewer.ftl | 495 + pdfjs/web/locale/en-US/viewer.ftl | 526 + pdfjs/web/locale/eo/viewer.ftl | 481 + pdfjs/web/locale/es-AR/viewer.ftl | 495 + pdfjs/web/locale/es-CL/viewer.ftl | 495 + pdfjs/web/locale/es-ES/viewer.ftl | 495 + pdfjs/web/locale/es-MX/viewer.ftl | 401 + pdfjs/web/locale/et/viewer.ftl | 268 + pdfjs/web/locale/eu/viewer.ftl | 495 + pdfjs/web/locale/fa/viewer.ftl | 246 + pdfjs/web/locale/ff/viewer.ftl | 247 + pdfjs/web/locale/fi/viewer.ftl | 495 + pdfjs/web/locale/fr/viewer.ftl | 491 + pdfjs/web/locale/fur/viewer.ftl | 485 + pdfjs/web/locale/fy-NL/viewer.ftl | 495 + pdfjs/web/locale/ga-IE/viewer.ftl | 213 + pdfjs/web/locale/gd/viewer.ftl | 313 + pdfjs/web/locale/gl/viewer.ftl | 385 + pdfjs/web/locale/gn/viewer.ftl | 495 + pdfjs/web/locale/gu-IN/viewer.ftl | 247 + pdfjs/web/locale/he/viewer.ftl | 495 + pdfjs/web/locale/hi-IN/viewer.ftl | 267 + pdfjs/web/locale/hr/viewer.ftl | 473 + pdfjs/web/locale/hsb/viewer.ftl | 499 + pdfjs/web/locale/hu/viewer.ftl | 495 + pdfjs/web/locale/hy-AM/viewer.ftl | 272 + pdfjs/web/locale/hye/viewer.ftl | 268 + pdfjs/web/locale/ia/viewer.ftl | 495 + pdfjs/web/locale/id/viewer.ftl | 293 + pdfjs/web/locale/is/viewer.ftl | 495 + pdfjs/web/locale/it/viewer.ftl | 495 + pdfjs/web/locale/ja/viewer.ftl | 488 + pdfjs/web/locale/ka/viewer.ftl | 406 + pdfjs/web/locale/kab/viewer.ftl | 438 + pdfjs/web/locale/kk/viewer.ftl | 495 + pdfjs/web/locale/km/viewer.ftl | 223 + pdfjs/web/locale/kn/viewer.ftl | 213 + pdfjs/web/locale/ko/viewer.ftl | 487 + pdfjs/web/locale/lij/viewer.ftl | 247 + pdfjs/web/locale/lo/viewer.ftl | 313 + pdfjs/web/locale/locale.json | 1 + pdfjs/web/locale/lt/viewer.ftl | 268 + pdfjs/web/locale/ltg/viewer.ftl | 246 + pdfjs/web/locale/lv/viewer.ftl | 247 + pdfjs/web/locale/meh/viewer.ftl | 87 + pdfjs/web/locale/mk/viewer.ftl | 215 + pdfjs/web/locale/mr/viewer.ftl | 239 + pdfjs/web/locale/ms/viewer.ftl | 247 + pdfjs/web/locale/my/viewer.ftl | 206 + pdfjs/web/locale/nb-NO/viewer.ftl | 495 + pdfjs/web/locale/ne-NP/viewer.ftl | 234 + pdfjs/web/locale/nl/viewer.ftl | 495 + pdfjs/web/locale/nn-NO/viewer.ftl | 481 + pdfjs/web/locale/oc/viewer.ftl | 361 + pdfjs/web/locale/pa-IN/viewer.ftl | 495 + pdfjs/web/locale/pl/viewer.ftl | 497 + pdfjs/web/locale/pt-BR/viewer.ftl | 495 + pdfjs/web/locale/pt-PT/viewer.ftl | 485 + pdfjs/web/locale/rm/viewer.ftl | 495 + pdfjs/web/locale/ro/viewer.ftl | 251 + pdfjs/web/locale/ru/viewer.ftl | 497 + pdfjs/web/locale/sat/viewer.ftl | 325 + pdfjs/web/locale/sc/viewer.ftl | 367 + pdfjs/web/locale/scn/viewer.ftl | 74 + pdfjs/web/locale/sco/viewer.ftl | 264 + pdfjs/web/locale/si/viewer.ftl | 271 + pdfjs/web/locale/sk/viewer.ftl | 499 + pdfjs/web/locale/skr/viewer.ftl | 481 + pdfjs/web/locale/sl/viewer.ftl | 499 + pdfjs/web/locale/son/viewer.ftl | 206 + pdfjs/web/locale/sq/viewer.ftl | 486 + pdfjs/web/locale/sr/viewer.ftl | 313 + pdfjs/web/locale/sv-SE/viewer.ftl | 495 + pdfjs/web/locale/szl/viewer.ftl | 257 + pdfjs/web/locale/ta/viewer.ftl | 223 + pdfjs/web/locale/te/viewer.ftl | 239 + pdfjs/web/locale/tg/viewer.ftl | 478 + pdfjs/web/locale/th/viewer.ftl | 487 + pdfjs/web/locale/tl/viewer.ftl | 257 + pdfjs/web/locale/tr/viewer.ftl | 495 + pdfjs/web/locale/trs/viewer.ftl | 197 + pdfjs/web/locale/uk/viewer.ftl | 497 + pdfjs/web/locale/ur/viewer.ftl | 248 + pdfjs/web/locale/uz/viewer.ftl | 187 + pdfjs/web/locale/vi/viewer.ftl | 487 + pdfjs/web/locale/wo/viewer.ftl | 127 + pdfjs/web/locale/xh/viewer.ftl | 212 + pdfjs/web/locale/zh-CN/viewer.ftl | 487 + pdfjs/web/locale/zh-TW/viewer.ftl | 487 + pdfjs/web/standard_fonts/FoxitDingbats.pfb | Bin 0 -> 29513 bytes pdfjs/web/standard_fonts/FoxitFixed.pfb | Bin 0 -> 17597 bytes pdfjs/web/standard_fonts/FoxitFixedBold.pfb | Bin 0 -> 18055 bytes .../standard_fonts/FoxitFixedBoldItalic.pfb | Bin 0 -> 19151 bytes pdfjs/web/standard_fonts/FoxitFixedItalic.pfb | Bin 0 -> 18746 bytes pdfjs/web/standard_fonts/FoxitSerif.pfb | Bin 0 -> 19469 bytes pdfjs/web/standard_fonts/FoxitSerifBold.pfb | Bin 0 -> 19395 bytes .../standard_fonts/FoxitSerifBoldItalic.pfb | Bin 0 -> 20733 bytes pdfjs/web/standard_fonts/FoxitSerifItalic.pfb | Bin 0 -> 21227 bytes pdfjs/web/standard_fonts/FoxitSymbol.pfb | Bin 0 -> 16729 bytes pdfjs/web/standard_fonts/LICENSE_FOXIT | 27 + pdfjs/web/standard_fonts/LICENSE_LIBERATION | 102 + .../standard_fonts/LiberationSans-Bold.ttf | Bin 0 -> 137052 bytes .../LiberationSans-BoldItalic.ttf | Bin 0 -> 135124 bytes .../standard_fonts/LiberationSans-Italic.ttf | Bin 0 -> 162036 bytes .../standard_fonts/LiberationSans-Regular.ttf | Bin 0 -> 139512 bytes pdfjs/web/viewer.css | 5199 ++ pdfjs/web/viewer.html | 637 + pdfjs/web/viewer.mjs | 15428 +++++ pdfjs/web/viewer.mjs.map | 1 + shortlister/web.py | 2 +- 378 files changed, 142086 insertions(+), 1 deletion(-) create mode 100644 pdfjs/LICENSE create mode 100644 pdfjs/build/pdf.mjs create mode 100644 pdfjs/build/pdf.mjs.map create mode 100644 pdfjs/build/pdf.sandbox.mjs create mode 100644 pdfjs/build/pdf.sandbox.mjs.map create mode 100644 pdfjs/build/pdf.worker.mjs create mode 100644 pdfjs/build/pdf.worker.mjs.map create mode 100644 pdfjs/web/cmaps/78-EUC-H.bcmap create mode 100644 pdfjs/web/cmaps/78-EUC-V.bcmap create mode 100644 pdfjs/web/cmaps/78-H.bcmap create mode 100644 pdfjs/web/cmaps/78-RKSJ-H.bcmap create mode 100644 pdfjs/web/cmaps/78-RKSJ-V.bcmap create mode 100644 pdfjs/web/cmaps/78-V.bcmap create mode 100644 pdfjs/web/cmaps/78ms-RKSJ-H.bcmap create mode 100644 pdfjs/web/cmaps/78ms-RKSJ-V.bcmap create mode 100644 pdfjs/web/cmaps/83pv-RKSJ-H.bcmap create mode 100644 pdfjs/web/cmaps/90ms-RKSJ-H.bcmap create mode 100644 pdfjs/web/cmaps/90ms-RKSJ-V.bcmap create mode 100644 pdfjs/web/cmaps/90msp-RKSJ-H.bcmap create mode 100644 pdfjs/web/cmaps/90msp-RKSJ-V.bcmap create mode 100644 pdfjs/web/cmaps/90pv-RKSJ-H.bcmap create mode 100644 pdfjs/web/cmaps/90pv-RKSJ-V.bcmap create mode 100644 pdfjs/web/cmaps/Add-H.bcmap create mode 100644 pdfjs/web/cmaps/Add-RKSJ-H.bcmap create mode 100644 pdfjs/web/cmaps/Add-RKSJ-V.bcmap create mode 100644 pdfjs/web/cmaps/Add-V.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-CNS1-0.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-CNS1-1.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-CNS1-2.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-CNS1-3.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-CNS1-4.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-CNS1-5.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-CNS1-6.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-CNS1-UCS2.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-GB1-0.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-GB1-1.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-GB1-2.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-GB1-3.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-GB1-4.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-GB1-5.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-GB1-UCS2.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-Japan1-0.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-Japan1-1.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-Japan1-2.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-Japan1-3.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-Japan1-4.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-Japan1-5.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-Japan1-6.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-Japan1-UCS2.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-Korea1-0.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-Korea1-1.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-Korea1-2.bcmap create mode 100644 pdfjs/web/cmaps/Adobe-Korea1-UCS2.bcmap create mode 100644 pdfjs/web/cmaps/B5-H.bcmap create mode 100644 pdfjs/web/cmaps/B5-V.bcmap create mode 100644 pdfjs/web/cmaps/B5pc-H.bcmap create mode 100644 pdfjs/web/cmaps/B5pc-V.bcmap create mode 100644 pdfjs/web/cmaps/CNS-EUC-H.bcmap create mode 100644 pdfjs/web/cmaps/CNS-EUC-V.bcmap create mode 100644 pdfjs/web/cmaps/CNS1-H.bcmap create mode 100644 pdfjs/web/cmaps/CNS1-V.bcmap create mode 100644 pdfjs/web/cmaps/CNS2-H.bcmap create mode 100644 pdfjs/web/cmaps/CNS2-V.bcmap create mode 100644 pdfjs/web/cmaps/ETHK-B5-H.bcmap create mode 100644 pdfjs/web/cmaps/ETHK-B5-V.bcmap create mode 100644 pdfjs/web/cmaps/ETen-B5-H.bcmap create mode 100644 pdfjs/web/cmaps/ETen-B5-V.bcmap create mode 100644 pdfjs/web/cmaps/ETenms-B5-H.bcmap create mode 100644 pdfjs/web/cmaps/ETenms-B5-V.bcmap create mode 100644 pdfjs/web/cmaps/EUC-H.bcmap create mode 100644 pdfjs/web/cmaps/EUC-V.bcmap create mode 100644 pdfjs/web/cmaps/Ext-H.bcmap create mode 100644 pdfjs/web/cmaps/Ext-RKSJ-H.bcmap create mode 100644 pdfjs/web/cmaps/Ext-RKSJ-V.bcmap create mode 100644 pdfjs/web/cmaps/Ext-V.bcmap create mode 100644 pdfjs/web/cmaps/GB-EUC-H.bcmap create mode 100644 pdfjs/web/cmaps/GB-EUC-V.bcmap create mode 100644 pdfjs/web/cmaps/GB-H.bcmap create mode 100644 pdfjs/web/cmaps/GB-V.bcmap create mode 100644 pdfjs/web/cmaps/GBK-EUC-H.bcmap create mode 100644 pdfjs/web/cmaps/GBK-EUC-V.bcmap create mode 100644 pdfjs/web/cmaps/GBK2K-H.bcmap create mode 100644 pdfjs/web/cmaps/GBK2K-V.bcmap create mode 100644 pdfjs/web/cmaps/GBKp-EUC-H.bcmap create mode 100644 pdfjs/web/cmaps/GBKp-EUC-V.bcmap create mode 100644 pdfjs/web/cmaps/GBT-EUC-H.bcmap create mode 100644 pdfjs/web/cmaps/GBT-EUC-V.bcmap create mode 100644 pdfjs/web/cmaps/GBT-H.bcmap create mode 100644 pdfjs/web/cmaps/GBT-V.bcmap create mode 100644 pdfjs/web/cmaps/GBTpc-EUC-H.bcmap create mode 100644 pdfjs/web/cmaps/GBTpc-EUC-V.bcmap create mode 100644 pdfjs/web/cmaps/GBpc-EUC-H.bcmap create mode 100644 pdfjs/web/cmaps/GBpc-EUC-V.bcmap create mode 100644 pdfjs/web/cmaps/H.bcmap create mode 100644 pdfjs/web/cmaps/HKdla-B5-H.bcmap create mode 100644 pdfjs/web/cmaps/HKdla-B5-V.bcmap create mode 100644 pdfjs/web/cmaps/HKdlb-B5-H.bcmap create mode 100644 pdfjs/web/cmaps/HKdlb-B5-V.bcmap create mode 100644 pdfjs/web/cmaps/HKgccs-B5-H.bcmap create mode 100644 pdfjs/web/cmaps/HKgccs-B5-V.bcmap create mode 100644 pdfjs/web/cmaps/HKm314-B5-H.bcmap create mode 100644 pdfjs/web/cmaps/HKm314-B5-V.bcmap create mode 100644 pdfjs/web/cmaps/HKm471-B5-H.bcmap create mode 100644 pdfjs/web/cmaps/HKm471-B5-V.bcmap create mode 100644 pdfjs/web/cmaps/HKscs-B5-H.bcmap create mode 100644 pdfjs/web/cmaps/HKscs-B5-V.bcmap create mode 100644 pdfjs/web/cmaps/Hankaku.bcmap create mode 100644 pdfjs/web/cmaps/Hiragana.bcmap create mode 100644 pdfjs/web/cmaps/KSC-EUC-H.bcmap create mode 100644 pdfjs/web/cmaps/KSC-EUC-V.bcmap create mode 100644 pdfjs/web/cmaps/KSC-H.bcmap create mode 100644 pdfjs/web/cmaps/KSC-Johab-H.bcmap create mode 100644 pdfjs/web/cmaps/KSC-Johab-V.bcmap create mode 100644 pdfjs/web/cmaps/KSC-V.bcmap create mode 100644 pdfjs/web/cmaps/KSCms-UHC-H.bcmap create mode 100644 pdfjs/web/cmaps/KSCms-UHC-HW-H.bcmap create mode 100644 pdfjs/web/cmaps/KSCms-UHC-HW-V.bcmap create mode 100644 pdfjs/web/cmaps/KSCms-UHC-V.bcmap create mode 100644 pdfjs/web/cmaps/KSCpc-EUC-H.bcmap create mode 100644 pdfjs/web/cmaps/KSCpc-EUC-V.bcmap create mode 100644 pdfjs/web/cmaps/Katakana.bcmap create mode 100644 pdfjs/web/cmaps/LICENSE create mode 100644 pdfjs/web/cmaps/NWP-H.bcmap create mode 100644 pdfjs/web/cmaps/NWP-V.bcmap create mode 100644 pdfjs/web/cmaps/RKSJ-H.bcmap create mode 100644 pdfjs/web/cmaps/RKSJ-V.bcmap create mode 100644 pdfjs/web/cmaps/Roman.bcmap create mode 100644 pdfjs/web/cmaps/UniCNS-UCS2-H.bcmap create mode 100644 pdfjs/web/cmaps/UniCNS-UCS2-V.bcmap create mode 100644 pdfjs/web/cmaps/UniCNS-UTF16-H.bcmap create mode 100644 pdfjs/web/cmaps/UniCNS-UTF16-V.bcmap create mode 100644 pdfjs/web/cmaps/UniCNS-UTF32-H.bcmap create mode 100644 pdfjs/web/cmaps/UniCNS-UTF32-V.bcmap create mode 100644 pdfjs/web/cmaps/UniCNS-UTF8-H.bcmap create mode 100644 pdfjs/web/cmaps/UniCNS-UTF8-V.bcmap create mode 100644 pdfjs/web/cmaps/UniGB-UCS2-H.bcmap create mode 100644 pdfjs/web/cmaps/UniGB-UCS2-V.bcmap create mode 100644 pdfjs/web/cmaps/UniGB-UTF16-H.bcmap create mode 100644 pdfjs/web/cmaps/UniGB-UTF16-V.bcmap create mode 100644 pdfjs/web/cmaps/UniGB-UTF32-H.bcmap create mode 100644 pdfjs/web/cmaps/UniGB-UTF32-V.bcmap create mode 100644 pdfjs/web/cmaps/UniGB-UTF8-H.bcmap create mode 100644 pdfjs/web/cmaps/UniGB-UTF8-V.bcmap create mode 100644 pdfjs/web/cmaps/UniJIS-UCS2-H.bcmap create mode 100644 pdfjs/web/cmaps/UniJIS-UCS2-HW-H.bcmap create mode 100644 pdfjs/web/cmaps/UniJIS-UCS2-HW-V.bcmap create mode 100644 pdfjs/web/cmaps/UniJIS-UCS2-V.bcmap create mode 100644 pdfjs/web/cmaps/UniJIS-UTF16-H.bcmap create mode 100644 pdfjs/web/cmaps/UniJIS-UTF16-V.bcmap create mode 100644 pdfjs/web/cmaps/UniJIS-UTF32-H.bcmap create mode 100644 pdfjs/web/cmaps/UniJIS-UTF32-V.bcmap create mode 100644 pdfjs/web/cmaps/UniJIS-UTF8-H.bcmap create mode 100644 pdfjs/web/cmaps/UniJIS-UTF8-V.bcmap create mode 100644 pdfjs/web/cmaps/UniJIS2004-UTF16-H.bcmap create mode 100644 pdfjs/web/cmaps/UniJIS2004-UTF16-V.bcmap create mode 100644 pdfjs/web/cmaps/UniJIS2004-UTF32-H.bcmap create mode 100644 pdfjs/web/cmaps/UniJIS2004-UTF32-V.bcmap create mode 100644 pdfjs/web/cmaps/UniJIS2004-UTF8-H.bcmap create mode 100644 pdfjs/web/cmaps/UniJIS2004-UTF8-V.bcmap create mode 100644 pdfjs/web/cmaps/UniJISPro-UCS2-HW-V.bcmap create mode 100644 pdfjs/web/cmaps/UniJISPro-UCS2-V.bcmap create mode 100644 pdfjs/web/cmaps/UniJISPro-UTF8-V.bcmap create mode 100644 pdfjs/web/cmaps/UniJISX0213-UTF32-H.bcmap create mode 100644 pdfjs/web/cmaps/UniJISX0213-UTF32-V.bcmap create mode 100644 pdfjs/web/cmaps/UniJISX02132004-UTF32-H.bcmap create mode 100644 pdfjs/web/cmaps/UniJISX02132004-UTF32-V.bcmap create mode 100644 pdfjs/web/cmaps/UniKS-UCS2-H.bcmap create mode 100644 pdfjs/web/cmaps/UniKS-UCS2-V.bcmap create mode 100644 pdfjs/web/cmaps/UniKS-UTF16-H.bcmap create mode 100644 pdfjs/web/cmaps/UniKS-UTF16-V.bcmap create mode 100644 pdfjs/web/cmaps/UniKS-UTF32-H.bcmap create mode 100644 pdfjs/web/cmaps/UniKS-UTF32-V.bcmap create mode 100644 pdfjs/web/cmaps/UniKS-UTF8-H.bcmap create mode 100644 pdfjs/web/cmaps/UniKS-UTF8-V.bcmap create mode 100644 pdfjs/web/cmaps/V.bcmap create mode 100644 pdfjs/web/cmaps/WP-Symbol.bcmap create mode 100644 pdfjs/web/compressed.tracemonkey-pldi-09.pdf create mode 100644 pdfjs/web/debugger.css create mode 100644 pdfjs/web/debugger.mjs create mode 100644 pdfjs/web/images/altText_add.svg create mode 100644 pdfjs/web/images/altText_disclaimer.svg create mode 100644 pdfjs/web/images/altText_done.svg create mode 100644 pdfjs/web/images/altText_spinner.svg create mode 100644 pdfjs/web/images/altText_warning.svg create mode 100644 pdfjs/web/images/annotation-check.svg create mode 100644 pdfjs/web/images/annotation-comment.svg create mode 100644 pdfjs/web/images/annotation-help.svg create mode 100644 pdfjs/web/images/annotation-insert.svg create mode 100644 pdfjs/web/images/annotation-key.svg create mode 100644 pdfjs/web/images/annotation-newparagraph.svg create mode 100644 pdfjs/web/images/annotation-noicon.svg create mode 100644 pdfjs/web/images/annotation-note.svg create mode 100644 pdfjs/web/images/annotation-paperclip.svg create mode 100644 pdfjs/web/images/annotation-paragraph.svg create mode 100644 pdfjs/web/images/annotation-pushpin.svg create mode 100644 pdfjs/web/images/cursor-editorFreeHighlight.svg create mode 100644 pdfjs/web/images/cursor-editorFreeText.svg create mode 100644 pdfjs/web/images/cursor-editorInk.svg create mode 100644 pdfjs/web/images/cursor-editorTextHighlight.svg create mode 100644 pdfjs/web/images/editor-toolbar-delete.svg create mode 100644 pdfjs/web/images/findbarButton-next.svg create mode 100644 pdfjs/web/images/findbarButton-previous.svg create mode 100644 pdfjs/web/images/gv-toolbarButton-download.svg create mode 100644 pdfjs/web/images/loading-icon.gif create mode 100644 pdfjs/web/images/loading.svg create mode 100644 pdfjs/web/images/messageBar_closingButton.svg create mode 100644 pdfjs/web/images/messageBar_warning.svg create mode 100644 pdfjs/web/images/secondaryToolbarButton-documentProperties.svg create mode 100644 pdfjs/web/images/secondaryToolbarButton-firstPage.svg create mode 100644 pdfjs/web/images/secondaryToolbarButton-handTool.svg create mode 100644 pdfjs/web/images/secondaryToolbarButton-lastPage.svg create mode 100644 pdfjs/web/images/secondaryToolbarButton-rotateCcw.svg create mode 100644 pdfjs/web/images/secondaryToolbarButton-rotateCw.svg create mode 100644 pdfjs/web/images/secondaryToolbarButton-scrollHorizontal.svg create mode 100644 pdfjs/web/images/secondaryToolbarButton-scrollPage.svg create mode 100644 pdfjs/web/images/secondaryToolbarButton-scrollVertical.svg create mode 100644 pdfjs/web/images/secondaryToolbarButton-scrollWrapped.svg create mode 100644 pdfjs/web/images/secondaryToolbarButton-selectTool.svg create mode 100644 pdfjs/web/images/secondaryToolbarButton-spreadEven.svg create mode 100644 pdfjs/web/images/secondaryToolbarButton-spreadNone.svg create mode 100644 pdfjs/web/images/secondaryToolbarButton-spreadOdd.svg create mode 100644 pdfjs/web/images/toolbarButton-bookmark.svg create mode 100644 pdfjs/web/images/toolbarButton-currentOutlineItem.svg create mode 100644 pdfjs/web/images/toolbarButton-download.svg create mode 100644 pdfjs/web/images/toolbarButton-editorFreeText.svg create mode 100644 pdfjs/web/images/toolbarButton-editorHighlight.svg create mode 100644 pdfjs/web/images/toolbarButton-editorInk.svg create mode 100644 pdfjs/web/images/toolbarButton-editorStamp.svg create mode 100644 pdfjs/web/images/toolbarButton-menuArrow.svg create mode 100644 pdfjs/web/images/toolbarButton-openFile.svg create mode 100644 pdfjs/web/images/toolbarButton-pageDown.svg create mode 100644 pdfjs/web/images/toolbarButton-pageUp.svg create mode 100644 pdfjs/web/images/toolbarButton-presentationMode.svg create mode 100644 pdfjs/web/images/toolbarButton-print.svg create mode 100644 pdfjs/web/images/toolbarButton-search.svg create mode 100644 pdfjs/web/images/toolbarButton-secondaryToolbarToggle.svg create mode 100644 pdfjs/web/images/toolbarButton-sidebarToggle.svg create mode 100644 pdfjs/web/images/toolbarButton-viewAttachments.svg create mode 100644 pdfjs/web/images/toolbarButton-viewLayers.svg create mode 100644 pdfjs/web/images/toolbarButton-viewOutline.svg create mode 100644 pdfjs/web/images/toolbarButton-viewThumbnail.svg create mode 100644 pdfjs/web/images/toolbarButton-zoomIn.svg create mode 100644 pdfjs/web/images/toolbarButton-zoomOut.svg create mode 100644 pdfjs/web/images/treeitem-collapsed.svg create mode 100644 pdfjs/web/images/treeitem-expanded.svg create mode 100644 pdfjs/web/locale/ach/viewer.ftl create mode 100644 pdfjs/web/locale/af/viewer.ftl create mode 100644 pdfjs/web/locale/an/viewer.ftl create mode 100644 pdfjs/web/locale/ar/viewer.ftl create mode 100644 pdfjs/web/locale/ast/viewer.ftl create mode 100644 pdfjs/web/locale/az/viewer.ftl create mode 100644 pdfjs/web/locale/be/viewer.ftl create mode 100644 pdfjs/web/locale/bg/viewer.ftl create mode 100644 pdfjs/web/locale/bn/viewer.ftl create mode 100644 pdfjs/web/locale/bo/viewer.ftl create mode 100644 pdfjs/web/locale/br/viewer.ftl create mode 100644 pdfjs/web/locale/brx/viewer.ftl create mode 100644 pdfjs/web/locale/bs/viewer.ftl create mode 100644 pdfjs/web/locale/ca/viewer.ftl create mode 100644 pdfjs/web/locale/cak/viewer.ftl create mode 100644 pdfjs/web/locale/ckb/viewer.ftl create mode 100644 pdfjs/web/locale/cs/viewer.ftl create mode 100644 pdfjs/web/locale/cy/viewer.ftl create mode 100644 pdfjs/web/locale/da/viewer.ftl create mode 100644 pdfjs/web/locale/de/viewer.ftl create mode 100644 pdfjs/web/locale/dsb/viewer.ftl create mode 100644 pdfjs/web/locale/el/viewer.ftl create mode 100644 pdfjs/web/locale/en-CA/viewer.ftl create mode 100644 pdfjs/web/locale/en-GB/viewer.ftl create mode 100644 pdfjs/web/locale/en-US/viewer.ftl create mode 100644 pdfjs/web/locale/eo/viewer.ftl create mode 100644 pdfjs/web/locale/es-AR/viewer.ftl create mode 100644 pdfjs/web/locale/es-CL/viewer.ftl create mode 100644 pdfjs/web/locale/es-ES/viewer.ftl create mode 100644 pdfjs/web/locale/es-MX/viewer.ftl create mode 100644 pdfjs/web/locale/et/viewer.ftl create mode 100644 pdfjs/web/locale/eu/viewer.ftl create mode 100644 pdfjs/web/locale/fa/viewer.ftl create mode 100644 pdfjs/web/locale/ff/viewer.ftl create mode 100644 pdfjs/web/locale/fi/viewer.ftl create mode 100644 pdfjs/web/locale/fr/viewer.ftl create mode 100644 pdfjs/web/locale/fur/viewer.ftl create mode 100644 pdfjs/web/locale/fy-NL/viewer.ftl create mode 100644 pdfjs/web/locale/ga-IE/viewer.ftl create mode 100644 pdfjs/web/locale/gd/viewer.ftl create mode 100644 pdfjs/web/locale/gl/viewer.ftl create mode 100644 pdfjs/web/locale/gn/viewer.ftl create mode 100644 pdfjs/web/locale/gu-IN/viewer.ftl create mode 100644 pdfjs/web/locale/he/viewer.ftl create mode 100644 pdfjs/web/locale/hi-IN/viewer.ftl create mode 100644 pdfjs/web/locale/hr/viewer.ftl create mode 100644 pdfjs/web/locale/hsb/viewer.ftl create mode 100644 pdfjs/web/locale/hu/viewer.ftl create mode 100644 pdfjs/web/locale/hy-AM/viewer.ftl create mode 100644 pdfjs/web/locale/hye/viewer.ftl create mode 100644 pdfjs/web/locale/ia/viewer.ftl create mode 100644 pdfjs/web/locale/id/viewer.ftl create mode 100644 pdfjs/web/locale/is/viewer.ftl create mode 100644 pdfjs/web/locale/it/viewer.ftl create mode 100644 pdfjs/web/locale/ja/viewer.ftl create mode 100644 pdfjs/web/locale/ka/viewer.ftl create mode 100644 pdfjs/web/locale/kab/viewer.ftl create mode 100644 pdfjs/web/locale/kk/viewer.ftl create mode 100644 pdfjs/web/locale/km/viewer.ftl create mode 100644 pdfjs/web/locale/kn/viewer.ftl create mode 100644 pdfjs/web/locale/ko/viewer.ftl create mode 100644 pdfjs/web/locale/lij/viewer.ftl create mode 100644 pdfjs/web/locale/lo/viewer.ftl create mode 100644 pdfjs/web/locale/locale.json create mode 100644 pdfjs/web/locale/lt/viewer.ftl create mode 100644 pdfjs/web/locale/ltg/viewer.ftl create mode 100644 pdfjs/web/locale/lv/viewer.ftl create mode 100644 pdfjs/web/locale/meh/viewer.ftl create mode 100644 pdfjs/web/locale/mk/viewer.ftl create mode 100644 pdfjs/web/locale/mr/viewer.ftl create mode 100644 pdfjs/web/locale/ms/viewer.ftl create mode 100644 pdfjs/web/locale/my/viewer.ftl create mode 100644 pdfjs/web/locale/nb-NO/viewer.ftl create mode 100644 pdfjs/web/locale/ne-NP/viewer.ftl create mode 100644 pdfjs/web/locale/nl/viewer.ftl create mode 100644 pdfjs/web/locale/nn-NO/viewer.ftl create mode 100644 pdfjs/web/locale/oc/viewer.ftl create mode 100644 pdfjs/web/locale/pa-IN/viewer.ftl create mode 100644 pdfjs/web/locale/pl/viewer.ftl create mode 100644 pdfjs/web/locale/pt-BR/viewer.ftl create mode 100644 pdfjs/web/locale/pt-PT/viewer.ftl create mode 100644 pdfjs/web/locale/rm/viewer.ftl create mode 100644 pdfjs/web/locale/ro/viewer.ftl create mode 100644 pdfjs/web/locale/ru/viewer.ftl create mode 100644 pdfjs/web/locale/sat/viewer.ftl create mode 100644 pdfjs/web/locale/sc/viewer.ftl create mode 100644 pdfjs/web/locale/scn/viewer.ftl create mode 100644 pdfjs/web/locale/sco/viewer.ftl create mode 100644 pdfjs/web/locale/si/viewer.ftl create mode 100644 pdfjs/web/locale/sk/viewer.ftl create mode 100644 pdfjs/web/locale/skr/viewer.ftl create mode 100644 pdfjs/web/locale/sl/viewer.ftl create mode 100644 pdfjs/web/locale/son/viewer.ftl create mode 100644 pdfjs/web/locale/sq/viewer.ftl create mode 100644 pdfjs/web/locale/sr/viewer.ftl create mode 100644 pdfjs/web/locale/sv-SE/viewer.ftl create mode 100644 pdfjs/web/locale/szl/viewer.ftl create mode 100644 pdfjs/web/locale/ta/viewer.ftl create mode 100644 pdfjs/web/locale/te/viewer.ftl create mode 100644 pdfjs/web/locale/tg/viewer.ftl create mode 100644 pdfjs/web/locale/th/viewer.ftl create mode 100644 pdfjs/web/locale/tl/viewer.ftl create mode 100644 pdfjs/web/locale/tr/viewer.ftl create mode 100644 pdfjs/web/locale/trs/viewer.ftl create mode 100644 pdfjs/web/locale/uk/viewer.ftl create mode 100644 pdfjs/web/locale/ur/viewer.ftl create mode 100644 pdfjs/web/locale/uz/viewer.ftl create mode 100644 pdfjs/web/locale/vi/viewer.ftl create mode 100644 pdfjs/web/locale/wo/viewer.ftl create mode 100644 pdfjs/web/locale/xh/viewer.ftl create mode 100644 pdfjs/web/locale/zh-CN/viewer.ftl create mode 100644 pdfjs/web/locale/zh-TW/viewer.ftl create mode 100644 pdfjs/web/standard_fonts/FoxitDingbats.pfb create mode 100644 pdfjs/web/standard_fonts/FoxitFixed.pfb create mode 100644 pdfjs/web/standard_fonts/FoxitFixedBold.pfb create mode 100644 pdfjs/web/standard_fonts/FoxitFixedBoldItalic.pfb create mode 100644 pdfjs/web/standard_fonts/FoxitFixedItalic.pfb create mode 100644 pdfjs/web/standard_fonts/FoxitSerif.pfb create mode 100644 pdfjs/web/standard_fonts/FoxitSerifBold.pfb create mode 100644 pdfjs/web/standard_fonts/FoxitSerifBoldItalic.pfb create mode 100644 pdfjs/web/standard_fonts/FoxitSerifItalic.pfb create mode 100644 pdfjs/web/standard_fonts/FoxitSymbol.pfb create mode 100644 pdfjs/web/standard_fonts/LICENSE_FOXIT create mode 100644 pdfjs/web/standard_fonts/LICENSE_LIBERATION create mode 100644 pdfjs/web/standard_fonts/LiberationSans-Bold.ttf create mode 100644 pdfjs/web/standard_fonts/LiberationSans-BoldItalic.ttf create mode 100644 pdfjs/web/standard_fonts/LiberationSans-Italic.ttf create mode 100644 pdfjs/web/standard_fonts/LiberationSans-Regular.ttf create mode 100644 pdfjs/web/viewer.css create mode 100644 pdfjs/web/viewer.html create mode 100644 pdfjs/web/viewer.mjs create mode 100644 pdfjs/web/viewer.mjs.map diff --git a/pdfjs/LICENSE b/pdfjs/LICENSE new file mode 100644 index 0000000..f433b1a --- /dev/null +++ b/pdfjs/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/pdfjs/build/pdf.mjs b/pdfjs/build/pdf.mjs new file mode 100644 index 0000000..c9f1e70 --- /dev/null +++ b/pdfjs/build/pdf.mjs @@ -0,0 +1,21337 @@ +/** + * @licstart The following is the entire license notice for the + * JavaScript code in this page + * + * Copyright 2024 Mozilla Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @licend The above is the entire license notice for the + * JavaScript code in this page + */ + +/******/ // The require scope +/******/ var __webpack_require__ = {}; +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __webpack_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/************************************************************************/ +var __webpack_exports__ = globalThis.pdfjsLib = {}; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + AbortException: () => (/* reexport */ AbortException), + AnnotationEditorLayer: () => (/* reexport */ AnnotationEditorLayer), + AnnotationEditorParamsType: () => (/* reexport */ AnnotationEditorParamsType), + AnnotationEditorType: () => (/* reexport */ AnnotationEditorType), + AnnotationEditorUIManager: () => (/* reexport */ AnnotationEditorUIManager), + AnnotationLayer: () => (/* reexport */ AnnotationLayer), + AnnotationMode: () => (/* reexport */ AnnotationMode), + ColorPicker: () => (/* reexport */ ColorPicker), + DOMSVGFactory: () => (/* reexport */ DOMSVGFactory), + DrawLayer: () => (/* reexport */ DrawLayer), + FeatureTest: () => (/* reexport */ util_FeatureTest), + GlobalWorkerOptions: () => (/* reexport */ GlobalWorkerOptions), + ImageKind: () => (/* reexport */ util_ImageKind), + InvalidPDFException: () => (/* reexport */ InvalidPDFException), + MissingPDFException: () => (/* reexport */ MissingPDFException), + OPS: () => (/* reexport */ OPS), + OutputScale: () => (/* reexport */ OutputScale), + PDFDataRangeTransport: () => (/* reexport */ PDFDataRangeTransport), + PDFDateString: () => (/* reexport */ PDFDateString), + PDFWorker: () => (/* reexport */ PDFWorker), + PasswordResponses: () => (/* reexport */ PasswordResponses), + PermissionFlag: () => (/* reexport */ PermissionFlag), + PixelsPerInch: () => (/* reexport */ PixelsPerInch), + RenderingCancelledException: () => (/* reexport */ RenderingCancelledException), + TextLayer: () => (/* reexport */ TextLayer), + UnexpectedResponseException: () => (/* reexport */ UnexpectedResponseException), + Util: () => (/* reexport */ Util), + VerbosityLevel: () => (/* reexport */ VerbosityLevel), + XfaLayer: () => (/* reexport */ XfaLayer), + build: () => (/* reexport */ build), + createValidAbsoluteUrl: () => (/* reexport */ createValidAbsoluteUrl), + fetchData: () => (/* reexport */ fetchData), + getDocument: () => (/* reexport */ getDocument), + getFilenameFromUrl: () => (/* reexport */ getFilenameFromUrl), + getPdfFilenameFromUrl: () => (/* reexport */ getPdfFilenameFromUrl), + getXfaPageViewport: () => (/* reexport */ getXfaPageViewport), + isDataScheme: () => (/* reexport */ isDataScheme), + isPdfFile: () => (/* reexport */ isPdfFile), + noContextMenu: () => (/* reexport */ noContextMenu), + normalizeUnicode: () => (/* reexport */ normalizeUnicode), + setLayerDimensions: () => (/* reexport */ setLayerDimensions), + shadow: () => (/* reexport */ shadow), + stopEvent: () => (/* reexport */ stopEvent), + version: () => (/* reexport */ version) +}); + +;// ./src/shared/util.js +const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser"); +const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; +const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; +const MAX_IMAGE_SIZE_TO_CACHE = 10e6; +const LINE_FACTOR = 1.35; +const LINE_DESCENT_FACTOR = 0.35; +const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR; +const RenderingIntentFlag = { + ANY: 0x01, + DISPLAY: 0x02, + PRINT: 0x04, + SAVE: 0x08, + ANNOTATIONS_FORMS: 0x10, + ANNOTATIONS_STORAGE: 0x20, + ANNOTATIONS_DISABLE: 0x40, + IS_EDITING: 0x80, + OPLIST: 0x100 +}; +const AnnotationMode = { + DISABLE: 0, + ENABLE: 1, + ENABLE_FORMS: 2, + ENABLE_STORAGE: 3 +}; +const AnnotationEditorPrefix = "pdfjs_internal_editor_"; +const AnnotationEditorType = { + DISABLE: -1, + NONE: 0, + FREETEXT: 3, + HIGHLIGHT: 9, + STAMP: 13, + INK: 15 +}; +const AnnotationEditorParamsType = { + RESIZE: 1, + CREATE: 2, + FREETEXT_SIZE: 11, + FREETEXT_COLOR: 12, + FREETEXT_OPACITY: 13, + INK_COLOR: 21, + INK_THICKNESS: 22, + INK_OPACITY: 23, + HIGHLIGHT_COLOR: 31, + HIGHLIGHT_DEFAULT_COLOR: 32, + HIGHLIGHT_THICKNESS: 33, + HIGHLIGHT_FREE: 34, + HIGHLIGHT_SHOW_ALL: 35, + DRAW_STEP: 41 +}; +const PermissionFlag = { + PRINT: 0x04, + MODIFY_CONTENTS: 0x08, + COPY: 0x10, + MODIFY_ANNOTATIONS: 0x20, + FILL_INTERACTIVE_FORMS: 0x100, + COPY_FOR_ACCESSIBILITY: 0x200, + ASSEMBLE: 0x400, + PRINT_HIGH_QUALITY: 0x800 +}; +const TextRenderingMode = { + FILL: 0, + STROKE: 1, + FILL_STROKE: 2, + INVISIBLE: 3, + FILL_ADD_TO_PATH: 4, + STROKE_ADD_TO_PATH: 5, + FILL_STROKE_ADD_TO_PATH: 6, + ADD_TO_PATH: 7, + FILL_STROKE_MASK: 3, + ADD_TO_PATH_FLAG: 4 +}; +const util_ImageKind = { + GRAYSCALE_1BPP: 1, + RGB_24BPP: 2, + RGBA_32BPP: 3 +}; +const AnnotationType = { + TEXT: 1, + LINK: 2, + FREETEXT: 3, + LINE: 4, + SQUARE: 5, + CIRCLE: 6, + POLYGON: 7, + POLYLINE: 8, + HIGHLIGHT: 9, + UNDERLINE: 10, + SQUIGGLY: 11, + STRIKEOUT: 12, + STAMP: 13, + CARET: 14, + INK: 15, + POPUP: 16, + FILEATTACHMENT: 17, + SOUND: 18, + MOVIE: 19, + WIDGET: 20, + SCREEN: 21, + PRINTERMARK: 22, + TRAPNET: 23, + WATERMARK: 24, + THREED: 25, + REDACT: 26 +}; +const AnnotationReplyType = { + GROUP: "Group", + REPLY: "R" +}; +const AnnotationFlag = { + INVISIBLE: 0x01, + HIDDEN: 0x02, + PRINT: 0x04, + NOZOOM: 0x08, + NOROTATE: 0x10, + NOVIEW: 0x20, + READONLY: 0x40, + LOCKED: 0x80, + TOGGLENOVIEW: 0x100, + LOCKEDCONTENTS: 0x200 +}; +const AnnotationFieldFlag = { + READONLY: 0x0000001, + REQUIRED: 0x0000002, + NOEXPORT: 0x0000004, + MULTILINE: 0x0001000, + PASSWORD: 0x0002000, + NOTOGGLETOOFF: 0x0004000, + RADIO: 0x0008000, + PUSHBUTTON: 0x0010000, + COMBO: 0x0020000, + EDIT: 0x0040000, + SORT: 0x0080000, + FILESELECT: 0x0100000, + MULTISELECT: 0x0200000, + DONOTSPELLCHECK: 0x0400000, + DONOTSCROLL: 0x0800000, + COMB: 0x1000000, + RICHTEXT: 0x2000000, + RADIOSINUNISON: 0x2000000, + COMMITONSELCHANGE: 0x4000000 +}; +const AnnotationBorderStyleType = { + SOLID: 1, + DASHED: 2, + BEVELED: 3, + INSET: 4, + UNDERLINE: 5 +}; +const AnnotationActionEventType = { + E: "Mouse Enter", + X: "Mouse Exit", + D: "Mouse Down", + U: "Mouse Up", + Fo: "Focus", + Bl: "Blur", + PO: "PageOpen", + PC: "PageClose", + PV: "PageVisible", + PI: "PageInvisible", + K: "Keystroke", + F: "Format", + V: "Validate", + C: "Calculate" +}; +const DocumentActionEventType = { + WC: "WillClose", + WS: "WillSave", + DS: "DidSave", + WP: "WillPrint", + DP: "DidPrint" +}; +const PageActionEventType = { + O: "PageOpen", + C: "PageClose" +}; +const VerbosityLevel = { + ERRORS: 0, + WARNINGS: 1, + INFOS: 5 +}; +const OPS = { + dependency: 1, + setLineWidth: 2, + setLineCap: 3, + setLineJoin: 4, + setMiterLimit: 5, + setDash: 6, + setRenderingIntent: 7, + setFlatness: 8, + setGState: 9, + save: 10, + restore: 11, + transform: 12, + moveTo: 13, + lineTo: 14, + curveTo: 15, + curveTo2: 16, + curveTo3: 17, + closePath: 18, + rectangle: 19, + stroke: 20, + closeStroke: 21, + fill: 22, + eoFill: 23, + fillStroke: 24, + eoFillStroke: 25, + closeFillStroke: 26, + closeEOFillStroke: 27, + endPath: 28, + clip: 29, + eoClip: 30, + beginText: 31, + endText: 32, + setCharSpacing: 33, + setWordSpacing: 34, + setHScale: 35, + setLeading: 36, + setFont: 37, + setTextRenderingMode: 38, + setTextRise: 39, + moveText: 40, + setLeadingMoveText: 41, + setTextMatrix: 42, + nextLine: 43, + showText: 44, + showSpacedText: 45, + nextLineShowText: 46, + nextLineSetSpacingShowText: 47, + setCharWidth: 48, + setCharWidthAndBounds: 49, + setStrokeColorSpace: 50, + setFillColorSpace: 51, + setStrokeColor: 52, + setStrokeColorN: 53, + setFillColor: 54, + setFillColorN: 55, + setStrokeGray: 56, + setFillGray: 57, + setStrokeRGBColor: 58, + setFillRGBColor: 59, + setStrokeCMYKColor: 60, + setFillCMYKColor: 61, + shadingFill: 62, + beginInlineImage: 63, + beginImageData: 64, + endInlineImage: 65, + paintXObject: 66, + markPoint: 67, + markPointProps: 68, + beginMarkedContent: 69, + beginMarkedContentProps: 70, + endMarkedContent: 71, + beginCompat: 72, + endCompat: 73, + paintFormXObjectBegin: 74, + paintFormXObjectEnd: 75, + beginGroup: 76, + endGroup: 77, + beginAnnotation: 80, + endAnnotation: 81, + paintImageMaskXObject: 83, + paintImageMaskXObjectGroup: 84, + paintImageXObject: 85, + paintInlineImageXObject: 86, + paintInlineImageXObjectGroup: 87, + paintImageXObjectRepeat: 88, + paintImageMaskXObjectRepeat: 89, + paintSolidColorImageMask: 90, + constructPath: 91, + setStrokeTransparent: 92, + setFillTransparent: 93 +}; +const PasswordResponses = { + NEED_PASSWORD: 1, + INCORRECT_PASSWORD: 2 +}; +let verbosity = VerbosityLevel.WARNINGS; +function setVerbosityLevel(level) { + if (Number.isInteger(level)) { + verbosity = level; + } +} +function getVerbosityLevel() { + return verbosity; +} +function info(msg) { + if (verbosity >= VerbosityLevel.INFOS) { + console.log(`Info: ${msg}`); + } +} +function warn(msg) { + if (verbosity >= VerbosityLevel.WARNINGS) { + console.log(`Warning: ${msg}`); + } +} +function unreachable(msg) { + throw new Error(msg); +} +function assert(cond, msg) { + if (!cond) { + unreachable(msg); + } +} +function _isValidProtocol(url) { + switch (url?.protocol) { + case "http:": + case "https:": + case "ftp:": + case "mailto:": + case "tel:": + return true; + default: + return false; + } +} +function createValidAbsoluteUrl(url, baseUrl = null, options = null) { + if (!url) { + return null; + } + try { + if (options && typeof url === "string") { + if (options.addDefaultProtocol && url.startsWith("www.")) { + const dots = url.match(/\./g); + if (dots?.length >= 2) { + url = `http://${url}`; + } + } + if (options.tryConvertEncoding) { + try { + url = stringToUTF8String(url); + } catch {} + } + } + const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url); + if (_isValidProtocol(absoluteUrl)) { + return absoluteUrl; + } + } catch {} + return null; +} +function shadow(obj, prop, value, nonSerializable = false) { + Object.defineProperty(obj, prop, { + value, + enumerable: !nonSerializable, + configurable: true, + writable: false + }); + return value; +} +const BaseException = function BaseExceptionClosure() { + function BaseException(message, name) { + this.message = message; + this.name = name; + } + BaseException.prototype = new Error(); + BaseException.constructor = BaseException; + return BaseException; +}(); +class PasswordException extends BaseException { + constructor(msg, code) { + super(msg, "PasswordException"); + this.code = code; + } +} +class UnknownErrorException extends BaseException { + constructor(msg, details) { + super(msg, "UnknownErrorException"); + this.details = details; + } +} +class InvalidPDFException extends BaseException { + constructor(msg) { + super(msg, "InvalidPDFException"); + } +} +class MissingPDFException extends BaseException { + constructor(msg) { + super(msg, "MissingPDFException"); + } +} +class UnexpectedResponseException extends BaseException { + constructor(msg, status) { + super(msg, "UnexpectedResponseException"); + this.status = status; + } +} +class FormatError extends BaseException { + constructor(msg) { + super(msg, "FormatError"); + } +} +class AbortException extends BaseException { + constructor(msg) { + super(msg, "AbortException"); + } +} +function bytesToString(bytes) { + if (typeof bytes !== "object" || bytes?.length === undefined) { + unreachable("Invalid argument for bytesToString"); + } + const length = bytes.length; + const MAX_ARGUMENT_COUNT = 8192; + if (length < MAX_ARGUMENT_COUNT) { + return String.fromCharCode.apply(null, bytes); + } + const strBuf = []; + for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) { + const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length); + const chunk = bytes.subarray(i, chunkEnd); + strBuf.push(String.fromCharCode.apply(null, chunk)); + } + return strBuf.join(""); +} +function stringToBytes(str) { + if (typeof str !== "string") { + unreachable("Invalid argument for stringToBytes"); + } + const length = str.length; + const bytes = new Uint8Array(length); + for (let i = 0; i < length; ++i) { + bytes[i] = str.charCodeAt(i) & 0xff; + } + return bytes; +} +function string32(value) { + return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff); +} +function objectSize(obj) { + return Object.keys(obj).length; +} +function objectFromMap(map) { + const obj = Object.create(null); + for (const [key, value] of map) { + obj[key] = value; + } + return obj; +} +function isLittleEndian() { + const buffer8 = new Uint8Array(4); + buffer8[0] = 1; + const view32 = new Uint32Array(buffer8.buffer, 0, 1); + return view32[0] === 1; +} +function isEvalSupported() { + try { + new Function(""); + return true; + } catch { + return false; + } +} +class util_FeatureTest { + static get isLittleEndian() { + return shadow(this, "isLittleEndian", isLittleEndian()); + } + static get isEvalSupported() { + return shadow(this, "isEvalSupported", isEvalSupported()); + } + static get isOffscreenCanvasSupported() { + return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined"); + } + static get isImageDecoderSupported() { + return shadow(this, "isImageDecoderSupported", typeof ImageDecoder !== "undefined"); + } + static get platform() { + if (typeof navigator !== "undefined" && typeof navigator?.platform === "string") { + return shadow(this, "platform", { + isMac: navigator.platform.includes("Mac"), + isWindows: navigator.platform.includes("Win"), + isFirefox: typeof navigator?.userAgent === "string" && navigator.userAgent.includes("Firefox") + }); + } + return shadow(this, "platform", { + isMac: false, + isWindows: false, + isFirefox: false + }); + } + static get isCSSRoundSupported() { + return shadow(this, "isCSSRoundSupported", globalThis.CSS?.supports?.("width: round(1.5px, 1px)")); + } +} +const hexNumbers = Array.from(Array(256).keys(), n => n.toString(16).padStart(2, "0")); +class Util { + static makeHexColor(r, g, b) { + return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`; + } + static scaleMinMax(transform, minMax) { + let temp; + if (transform[0]) { + if (transform[0] < 0) { + temp = minMax[0]; + minMax[0] = minMax[2]; + minMax[2] = temp; + } + minMax[0] *= transform[0]; + minMax[2] *= transform[0]; + if (transform[3] < 0) { + temp = minMax[1]; + minMax[1] = minMax[3]; + minMax[3] = temp; + } + minMax[1] *= transform[3]; + minMax[3] *= transform[3]; + } else { + temp = minMax[0]; + minMax[0] = minMax[1]; + minMax[1] = temp; + temp = minMax[2]; + minMax[2] = minMax[3]; + minMax[3] = temp; + if (transform[1] < 0) { + temp = minMax[1]; + minMax[1] = minMax[3]; + minMax[3] = temp; + } + minMax[1] *= transform[1]; + minMax[3] *= transform[1]; + if (transform[2] < 0) { + temp = minMax[0]; + minMax[0] = minMax[2]; + minMax[2] = temp; + } + minMax[0] *= transform[2]; + minMax[2] *= transform[2]; + } + minMax[0] += transform[4]; + minMax[1] += transform[5]; + minMax[2] += transform[4]; + minMax[3] += transform[5]; + } + static transform(m1, m2) { + return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]]; + } + static applyTransform(p, m) { + const xt = p[0] * m[0] + p[1] * m[2] + m[4]; + const yt = p[0] * m[1] + p[1] * m[3] + m[5]; + return [xt, yt]; + } + static applyInverseTransform(p, m) { + const d = m[0] * m[3] - m[1] * m[2]; + const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d; + const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d; + return [xt, yt]; + } + static getAxialAlignedBoundingBox(r, m) { + const p1 = this.applyTransform(r, m); + const p2 = this.applyTransform(r.slice(2, 4), m); + const p3 = this.applyTransform([r[0], r[3]], m); + const p4 = this.applyTransform([r[2], r[1]], m); + return [Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1])]; + } + static inverseTransform(m) { + const d = m[0] * m[3] - m[1] * m[2]; + return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d]; + } + static singularValueDecompose2dScale(m) { + const transpose = [m[0], m[2], m[1], m[3]]; + const a = m[0] * transpose[0] + m[1] * transpose[2]; + const b = m[0] * transpose[1] + m[1] * transpose[3]; + const c = m[2] * transpose[0] + m[3] * transpose[2]; + const d = m[2] * transpose[1] + m[3] * transpose[3]; + const first = (a + d) / 2; + const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2; + const sx = first + second || 1; + const sy = first - second || 1; + return [Math.sqrt(sx), Math.sqrt(sy)]; + } + static normalizeRect(rect) { + const r = rect.slice(0); + if (rect[0] > rect[2]) { + r[0] = rect[2]; + r[2] = rect[0]; + } + if (rect[1] > rect[3]) { + r[1] = rect[3]; + r[3] = rect[1]; + } + return r; + } + static intersect(rect1, rect2) { + const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2])); + const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2])); + if (xLow > xHigh) { + return null; + } + const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3])); + const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3])); + if (yLow > yHigh) { + return null; + } + return [xLow, yLow, xHigh, yHigh]; + } + static #getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, t, minMax) { + if (t <= 0 || t >= 1) { + return; + } + const mt = 1 - t; + const tt = t * t; + const ttt = tt * t; + const x = mt * (mt * (mt * x0 + 3 * t * x1) + 3 * tt * x2) + ttt * x3; + const y = mt * (mt * (mt * y0 + 3 * t * y1) + 3 * tt * y2) + ttt * y3; + minMax[0] = Math.min(minMax[0], x); + minMax[1] = Math.min(minMax[1], y); + minMax[2] = Math.max(minMax[2], x); + minMax[3] = Math.max(minMax[3], y); + } + static #getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, a, b, c, minMax) { + if (Math.abs(a) < 1e-12) { + if (Math.abs(b) >= 1e-12) { + this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, -c / b, minMax); + } + return; + } + const delta = b ** 2 - 4 * c * a; + if (delta < 0) { + return; + } + const sqrtDelta = Math.sqrt(delta); + const a2 = 2 * a; + this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b + sqrtDelta) / a2, minMax); + this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b - sqrtDelta) / a2, minMax); + } + static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax) { + if (minMax) { + minMax[0] = Math.min(minMax[0], x0, x3); + minMax[1] = Math.min(minMax[1], y0, y3); + minMax[2] = Math.max(minMax[2], x0, x3); + minMax[3] = Math.max(minMax[3], y0, y3); + } else { + minMax = [Math.min(x0, x3), Math.min(y0, y3), Math.max(x0, x3), Math.max(y0, y3)]; + } + this.#getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, 3 * (-x0 + 3 * (x1 - x2) + x3), 6 * (x0 - 2 * x1 + x2), 3 * (x1 - x0), minMax); + this.#getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, 3 * (-y0 + 3 * (y1 - y2) + y3), 6 * (y0 - 2 * y1 + y2), 3 * (y1 - y0), minMax); + return minMax; + } +} +const PDFStringTranslateTable = (/* unused pure expression or super */ null && ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2d8, 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d, 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac])); +function stringToPDFString(str) { + if (str[0] >= "\xEF") { + let encoding; + if (str[0] === "\xFE" && str[1] === "\xFF") { + encoding = "utf-16be"; + if (str.length % 2 === 1) { + str = str.slice(0, -1); + } + } else if (str[0] === "\xFF" && str[1] === "\xFE") { + encoding = "utf-16le"; + if (str.length % 2 === 1) { + str = str.slice(0, -1); + } + } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") { + encoding = "utf-8"; + } + if (encoding) { + try { + const decoder = new TextDecoder(encoding, { + fatal: true + }); + const buffer = stringToBytes(str); + const decoded = decoder.decode(buffer); + if (!decoded.includes("\x1b")) { + return decoded; + } + return decoded.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g, ""); + } catch (ex) { + warn(`stringToPDFString: "${ex}".`); + } + } + } + const strBuf = []; + for (let i = 0, ii = str.length; i < ii; i++) { + const charCode = str.charCodeAt(i); + if (charCode === 0x1b) { + while (++i < ii && str.charCodeAt(i) !== 0x1b) {} + continue; + } + const code = PDFStringTranslateTable[charCode]; + strBuf.push(code ? String.fromCharCode(code) : str.charAt(i)); + } + return strBuf.join(""); +} +function stringToUTF8String(str) { + return decodeURIComponent(escape(str)); +} +function utf8StringToString(str) { + return unescape(encodeURIComponent(str)); +} +function isArrayEqual(arr1, arr2) { + if (arr1.length !== arr2.length) { + return false; + } + for (let i = 0, ii = arr1.length; i < ii; i++) { + if (arr1[i] !== arr2[i]) { + return false; + } + } + return true; +} +function getModificationDate(date = new Date()) { + const buffer = [date.getUTCFullYear().toString(), (date.getUTCMonth() + 1).toString().padStart(2, "0"), date.getUTCDate().toString().padStart(2, "0"), date.getUTCHours().toString().padStart(2, "0"), date.getUTCMinutes().toString().padStart(2, "0"), date.getUTCSeconds().toString().padStart(2, "0")]; + return buffer.join(""); +} +let NormalizeRegex = null; +let NormalizationMap = null; +function normalizeUnicode(str) { + if (!NormalizeRegex) { + NormalizeRegex = /([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu; + NormalizationMap = new Map([["ſt", "ſt"]]); + } + return str.replaceAll(NormalizeRegex, (_, p1, p2) => p1 ? p1.normalize("NFKC") : NormalizationMap.get(p2)); +} +function getUuid() { + if (typeof crypto.randomUUID === "function") { + return crypto.randomUUID(); + } + const buf = new Uint8Array(32); + crypto.getRandomValues(buf); + return bytesToString(buf); +} +const AnnotationPrefix = "pdfjs_internal_id_"; +const FontRenderOps = { + BEZIER_CURVE_TO: 0, + MOVE_TO: 1, + LINE_TO: 2, + QUADRATIC_CURVE_TO: 3, + RESTORE: 4, + SAVE: 5, + SCALE: 6, + TRANSFORM: 7, + TRANSLATE: 8 +}; +function toHexUtil(arr) { + if (Uint8Array.prototype.toHex) { + return arr.toHex(); + } + return Array.from(arr, num => hexNumbers[num]).join(""); +} +function toBase64Util(arr) { + if (Uint8Array.prototype.toBase64) { + return arr.toBase64(); + } + return btoa(bytesToString(arr)); +} +function fromBase64Util(str) { + if (Uint8Array.fromBase64) { + return Uint8Array.fromBase64(str); + } + return stringToBytes(atob(str)); +} +if (typeof Promise.try !== "function") { + Promise.try = function (fn, ...args) { + return new Promise(resolve => { + resolve(fn(...args)); + }); + }; +} + +;// ./src/display/display_utils.js + +const SVG_NS = "http://www.w3.org/2000/svg"; +class PixelsPerInch { + static CSS = 96.0; + static PDF = 72.0; + static PDF_TO_CSS_UNITS = this.CSS / this.PDF; +} +async function fetchData(url, type = "text") { + if (isValidFetchUrl(url, document.baseURI)) { + const response = await fetch(url); + if (!response.ok) { + throw new Error(response.statusText); + } + switch (type) { + case "arraybuffer": + return response.arrayBuffer(); + case "blob": + return response.blob(); + case "json": + return response.json(); + } + return response.text(); + } + return new Promise((resolve, reject) => { + const request = new XMLHttpRequest(); + request.open("GET", url, true); + request.responseType = type; + request.onreadystatechange = () => { + if (request.readyState !== XMLHttpRequest.DONE) { + return; + } + if (request.status === 200 || request.status === 0) { + switch (type) { + case "arraybuffer": + case "blob": + case "json": + resolve(request.response); + return; + } + resolve(request.responseText); + return; + } + reject(new Error(request.statusText)); + }; + request.send(null); + }); +} +class PageViewport { + constructor({ + viewBox, + scale, + rotation, + offsetX = 0, + offsetY = 0, + dontFlip = false + }) { + this.viewBox = viewBox; + this.scale = scale; + this.rotation = rotation; + this.offsetX = offsetX; + this.offsetY = offsetY; + const centerX = (viewBox[2] + viewBox[0]) / 2; + const centerY = (viewBox[3] + viewBox[1]) / 2; + let rotateA, rotateB, rotateC, rotateD; + rotation %= 360; + if (rotation < 0) { + rotation += 360; + } + switch (rotation) { + case 180: + rotateA = -1; + rotateB = 0; + rotateC = 0; + rotateD = 1; + break; + case 90: + rotateA = 0; + rotateB = 1; + rotateC = 1; + rotateD = 0; + break; + case 270: + rotateA = 0; + rotateB = -1; + rotateC = -1; + rotateD = 0; + break; + case 0: + rotateA = 1; + rotateB = 0; + rotateC = 0; + rotateD = -1; + break; + default: + throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees."); + } + if (dontFlip) { + rotateC = -rotateC; + rotateD = -rotateD; + } + let offsetCanvasX, offsetCanvasY; + let width, height; + if (rotateA === 0) { + offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; + offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; + width = (viewBox[3] - viewBox[1]) * scale; + height = (viewBox[2] - viewBox[0]) * scale; + } else { + offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX; + offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY; + width = (viewBox[2] - viewBox[0]) * scale; + height = (viewBox[3] - viewBox[1]) * scale; + } + this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY]; + this.width = width; + this.height = height; + } + get rawDims() { + const { + viewBox + } = this; + return shadow(this, "rawDims", { + pageWidth: viewBox[2] - viewBox[0], + pageHeight: viewBox[3] - viewBox[1], + pageX: viewBox[0], + pageY: viewBox[1] + }); + } + clone({ + scale = this.scale, + rotation = this.rotation, + offsetX = this.offsetX, + offsetY = this.offsetY, + dontFlip = false + } = {}) { + return new PageViewport({ + viewBox: this.viewBox.slice(), + scale, + rotation, + offsetX, + offsetY, + dontFlip + }); + } + convertToViewportPoint(x, y) { + return Util.applyTransform([x, y], this.transform); + } + convertToViewportRectangle(rect) { + const topLeft = Util.applyTransform([rect[0], rect[1]], this.transform); + const bottomRight = Util.applyTransform([rect[2], rect[3]], this.transform); + return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]]; + } + convertToPdfPoint(x, y) { + return Util.applyInverseTransform([x, y], this.transform); + } +} +class RenderingCancelledException extends BaseException { + constructor(msg, extraDelay = 0) { + super(msg, "RenderingCancelledException"); + this.extraDelay = extraDelay; + } +} +function isDataScheme(url) { + const ii = url.length; + let i = 0; + while (i < ii && url[i].trim() === "") { + i++; + } + return url.substring(i, i + 5).toLowerCase() === "data:"; +} +function isPdfFile(filename) { + return typeof filename === "string" && /\.pdf$/i.test(filename); +} +function getFilenameFromUrl(url) { + [url] = url.split(/[#?]/, 1); + return url.substring(url.lastIndexOf("/") + 1); +} +function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") { + if (typeof url !== "string") { + return defaultFilename; + } + if (isDataScheme(url)) { + warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'); + return defaultFilename; + } + const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/; + const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i; + const splitURI = reURI.exec(url); + let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]); + if (suggestedFilename) { + suggestedFilename = suggestedFilename[0]; + if (suggestedFilename.includes("%")) { + try { + suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0]; + } catch {} + } + } + return suggestedFilename || defaultFilename; +} +class StatTimer { + started = Object.create(null); + times = []; + time(name) { + if (name in this.started) { + warn(`Timer is already running for ${name}`); + } + this.started[name] = Date.now(); + } + timeEnd(name) { + if (!(name in this.started)) { + warn(`Timer has not been started for ${name}`); + } + this.times.push({ + name, + start: this.started[name], + end: Date.now() + }); + delete this.started[name]; + } + toString() { + const outBuf = []; + let longest = 0; + for (const { + name + } of this.times) { + longest = Math.max(name.length, longest); + } + for (const { + name, + start, + end + } of this.times) { + outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`); + } + return outBuf.join(""); + } +} +function isValidFetchUrl(url, baseUrl) { + try { + const { + protocol + } = baseUrl ? new URL(url, baseUrl) : new URL(url); + return protocol === "http:" || protocol === "https:"; + } catch { + return false; + } +} +function noContextMenu(e) { + e.preventDefault(); +} +function stopEvent(e) { + e.preventDefault(); + e.stopPropagation(); +} +function deprecated(details) { + console.log("Deprecated API usage: " + details); +} +class PDFDateString { + static #regex; + static toDateObject(input) { + if (!input || typeof input !== "string") { + return null; + } + this.#regex ||= new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?"); + const matches = this.#regex.exec(input); + if (!matches) { + return null; + } + const year = parseInt(matches[1], 10); + let month = parseInt(matches[2], 10); + month = month >= 1 && month <= 12 ? month - 1 : 0; + let day = parseInt(matches[3], 10); + day = day >= 1 && day <= 31 ? day : 1; + let hour = parseInt(matches[4], 10); + hour = hour >= 0 && hour <= 23 ? hour : 0; + let minute = parseInt(matches[5], 10); + minute = minute >= 0 && minute <= 59 ? minute : 0; + let second = parseInt(matches[6], 10); + second = second >= 0 && second <= 59 ? second : 0; + const universalTimeRelation = matches[7] || "Z"; + let offsetHour = parseInt(matches[8], 10); + offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0; + let offsetMinute = parseInt(matches[9], 10) || 0; + offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0; + if (universalTimeRelation === "-") { + hour += offsetHour; + minute += offsetMinute; + } else if (universalTimeRelation === "+") { + hour -= offsetHour; + minute -= offsetMinute; + } + return new Date(Date.UTC(year, month, day, hour, minute, second)); + } +} +function getXfaPageViewport(xfaPage, { + scale = 1, + rotation = 0 +}) { + const { + width, + height + } = xfaPage.attributes.style; + const viewBox = [0, 0, parseInt(width), parseInt(height)]; + return new PageViewport({ + viewBox, + scale, + rotation + }); +} +function getRGB(color) { + if (color.startsWith("#")) { + const colorRGB = parseInt(color.slice(1), 16); + return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff]; + } + if (color.startsWith("rgb(")) { + return color.slice(4, -1).split(",").map(x => parseInt(x)); + } + if (color.startsWith("rgba(")) { + return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3); + } + warn(`Not a valid color format: "${color}"`); + return [0, 0, 0]; +} +function getColorValues(colors) { + const span = document.createElement("span"); + span.style.visibility = "hidden"; + document.body.append(span); + for (const name of colors.keys()) { + span.style.color = name; + const computedColor = window.getComputedStyle(span).color; + colors.set(name, getRGB(computedColor)); + } + span.remove(); +} +function getCurrentTransform(ctx) { + const { + a, + b, + c, + d, + e, + f + } = ctx.getTransform(); + return [a, b, c, d, e, f]; +} +function getCurrentTransformInverse(ctx) { + const { + a, + b, + c, + d, + e, + f + } = ctx.getTransform().invertSelf(); + return [a, b, c, d, e, f]; +} +function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) { + if (viewport instanceof PageViewport) { + const { + pageWidth, + pageHeight + } = viewport.rawDims; + const { + style + } = div; + const useRound = util_FeatureTest.isCSSRoundSupported; + const w = `var(--scale-factor) * ${pageWidth}px`, + h = `var(--scale-factor) * ${pageHeight}px`; + const widthStr = useRound ? `round(down, ${w}, var(--scale-round-x, 1px))` : `calc(${w})`, + heightStr = useRound ? `round(down, ${h}, var(--scale-round-y, 1px))` : `calc(${h})`; + if (!mustFlip || viewport.rotation % 180 === 0) { + style.width = widthStr; + style.height = heightStr; + } else { + style.width = heightStr; + style.height = widthStr; + } + } + if (mustRotate) { + div.setAttribute("data-main-rotation", viewport.rotation); + } +} +class OutputScale { + constructor() { + const pixelRatio = window.devicePixelRatio || 1; + this.sx = pixelRatio; + this.sy = pixelRatio; + } + get scaled() { + return this.sx !== 1 || this.sy !== 1; + } + get symmetric() { + return this.sx === this.sy; + } +} + +;// ./src/display/editor/toolbar.js + +class EditorToolbar { + #toolbar = null; + #colorPicker = null; + #editor; + #buttons = null; + #altText = null; + static #l10nRemove = null; + constructor(editor) { + this.#editor = editor; + EditorToolbar.#l10nRemove ||= Object.freeze({ + freetext: "pdfjs-editor-remove-freetext-button", + highlight: "pdfjs-editor-remove-highlight-button", + ink: "pdfjs-editor-remove-ink-button", + stamp: "pdfjs-editor-remove-stamp-button" + }); + } + render() { + const editToolbar = this.#toolbar = document.createElement("div"); + editToolbar.classList.add("editToolbar", "hidden"); + editToolbar.setAttribute("role", "toolbar"); + const signal = this.#editor._uiManager._signal; + editToolbar.addEventListener("contextmenu", noContextMenu, { + signal + }); + editToolbar.addEventListener("pointerdown", EditorToolbar.#pointerDown, { + signal + }); + const buttons = this.#buttons = document.createElement("div"); + buttons.className = "buttons"; + editToolbar.append(buttons); + const position = this.#editor.toolbarPosition; + if (position) { + const { + style + } = editToolbar; + const x = this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0]; + style.insetInlineEnd = `${100 * x}%`; + style.top = `calc(${100 * position[1]}% + var(--editor-toolbar-vert-offset))`; + } + this.#addDeleteButton(); + return editToolbar; + } + get div() { + return this.#toolbar; + } + static #pointerDown(e) { + e.stopPropagation(); + } + #focusIn(e) { + this.#editor._focusEventsAllowed = false; + stopEvent(e); + } + #focusOut(e) { + this.#editor._focusEventsAllowed = true; + stopEvent(e); + } + #addListenersToElement(element) { + const signal = this.#editor._uiManager._signal; + element.addEventListener("focusin", this.#focusIn.bind(this), { + capture: true, + signal + }); + element.addEventListener("focusout", this.#focusOut.bind(this), { + capture: true, + signal + }); + element.addEventListener("contextmenu", noContextMenu, { + signal + }); + } + hide() { + this.#toolbar.classList.add("hidden"); + this.#colorPicker?.hideDropdown(); + } + show() { + this.#toolbar.classList.remove("hidden"); + this.#altText?.shown(); + } + #addDeleteButton() { + const { + editorType, + _uiManager + } = this.#editor; + const button = document.createElement("button"); + button.className = "delete"; + button.tabIndex = 0; + button.setAttribute("data-l10n-id", EditorToolbar.#l10nRemove[editorType]); + this.#addListenersToElement(button); + button.addEventListener("click", e => { + _uiManager.delete(); + }, { + signal: _uiManager._signal + }); + this.#buttons.append(button); + } + get #divider() { + const divider = document.createElement("div"); + divider.className = "divider"; + return divider; + } + async addAltText(altText) { + const button = await altText.render(); + this.#addListenersToElement(button); + this.#buttons.prepend(button, this.#divider); + this.#altText = altText; + } + addColorPicker(colorPicker) { + this.#colorPicker = colorPicker; + const button = colorPicker.renderButton(); + this.#addListenersToElement(button); + this.#buttons.prepend(button, this.#divider); + } + remove() { + this.#toolbar.remove(); + this.#colorPicker?.destroy(); + this.#colorPicker = null; + } +} +class HighlightToolbar { + #buttons = null; + #toolbar = null; + #uiManager; + constructor(uiManager) { + this.#uiManager = uiManager; + } + #render() { + const editToolbar = this.#toolbar = document.createElement("div"); + editToolbar.className = "editToolbar"; + editToolbar.setAttribute("role", "toolbar"); + editToolbar.addEventListener("contextmenu", noContextMenu, { + signal: this.#uiManager._signal + }); + const buttons = this.#buttons = document.createElement("div"); + buttons.className = "buttons"; + editToolbar.append(buttons); + this.#addHighlightButton(); + return editToolbar; + } + #getLastPoint(boxes, isLTR) { + let lastY = 0; + let lastX = 0; + for (const box of boxes) { + const y = box.y + box.height; + if (y < lastY) { + continue; + } + const x = box.x + (isLTR ? box.width : 0); + if (y > lastY) { + lastX = x; + lastY = y; + continue; + } + if (isLTR) { + if (x > lastX) { + lastX = x; + } + } else if (x < lastX) { + lastX = x; + } + } + return [isLTR ? 1 - lastX : lastX, lastY]; + } + show(parent, boxes, isLTR) { + const [x, y] = this.#getLastPoint(boxes, isLTR); + const { + style + } = this.#toolbar ||= this.#render(); + parent.append(this.#toolbar); + style.insetInlineEnd = `${100 * x}%`; + style.top = `calc(${100 * y}% + var(--editor-toolbar-vert-offset))`; + } + hide() { + this.#toolbar.remove(); + } + #addHighlightButton() { + const button = document.createElement("button"); + button.className = "highlightButton"; + button.tabIndex = 0; + button.setAttribute("data-l10n-id", `pdfjs-highlight-floating-button1`); + const span = document.createElement("span"); + button.append(span); + span.className = "visuallyHidden"; + span.setAttribute("data-l10n-id", "pdfjs-highlight-floating-button-label"); + const signal = this.#uiManager._signal; + button.addEventListener("contextmenu", noContextMenu, { + signal + }); + button.addEventListener("click", () => { + this.#uiManager.highlightSelection("floating_button"); + }, { + signal + }); + this.#buttons.append(button); + } +} + +;// ./src/display/editor/tools.js + + + +function bindEvents(obj, element, names) { + for (const name of names) { + element.addEventListener(name, obj[name].bind(obj)); + } +} +function opacityToHex(opacity) { + return Math.round(Math.min(255, Math.max(1, 255 * opacity))).toString(16).padStart(2, "0"); +} +class IdManager { + #id = 0; + get id() { + return `${AnnotationEditorPrefix}${this.#id++}`; + } +} +class ImageManager { + #baseId = getUuid(); + #id = 0; + #cache = null; + static get _isSVGFittingCanvas() { + const svg = `data:image/svg+xml;charset=UTF-8,`; + const canvas = new OffscreenCanvas(1, 3); + const ctx = canvas.getContext("2d", { + willReadFrequently: true + }); + const image = new Image(); + image.src = svg; + const promise = image.decode().then(() => { + ctx.drawImage(image, 0, 0, 1, 1, 0, 0, 1, 3); + return new Uint32Array(ctx.getImageData(0, 0, 1, 1).data.buffer)[0] === 0; + }); + return shadow(this, "_isSVGFittingCanvas", promise); + } + async #get(key, rawData) { + this.#cache ||= new Map(); + let data = this.#cache.get(key); + if (data === null) { + return null; + } + if (data?.bitmap) { + data.refCounter += 1; + return data; + } + try { + data ||= { + bitmap: null, + id: `image_${this.#baseId}_${this.#id++}`, + refCounter: 0, + isSvg: false + }; + let image; + if (typeof rawData === "string") { + data.url = rawData; + image = await fetchData(rawData, "blob"); + } else if (rawData instanceof File) { + image = data.file = rawData; + } else if (rawData instanceof Blob) { + image = rawData; + } + if (image.type === "image/svg+xml") { + const mustRemoveAspectRatioPromise = ImageManager._isSVGFittingCanvas; + const fileReader = new FileReader(); + const imageElement = new Image(); + const imagePromise = new Promise((resolve, reject) => { + imageElement.onload = () => { + data.bitmap = imageElement; + data.isSvg = true; + resolve(); + }; + fileReader.onload = async () => { + const url = data.svgUrl = fileReader.result; + imageElement.src = (await mustRemoveAspectRatioPromise) ? `${url}#svgView(preserveAspectRatio(none))` : url; + }; + imageElement.onerror = fileReader.onerror = reject; + }); + fileReader.readAsDataURL(image); + await imagePromise; + } else { + data.bitmap = await createImageBitmap(image); + } + data.refCounter = 1; + } catch (e) { + warn(e); + data = null; + } + this.#cache.set(key, data); + if (data) { + this.#cache.set(data.id, data); + } + return data; + } + async getFromFile(file) { + const { + lastModified, + name, + size, + type + } = file; + return this.#get(`${lastModified}_${name}_${size}_${type}`, file); + } + async getFromUrl(url) { + return this.#get(url, url); + } + async getFromBlob(id, blobPromise) { + const blob = await blobPromise; + return this.#get(id, blob); + } + async getFromId(id) { + this.#cache ||= new Map(); + const data = this.#cache.get(id); + if (!data) { + return null; + } + if (data.bitmap) { + data.refCounter += 1; + return data; + } + if (data.file) { + return this.getFromFile(data.file); + } + if (data.blobPromise) { + const { + blobPromise + } = data; + delete data.blobPromise; + return this.getFromBlob(data.id, blobPromise); + } + return this.getFromUrl(data.url); + } + getFromCanvas(id, canvas) { + this.#cache ||= new Map(); + let data = this.#cache.get(id); + if (data?.bitmap) { + data.refCounter += 1; + return data; + } + const offscreen = new OffscreenCanvas(canvas.width, canvas.height); + const ctx = offscreen.getContext("2d"); + ctx.drawImage(canvas, 0, 0); + data = { + bitmap: offscreen.transferToImageBitmap(), + id: `image_${this.#baseId}_${this.#id++}`, + refCounter: 1, + isSvg: false + }; + this.#cache.set(id, data); + this.#cache.set(data.id, data); + return data; + } + getSvgUrl(id) { + const data = this.#cache.get(id); + if (!data?.isSvg) { + return null; + } + return data.svgUrl; + } + deleteId(id) { + this.#cache ||= new Map(); + const data = this.#cache.get(id); + if (!data) { + return; + } + data.refCounter -= 1; + if (data.refCounter !== 0) { + return; + } + const { + bitmap + } = data; + if (!data.url && !data.file) { + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); + const ctx = canvas.getContext("bitmaprenderer"); + ctx.transferFromImageBitmap(bitmap); + data.blobPromise = canvas.convertToBlob(); + } + bitmap.close?.(); + data.bitmap = null; + } + isValidId(id) { + return id.startsWith(`image_${this.#baseId}_`); + } +} +class CommandManager { + #commands = []; + #locked = false; + #maxSize; + #position = -1; + constructor(maxSize = 128) { + this.#maxSize = maxSize; + } + add({ + cmd, + undo, + post, + mustExec, + type = NaN, + overwriteIfSameType = false, + keepUndo = false + }) { + if (mustExec) { + cmd(); + } + if (this.#locked) { + return; + } + const save = { + cmd, + undo, + post, + type + }; + if (this.#position === -1) { + if (this.#commands.length > 0) { + this.#commands.length = 0; + } + this.#position = 0; + this.#commands.push(save); + return; + } + if (overwriteIfSameType && this.#commands[this.#position].type === type) { + if (keepUndo) { + save.undo = this.#commands[this.#position].undo; + } + this.#commands[this.#position] = save; + return; + } + const next = this.#position + 1; + if (next === this.#maxSize) { + this.#commands.splice(0, 1); + } else { + this.#position = next; + if (next < this.#commands.length) { + this.#commands.splice(next); + } + } + this.#commands.push(save); + } + undo() { + if (this.#position === -1) { + return; + } + this.#locked = true; + const { + undo, + post + } = this.#commands[this.#position]; + undo(); + post?.(); + this.#locked = false; + this.#position -= 1; + } + redo() { + if (this.#position < this.#commands.length - 1) { + this.#position += 1; + this.#locked = true; + const { + cmd, + post + } = this.#commands[this.#position]; + cmd(); + post?.(); + this.#locked = false; + } + } + hasSomethingToUndo() { + return this.#position !== -1; + } + hasSomethingToRedo() { + return this.#position < this.#commands.length - 1; + } + cleanType(type) { + if (this.#position === -1) { + return; + } + for (let i = this.#position; i >= 0; i--) { + if (this.#commands[i].type !== type) { + this.#commands.splice(i + 1, this.#position - i); + this.#position = i; + return; + } + } + this.#commands.length = 0; + this.#position = -1; + } + destroy() { + this.#commands = null; + } +} +class KeyboardManager { + constructor(callbacks) { + this.buffer = []; + this.callbacks = new Map(); + this.allKeys = new Set(); + const { + isMac + } = util_FeatureTest.platform; + for (const [keys, callback, options = {}] of callbacks) { + for (const key of keys) { + const isMacKey = key.startsWith("mac+"); + if (isMac && isMacKey) { + this.callbacks.set(key.slice(4), { + callback, + options + }); + this.allKeys.add(key.split("+").at(-1)); + } else if (!isMac && !isMacKey) { + this.callbacks.set(key, { + callback, + options + }); + this.allKeys.add(key.split("+").at(-1)); + } + } + } + } + #serialize(event) { + if (event.altKey) { + this.buffer.push("alt"); + } + if (event.ctrlKey) { + this.buffer.push("ctrl"); + } + if (event.metaKey) { + this.buffer.push("meta"); + } + if (event.shiftKey) { + this.buffer.push("shift"); + } + this.buffer.push(event.key); + const str = this.buffer.join("+"); + this.buffer.length = 0; + return str; + } + exec(self, event) { + if (!this.allKeys.has(event.key)) { + return; + } + const info = this.callbacks.get(this.#serialize(event)); + if (!info) { + return; + } + const { + callback, + options: { + bubbles = false, + args = [], + checker = null + } + } = info; + if (checker && !checker(self, event)) { + return; + } + callback.bind(self, ...args, event)(); + if (!bubbles) { + stopEvent(event); + } + } +} +class ColorManager { + static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]); + get _colors() { + const colors = new Map([["CanvasText", null], ["Canvas", null]]); + getColorValues(colors); + return shadow(this, "_colors", colors); + } + convert(color) { + const rgb = getRGB(color); + if (!window.matchMedia("(forced-colors: active)").matches) { + return rgb; + } + for (const [name, RGB] of this._colors) { + if (RGB.every((x, i) => x === rgb[i])) { + return ColorManager._colorsMapping.get(name); + } + } + return rgb; + } + getHexCode(name) { + const rgb = this._colors.get(name); + if (!rgb) { + return name; + } + return Util.makeHexColor(...rgb); + } +} +class AnnotationEditorUIManager { + #abortController = new AbortController(); + #activeEditor = null; + #allEditors = new Map(); + #allLayers = new Map(); + #altTextManager = null; + #annotationStorage = null; + #changedExistingAnnotations = null; + #commandManager = new CommandManager(); + #copyPasteAC = null; + #currentDrawingSession = null; + #currentPageIndex = 0; + #deletedAnnotationsElementIds = new Set(); + #draggingEditors = null; + #editorTypes = null; + #editorsToRescale = new Set(); + _editorUndoBar = null; + #enableHighlightFloatingButton = false; + #enableUpdatedAddImage = false; + #enableNewAltTextWhenAddingImage = false; + #filterFactory = null; + #focusMainContainerTimeoutId = null; + #focusManagerAC = null; + #highlightColors = null; + #highlightWhenShiftUp = false; + #highlightToolbar = null; + #idManager = new IdManager(); + #isEnabled = false; + #isWaiting = false; + #keyboardManagerAC = null; + #lastActiveElement = null; + #mainHighlightColorPicker = null; + #mlManager = null; + #mode = AnnotationEditorType.NONE; + #selectedEditors = new Set(); + #selectedTextNode = null; + #pageColors = null; + #showAllStates = null; + #previousStates = { + isEditing: false, + isEmpty: true, + hasSomethingToUndo: false, + hasSomethingToRedo: false, + hasSelectedEditor: false, + hasSelectedText: false + }; + #translation = [0, 0]; + #translationTimeoutId = null; + #container = null; + #viewer = null; + #updateModeCapability = null; + static TRANSLATE_SMALL = 1; + static TRANSLATE_BIG = 10; + static get _keyboardManager() { + const proto = AnnotationEditorUIManager.prototype; + const arrowChecker = self => self.#container.contains(document.activeElement) && document.activeElement.tagName !== "BUTTON" && self.hasSomethingToControl(); + const textInputChecker = (_self, { + target: el + }) => { + if (el instanceof HTMLInputElement) { + const { + type + } = el; + return type !== "text" && type !== "number"; + } + return true; + }; + const small = this.TRANSLATE_SMALL; + const big = this.TRANSLATE_BIG; + return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+a", "mac+meta+a"], proto.selectAll, { + checker: textInputChecker + }], [["ctrl+z", "mac+meta+z"], proto.undo, { + checker: textInputChecker + }], [["ctrl+y", "ctrl+shift+z", "mac+meta+shift+z", "ctrl+shift+Z", "mac+meta+shift+Z"], proto.redo, { + checker: textInputChecker + }], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete", "mac+Delete"], proto.delete, { + checker: textInputChecker + }], [["Enter", "mac+Enter"], proto.addNewEditorFromKeyboard, { + checker: (self, { + target: el + }) => !(el instanceof HTMLButtonElement) && self.#container.contains(el) && !self.isEnterHandled + }], [[" ", "mac+ "], proto.addNewEditorFromKeyboard, { + checker: (self, { + target: el + }) => !(el instanceof HTMLButtonElement) && self.#container.contains(document.activeElement) + }], [["Escape", "mac+Escape"], proto.unselectAll], [["ArrowLeft", "mac+ArrowLeft"], proto.translateSelectedEditors, { + args: [-small, 0], + checker: arrowChecker + }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto.translateSelectedEditors, { + args: [-big, 0], + checker: arrowChecker + }], [["ArrowRight", "mac+ArrowRight"], proto.translateSelectedEditors, { + args: [small, 0], + checker: arrowChecker + }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto.translateSelectedEditors, { + args: [big, 0], + checker: arrowChecker + }], [["ArrowUp", "mac+ArrowUp"], proto.translateSelectedEditors, { + args: [0, -small], + checker: arrowChecker + }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto.translateSelectedEditors, { + args: [0, -big], + checker: arrowChecker + }], [["ArrowDown", "mac+ArrowDown"], proto.translateSelectedEditors, { + args: [0, small], + checker: arrowChecker + }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto.translateSelectedEditors, { + args: [0, big], + checker: arrowChecker + }]])); + } + constructor(container, viewer, altTextManager, eventBus, pdfDocument, pageColors, highlightColors, enableHighlightFloatingButton, enableUpdatedAddImage, enableNewAltTextWhenAddingImage, mlManager, editorUndoBar) { + const signal = this._signal = this.#abortController.signal; + this.#container = container; + this.#viewer = viewer; + this.#altTextManager = altTextManager; + this._eventBus = eventBus; + eventBus._on("editingaction", this.onEditingAction.bind(this), { + signal + }); + eventBus._on("pagechanging", this.onPageChanging.bind(this), { + signal + }); + eventBus._on("scalechanging", this.onScaleChanging.bind(this), { + signal + }); + eventBus._on("rotationchanging", this.onRotationChanging.bind(this), { + signal + }); + eventBus._on("setpreference", this.onSetPreference.bind(this), { + signal + }); + eventBus._on("switchannotationeditorparams", evt => this.updateParams(evt.type, evt.value), { + signal + }); + this.#addSelectionListener(); + this.#addDragAndDropListeners(); + this.#addKeyboardManager(); + this.#annotationStorage = pdfDocument.annotationStorage; + this.#filterFactory = pdfDocument.filterFactory; + this.#pageColors = pageColors; + this.#highlightColors = highlightColors || null; + this.#enableHighlightFloatingButton = enableHighlightFloatingButton; + this.#enableUpdatedAddImage = enableUpdatedAddImage; + this.#enableNewAltTextWhenAddingImage = enableNewAltTextWhenAddingImage; + this.#mlManager = mlManager || null; + this.viewParameters = { + realScale: PixelsPerInch.PDF_TO_CSS_UNITS, + rotation: 0 + }; + this.isShiftKeyDown = false; + this._editorUndoBar = editorUndoBar || null; + } + destroy() { + this.#updateModeCapability?.resolve(); + this.#updateModeCapability = null; + this.#abortController?.abort(); + this.#abortController = null; + this._signal = null; + for (const layer of this.#allLayers.values()) { + layer.destroy(); + } + this.#allLayers.clear(); + this.#allEditors.clear(); + this.#editorsToRescale.clear(); + this.#activeEditor = null; + this.#selectedEditors.clear(); + this.#commandManager.destroy(); + this.#altTextManager?.destroy(); + this.#highlightToolbar?.hide(); + this.#highlightToolbar = null; + if (this.#focusMainContainerTimeoutId) { + clearTimeout(this.#focusMainContainerTimeoutId); + this.#focusMainContainerTimeoutId = null; + } + if (this.#translationTimeoutId) { + clearTimeout(this.#translationTimeoutId); + this.#translationTimeoutId = null; + } + this._editorUndoBar?.destroy(); + } + combinedSignal(ac) { + return AbortSignal.any([this._signal, ac.signal]); + } + get mlManager() { + return this.#mlManager; + } + get useNewAltTextFlow() { + return this.#enableUpdatedAddImage; + } + get useNewAltTextWhenAddingImage() { + return this.#enableNewAltTextWhenAddingImage; + } + get hcmFilter() { + return shadow(this, "hcmFilter", this.#pageColors ? this.#filterFactory.addHCMFilter(this.#pageColors.foreground, this.#pageColors.background) : "none"); + } + get direction() { + return shadow(this, "direction", getComputedStyle(this.#container).direction); + } + get highlightColors() { + return shadow(this, "highlightColors", this.#highlightColors ? new Map(this.#highlightColors.split(",").map(pair => pair.split("=").map(x => x.trim()))) : null); + } + get highlightColorNames() { + return shadow(this, "highlightColorNames", this.highlightColors ? new Map(Array.from(this.highlightColors, e => e.reverse())) : null); + } + setCurrentDrawingSession(layer) { + if (layer) { + this.unselectAll(); + this.disableUserSelect(true); + } else { + this.disableUserSelect(false); + } + this.#currentDrawingSession = layer; + } + setMainHighlightColorPicker(colorPicker) { + this.#mainHighlightColorPicker = colorPicker; + } + editAltText(editor, firstTime = false) { + this.#altTextManager?.editAltText(this, editor, firstTime); + } + switchToMode(mode, callback) { + this._eventBus.on("annotationeditormodechanged", callback, { + once: true, + signal: this._signal + }); + this._eventBus.dispatch("showannotationeditorui", { + source: this, + mode + }); + } + setPreference(name, value) { + this._eventBus.dispatch("setpreference", { + source: this, + name, + value + }); + } + onSetPreference({ + name, + value + }) { + switch (name) { + case "enableNewAltTextWhenAddingImage": + this.#enableNewAltTextWhenAddingImage = value; + break; + } + } + onPageChanging({ + pageNumber + }) { + this.#currentPageIndex = pageNumber - 1; + } + focusMainContainer() { + this.#container.focus(); + } + findParent(x, y) { + for (const layer of this.#allLayers.values()) { + const { + x: layerX, + y: layerY, + width, + height + } = layer.div.getBoundingClientRect(); + if (x >= layerX && x <= layerX + width && y >= layerY && y <= layerY + height) { + return layer; + } + } + return null; + } + disableUserSelect(value = false) { + this.#viewer.classList.toggle("noUserSelect", value); + } + addShouldRescale(editor) { + this.#editorsToRescale.add(editor); + } + removeShouldRescale(editor) { + this.#editorsToRescale.delete(editor); + } + onScaleChanging({ + scale + }) { + this.commitOrRemove(); + this.viewParameters.realScale = scale * PixelsPerInch.PDF_TO_CSS_UNITS; + for (const editor of this.#editorsToRescale) { + editor.onScaleChanging(); + } + this.#currentDrawingSession?.onScaleChanging(); + } + onRotationChanging({ + pagesRotation + }) { + this.commitOrRemove(); + this.viewParameters.rotation = pagesRotation; + } + #getAnchorElementForSelection({ + anchorNode + }) { + return anchorNode.nodeType === Node.TEXT_NODE ? anchorNode.parentElement : anchorNode; + } + #getLayerForTextLayer(textLayer) { + const { + currentLayer + } = this; + if (currentLayer.hasTextLayer(textLayer)) { + return currentLayer; + } + for (const layer of this.#allLayers.values()) { + if (layer.hasTextLayer(textLayer)) { + return layer; + } + } + return null; + } + highlightSelection(methodOfCreation = "") { + const selection = document.getSelection(); + if (!selection || selection.isCollapsed) { + return; + } + const { + anchorNode, + anchorOffset, + focusNode, + focusOffset + } = selection; + const text = selection.toString(); + const anchorElement = this.#getAnchorElementForSelection(selection); + const textLayer = anchorElement.closest(".textLayer"); + const boxes = this.getSelectionBoxes(textLayer); + if (!boxes) { + return; + } + selection.empty(); + const layer = this.#getLayerForTextLayer(textLayer); + const isNoneMode = this.#mode === AnnotationEditorType.NONE; + const callback = () => { + layer?.createAndAddNewEditor({ + x: 0, + y: 0 + }, false, { + methodOfCreation, + boxes, + anchorNode, + anchorOffset, + focusNode, + focusOffset, + text + }); + if (isNoneMode) { + this.showAllEditors("highlight", true, true); + } + }; + if (isNoneMode) { + this.switchToMode(AnnotationEditorType.HIGHLIGHT, callback); + return; + } + callback(); + } + #displayHighlightToolbar() { + const selection = document.getSelection(); + if (!selection || selection.isCollapsed) { + return; + } + const anchorElement = this.#getAnchorElementForSelection(selection); + const textLayer = anchorElement.closest(".textLayer"); + const boxes = this.getSelectionBoxes(textLayer); + if (!boxes) { + return; + } + this.#highlightToolbar ||= new HighlightToolbar(this); + this.#highlightToolbar.show(textLayer, boxes, this.direction === "ltr"); + } + addToAnnotationStorage(editor) { + if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) { + this.#annotationStorage.setValue(editor.id, editor); + } + } + #selectionChange() { + const selection = document.getSelection(); + if (!selection || selection.isCollapsed) { + if (this.#selectedTextNode) { + this.#highlightToolbar?.hide(); + this.#selectedTextNode = null; + this.#dispatchUpdateStates({ + hasSelectedText: false + }); + } + return; + } + const { + anchorNode + } = selection; + if (anchorNode === this.#selectedTextNode) { + return; + } + const anchorElement = this.#getAnchorElementForSelection(selection); + const textLayer = anchorElement.closest(".textLayer"); + if (!textLayer) { + if (this.#selectedTextNode) { + this.#highlightToolbar?.hide(); + this.#selectedTextNode = null; + this.#dispatchUpdateStates({ + hasSelectedText: false + }); + } + return; + } + this.#highlightToolbar?.hide(); + this.#selectedTextNode = anchorNode; + this.#dispatchUpdateStates({ + hasSelectedText: true + }); + if (this.#mode !== AnnotationEditorType.HIGHLIGHT && this.#mode !== AnnotationEditorType.NONE) { + return; + } + if (this.#mode === AnnotationEditorType.HIGHLIGHT) { + this.showAllEditors("highlight", true, true); + } + this.#highlightWhenShiftUp = this.isShiftKeyDown; + if (!this.isShiftKeyDown) { + const activeLayer = this.#mode === AnnotationEditorType.HIGHLIGHT ? this.#getLayerForTextLayer(textLayer) : null; + activeLayer?.toggleDrawing(); + const ac = new AbortController(); + const signal = this.combinedSignal(ac); + const pointerup = e => { + if (e.type === "pointerup" && e.button !== 0) { + return; + } + ac.abort(); + activeLayer?.toggleDrawing(true); + if (e.type === "pointerup") { + this.#onSelectEnd("main_toolbar"); + } + }; + window.addEventListener("pointerup", pointerup, { + signal + }); + window.addEventListener("blur", pointerup, { + signal + }); + } + } + #onSelectEnd(methodOfCreation = "") { + if (this.#mode === AnnotationEditorType.HIGHLIGHT) { + this.highlightSelection(methodOfCreation); + } else if (this.#enableHighlightFloatingButton) { + this.#displayHighlightToolbar(); + } + } + #addSelectionListener() { + document.addEventListener("selectionchange", this.#selectionChange.bind(this), { + signal: this._signal + }); + } + #addFocusManager() { + if (this.#focusManagerAC) { + return; + } + this.#focusManagerAC = new AbortController(); + const signal = this.combinedSignal(this.#focusManagerAC); + window.addEventListener("focus", this.focus.bind(this), { + signal + }); + window.addEventListener("blur", this.blur.bind(this), { + signal + }); + } + #removeFocusManager() { + this.#focusManagerAC?.abort(); + this.#focusManagerAC = null; + } + blur() { + this.isShiftKeyDown = false; + if (this.#highlightWhenShiftUp) { + this.#highlightWhenShiftUp = false; + this.#onSelectEnd("main_toolbar"); + } + if (!this.hasSelection) { + return; + } + const { + activeElement + } = document; + for (const editor of this.#selectedEditors) { + if (editor.div.contains(activeElement)) { + this.#lastActiveElement = [editor, activeElement]; + editor._focusEventsAllowed = false; + break; + } + } + } + focus() { + if (!this.#lastActiveElement) { + return; + } + const [lastEditor, lastActiveElement] = this.#lastActiveElement; + this.#lastActiveElement = null; + lastActiveElement.addEventListener("focusin", () => { + lastEditor._focusEventsAllowed = true; + }, { + once: true, + signal: this._signal + }); + lastActiveElement.focus(); + } + #addKeyboardManager() { + if (this.#keyboardManagerAC) { + return; + } + this.#keyboardManagerAC = new AbortController(); + const signal = this.combinedSignal(this.#keyboardManagerAC); + window.addEventListener("keydown", this.keydown.bind(this), { + signal + }); + window.addEventListener("keyup", this.keyup.bind(this), { + signal + }); + } + #removeKeyboardManager() { + this.#keyboardManagerAC?.abort(); + this.#keyboardManagerAC = null; + } + #addCopyPasteListeners() { + if (this.#copyPasteAC) { + return; + } + this.#copyPasteAC = new AbortController(); + const signal = this.combinedSignal(this.#copyPasteAC); + document.addEventListener("copy", this.copy.bind(this), { + signal + }); + document.addEventListener("cut", this.cut.bind(this), { + signal + }); + document.addEventListener("paste", this.paste.bind(this), { + signal + }); + } + #removeCopyPasteListeners() { + this.#copyPasteAC?.abort(); + this.#copyPasteAC = null; + } + #addDragAndDropListeners() { + const signal = this._signal; + document.addEventListener("dragover", this.dragOver.bind(this), { + signal + }); + document.addEventListener("drop", this.drop.bind(this), { + signal + }); + } + addEditListeners() { + this.#addKeyboardManager(); + this.#addCopyPasteListeners(); + } + removeEditListeners() { + this.#removeKeyboardManager(); + this.#removeCopyPasteListeners(); + } + dragOver(event) { + for (const { + type + } of event.dataTransfer.items) { + for (const editorType of this.#editorTypes) { + if (editorType.isHandlingMimeForPasting(type)) { + event.dataTransfer.dropEffect = "copy"; + event.preventDefault(); + return; + } + } + } + } + drop(event) { + for (const item of event.dataTransfer.items) { + for (const editorType of this.#editorTypes) { + if (editorType.isHandlingMimeForPasting(item.type)) { + editorType.paste(item, this.currentLayer); + event.preventDefault(); + return; + } + } + } + } + copy(event) { + event.preventDefault(); + this.#activeEditor?.commitOrRemove(); + if (!this.hasSelection) { + return; + } + const editors = []; + for (const editor of this.#selectedEditors) { + const serialized = editor.serialize(true); + if (serialized) { + editors.push(serialized); + } + } + if (editors.length === 0) { + return; + } + event.clipboardData.setData("application/pdfjs", JSON.stringify(editors)); + } + cut(event) { + this.copy(event); + this.delete(); + } + async paste(event) { + event.preventDefault(); + const { + clipboardData + } = event; + for (const item of clipboardData.items) { + for (const editorType of this.#editorTypes) { + if (editorType.isHandlingMimeForPasting(item.type)) { + editorType.paste(item, this.currentLayer); + return; + } + } + } + let data = clipboardData.getData("application/pdfjs"); + if (!data) { + return; + } + try { + data = JSON.parse(data); + } catch (ex) { + warn(`paste: "${ex.message}".`); + return; + } + if (!Array.isArray(data)) { + return; + } + this.unselectAll(); + const layer = this.currentLayer; + try { + const newEditors = []; + for (const editor of data) { + const deserializedEditor = await layer.deserialize(editor); + if (!deserializedEditor) { + return; + } + newEditors.push(deserializedEditor); + } + const cmd = () => { + for (const editor of newEditors) { + this.#addEditorToLayer(editor); + } + this.#selectEditors(newEditors); + }; + const undo = () => { + for (const editor of newEditors) { + editor.remove(); + } + }; + this.addCommands({ + cmd, + undo, + mustExec: true + }); + } catch (ex) { + warn(`paste: "${ex.message}".`); + } + } + keydown(event) { + if (!this.isShiftKeyDown && event.key === "Shift") { + this.isShiftKeyDown = true; + } + if (this.#mode !== AnnotationEditorType.NONE && !this.isEditorHandlingKeyboard) { + AnnotationEditorUIManager._keyboardManager.exec(this, event); + } + } + keyup(event) { + if (this.isShiftKeyDown && event.key === "Shift") { + this.isShiftKeyDown = false; + if (this.#highlightWhenShiftUp) { + this.#highlightWhenShiftUp = false; + this.#onSelectEnd("main_toolbar"); + } + } + } + onEditingAction({ + name + }) { + switch (name) { + case "undo": + case "redo": + case "delete": + case "selectAll": + this[name](); + break; + case "highlightSelection": + this.highlightSelection("context_menu"); + break; + } + } + #dispatchUpdateStates(details) { + const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value); + if (hasChanged) { + this._eventBus.dispatch("annotationeditorstateschanged", { + source: this, + details: Object.assign(this.#previousStates, details) + }); + if (this.#mode === AnnotationEditorType.HIGHLIGHT && details.hasSelectedEditor === false) { + this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_FREE, true]]); + } + } + } + #dispatchUpdateUI(details) { + this._eventBus.dispatch("annotationeditorparamschanged", { + source: this, + details + }); + } + setEditingState(isEditing) { + if (isEditing) { + this.#addFocusManager(); + this.#addCopyPasteListeners(); + this.#dispatchUpdateStates({ + isEditing: this.#mode !== AnnotationEditorType.NONE, + isEmpty: this.#isEmpty(), + hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(), + hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(), + hasSelectedEditor: false + }); + } else { + this.#removeFocusManager(); + this.#removeCopyPasteListeners(); + this.#dispatchUpdateStates({ + isEditing: false + }); + this.disableUserSelect(false); + } + } + registerEditorTypes(types) { + if (this.#editorTypes) { + return; + } + this.#editorTypes = types; + for (const editorType of this.#editorTypes) { + this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate); + } + } + getId() { + return this.#idManager.id; + } + get currentLayer() { + return this.#allLayers.get(this.#currentPageIndex); + } + getLayer(pageIndex) { + return this.#allLayers.get(pageIndex); + } + get currentPageIndex() { + return this.#currentPageIndex; + } + addLayer(layer) { + this.#allLayers.set(layer.pageIndex, layer); + if (this.#isEnabled) { + layer.enable(); + } else { + layer.disable(); + } + } + removeLayer(layer) { + this.#allLayers.delete(layer.pageIndex); + } + async updateMode(mode, editId = null, isFromKeyboard = false) { + if (this.#mode === mode) { + return; + } + if (this.#updateModeCapability) { + await this.#updateModeCapability.promise; + if (!this.#updateModeCapability) { + return; + } + } + this.#updateModeCapability = Promise.withResolvers(); + this.#mode = mode; + if (mode === AnnotationEditorType.NONE) { + this.setEditingState(false); + this.#disableAll(); + this._editorUndoBar?.hide(); + this.#updateModeCapability.resolve(); + return; + } + this.setEditingState(true); + await this.#enableAll(); + this.unselectAll(); + for (const layer of this.#allLayers.values()) { + layer.updateMode(mode); + } + if (!editId) { + if (isFromKeyboard) { + this.addNewEditorFromKeyboard(); + } + this.#updateModeCapability.resolve(); + return; + } + for (const editor of this.#allEditors.values()) { + if (editor.annotationElementId === editId) { + this.setSelected(editor); + editor.enterInEditMode(); + } else { + editor.unselect(); + } + } + this.#updateModeCapability.resolve(); + } + addNewEditorFromKeyboard() { + if (this.currentLayer.canCreateNewEmptyEditor()) { + this.currentLayer.addNewEditor(); + } + } + updateToolbar(mode) { + if (mode === this.#mode) { + return; + } + this._eventBus.dispatch("switchannotationeditormode", { + source: this, + mode + }); + } + updateParams(type, value) { + if (!this.#editorTypes) { + return; + } + switch (type) { + case AnnotationEditorParamsType.CREATE: + this.currentLayer.addNewEditor(); + return; + case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR: + this.#mainHighlightColorPicker?.updateColor(value); + break; + case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL: + this._eventBus.dispatch("reporttelemetry", { + source: this, + details: { + type: "editing", + data: { + type: "highlight", + action: "toggle_visibility" + } + } + }); + (this.#showAllStates ||= new Map()).set(type, value); + this.showAllEditors("highlight", value); + break; + } + for (const editor of this.#selectedEditors) { + editor.updateParams(type, value); + } + for (const editorType of this.#editorTypes) { + editorType.updateDefaultParams(type, value); + } + } + showAllEditors(type, visible, updateButton = false) { + for (const editor of this.#allEditors.values()) { + if (editor.editorType === type) { + editor.show(visible); + } + } + const state = this.#showAllStates?.get(AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL) ?? true; + if (state !== visible) { + this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL, visible]]); + } + } + enableWaiting(mustWait = false) { + if (this.#isWaiting === mustWait) { + return; + } + this.#isWaiting = mustWait; + for (const layer of this.#allLayers.values()) { + if (mustWait) { + layer.disableClick(); + } else { + layer.enableClick(); + } + layer.div.classList.toggle("waiting", mustWait); + } + } + async #enableAll() { + if (!this.#isEnabled) { + this.#isEnabled = true; + const promises = []; + for (const layer of this.#allLayers.values()) { + promises.push(layer.enable()); + } + await Promise.all(promises); + for (const editor of this.#allEditors.values()) { + editor.enable(); + } + } + } + #disableAll() { + this.unselectAll(); + if (this.#isEnabled) { + this.#isEnabled = false; + for (const layer of this.#allLayers.values()) { + layer.disable(); + } + for (const editor of this.#allEditors.values()) { + editor.disable(); + } + } + } + getEditors(pageIndex) { + const editors = []; + for (const editor of this.#allEditors.values()) { + if (editor.pageIndex === pageIndex) { + editors.push(editor); + } + } + return editors; + } + getEditor(id) { + return this.#allEditors.get(id); + } + addEditor(editor) { + this.#allEditors.set(editor.id, editor); + } + removeEditor(editor) { + if (editor.div.contains(document.activeElement)) { + if (this.#focusMainContainerTimeoutId) { + clearTimeout(this.#focusMainContainerTimeoutId); + } + this.#focusMainContainerTimeoutId = setTimeout(() => { + this.focusMainContainer(); + this.#focusMainContainerTimeoutId = null; + }, 0); + } + this.#allEditors.delete(editor.id); + this.unselect(editor); + if (!editor.annotationElementId || !this.#deletedAnnotationsElementIds.has(editor.annotationElementId)) { + this.#annotationStorage?.remove(editor.id); + } + } + addDeletedAnnotationElement(editor) { + this.#deletedAnnotationsElementIds.add(editor.annotationElementId); + this.addChangedExistingAnnotation(editor); + editor.deleted = true; + } + isDeletedAnnotationElement(annotationElementId) { + return this.#deletedAnnotationsElementIds.has(annotationElementId); + } + removeDeletedAnnotationElement(editor) { + this.#deletedAnnotationsElementIds.delete(editor.annotationElementId); + this.removeChangedExistingAnnotation(editor); + editor.deleted = false; + } + #addEditorToLayer(editor) { + const layer = this.#allLayers.get(editor.pageIndex); + if (layer) { + layer.addOrRebuild(editor); + } else { + this.addEditor(editor); + this.addToAnnotationStorage(editor); + } + } + setActiveEditor(editor) { + if (this.#activeEditor === editor) { + return; + } + this.#activeEditor = editor; + if (editor) { + this.#dispatchUpdateUI(editor.propertiesToUpdate); + } + } + get #lastSelectedEditor() { + let ed = null; + for (ed of this.#selectedEditors) {} + return ed; + } + updateUI(editor) { + if (this.#lastSelectedEditor === editor) { + this.#dispatchUpdateUI(editor.propertiesToUpdate); + } + } + updateUIForDefaultProperties(editorType) { + this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate); + } + toggleSelected(editor) { + if (this.#selectedEditors.has(editor)) { + this.#selectedEditors.delete(editor); + editor.unselect(); + this.#dispatchUpdateStates({ + hasSelectedEditor: this.hasSelection + }); + return; + } + this.#selectedEditors.add(editor); + editor.select(); + this.#dispatchUpdateUI(editor.propertiesToUpdate); + this.#dispatchUpdateStates({ + hasSelectedEditor: true + }); + } + setSelected(editor) { + this.#currentDrawingSession?.commitOrRemove(); + for (const ed of this.#selectedEditors) { + if (ed !== editor) { + ed.unselect(); + } + } + this.#selectedEditors.clear(); + this.#selectedEditors.add(editor); + editor.select(); + this.#dispatchUpdateUI(editor.propertiesToUpdate); + this.#dispatchUpdateStates({ + hasSelectedEditor: true + }); + } + isSelected(editor) { + return this.#selectedEditors.has(editor); + } + get firstSelectedEditor() { + return this.#selectedEditors.values().next().value; + } + unselect(editor) { + editor.unselect(); + this.#selectedEditors.delete(editor); + this.#dispatchUpdateStates({ + hasSelectedEditor: this.hasSelection + }); + } + get hasSelection() { + return this.#selectedEditors.size !== 0; + } + get isEnterHandled() { + return this.#selectedEditors.size === 1 && this.firstSelectedEditor.isEnterHandled; + } + undo() { + this.#commandManager.undo(); + this.#dispatchUpdateStates({ + hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(), + hasSomethingToRedo: true, + isEmpty: this.#isEmpty() + }); + this._editorUndoBar?.hide(); + } + redo() { + this.#commandManager.redo(); + this.#dispatchUpdateStates({ + hasSomethingToUndo: true, + hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(), + isEmpty: this.#isEmpty() + }); + } + addCommands(params) { + this.#commandManager.add(params); + this.#dispatchUpdateStates({ + hasSomethingToUndo: true, + hasSomethingToRedo: false, + isEmpty: this.#isEmpty() + }); + } + cleanUndoStack(type) { + this.#commandManager.cleanType(type); + } + #isEmpty() { + if (this.#allEditors.size === 0) { + return true; + } + if (this.#allEditors.size === 1) { + for (const editor of this.#allEditors.values()) { + return editor.isEmpty(); + } + } + return false; + } + delete() { + this.commitOrRemove(); + const drawingEditor = this.currentLayer?.endDrawingSession(true); + if (!this.hasSelection && !drawingEditor) { + return; + } + const editors = drawingEditor ? [drawingEditor] : [...this.#selectedEditors]; + const cmd = () => { + this._editorUndoBar?.show(undo, editors.length === 1 ? editors[0].editorType : editors.length); + for (const editor of editors) { + editor.remove(); + } + }; + const undo = () => { + for (const editor of editors) { + this.#addEditorToLayer(editor); + } + }; + this.addCommands({ + cmd, + undo, + mustExec: true + }); + } + commitOrRemove() { + this.#activeEditor?.commitOrRemove(); + } + hasSomethingToControl() { + return this.#activeEditor || this.hasSelection; + } + #selectEditors(editors) { + for (const editor of this.#selectedEditors) { + editor.unselect(); + } + this.#selectedEditors.clear(); + for (const editor of editors) { + if (editor.isEmpty()) { + continue; + } + this.#selectedEditors.add(editor); + editor.select(); + } + this.#dispatchUpdateStates({ + hasSelectedEditor: this.hasSelection + }); + } + selectAll() { + for (const editor of this.#selectedEditors) { + editor.commit(); + } + this.#selectEditors(this.#allEditors.values()); + } + unselectAll() { + if (this.#activeEditor) { + this.#activeEditor.commitOrRemove(); + if (this.#mode !== AnnotationEditorType.NONE) { + return; + } + } + if (this.#currentDrawingSession?.commitOrRemove()) { + return; + } + if (!this.hasSelection) { + return; + } + for (const editor of this.#selectedEditors) { + editor.unselect(); + } + this.#selectedEditors.clear(); + this.#dispatchUpdateStates({ + hasSelectedEditor: false + }); + } + translateSelectedEditors(x, y, noCommit = false) { + if (!noCommit) { + this.commitOrRemove(); + } + if (!this.hasSelection) { + return; + } + this.#translation[0] += x; + this.#translation[1] += y; + const [totalX, totalY] = this.#translation; + const editors = [...this.#selectedEditors]; + const TIME_TO_WAIT = 1000; + if (this.#translationTimeoutId) { + clearTimeout(this.#translationTimeoutId); + } + this.#translationTimeoutId = setTimeout(() => { + this.#translationTimeoutId = null; + this.#translation[0] = this.#translation[1] = 0; + this.addCommands({ + cmd: () => { + for (const editor of editors) { + if (this.#allEditors.has(editor.id)) { + editor.translateInPage(totalX, totalY); + } + } + }, + undo: () => { + for (const editor of editors) { + if (this.#allEditors.has(editor.id)) { + editor.translateInPage(-totalX, -totalY); + } + } + }, + mustExec: false + }); + }, TIME_TO_WAIT); + for (const editor of editors) { + editor.translateInPage(x, y); + } + } + setUpDragSession() { + if (!this.hasSelection) { + return; + } + this.disableUserSelect(true); + this.#draggingEditors = new Map(); + for (const editor of this.#selectedEditors) { + this.#draggingEditors.set(editor, { + savedX: editor.x, + savedY: editor.y, + savedPageIndex: editor.pageIndex, + newX: 0, + newY: 0, + newPageIndex: -1 + }); + } + } + endDragSession() { + if (!this.#draggingEditors) { + return false; + } + this.disableUserSelect(false); + const map = this.#draggingEditors; + this.#draggingEditors = null; + let mustBeAddedInUndoStack = false; + for (const [{ + x, + y, + pageIndex + }, value] of map) { + value.newX = x; + value.newY = y; + value.newPageIndex = pageIndex; + mustBeAddedInUndoStack ||= x !== value.savedX || y !== value.savedY || pageIndex !== value.savedPageIndex; + } + if (!mustBeAddedInUndoStack) { + return false; + } + const move = (editor, x, y, pageIndex) => { + if (this.#allEditors.has(editor.id)) { + const parent = this.#allLayers.get(pageIndex); + if (parent) { + editor._setParentAndPosition(parent, x, y); + } else { + editor.pageIndex = pageIndex; + editor.x = x; + editor.y = y; + } + } + }; + this.addCommands({ + cmd: () => { + for (const [editor, { + newX, + newY, + newPageIndex + }] of map) { + move(editor, newX, newY, newPageIndex); + } + }, + undo: () => { + for (const [editor, { + savedX, + savedY, + savedPageIndex + }] of map) { + move(editor, savedX, savedY, savedPageIndex); + } + }, + mustExec: true + }); + return true; + } + dragSelectedEditors(tx, ty) { + if (!this.#draggingEditors) { + return; + } + for (const editor of this.#draggingEditors.keys()) { + editor.drag(tx, ty); + } + } + rebuild(editor) { + if (editor.parent === null) { + const parent = this.getLayer(editor.pageIndex); + if (parent) { + parent.changeParent(editor); + parent.addOrRebuild(editor); + } else { + this.addEditor(editor); + this.addToAnnotationStorage(editor); + editor.rebuild(); + } + } else { + editor.parent.addOrRebuild(editor); + } + } + get isEditorHandlingKeyboard() { + return this.getActive()?.shouldGetKeyboardEvents() || this.#selectedEditors.size === 1 && this.firstSelectedEditor.shouldGetKeyboardEvents(); + } + isActive(editor) { + return this.#activeEditor === editor; + } + getActive() { + return this.#activeEditor; + } + getMode() { + return this.#mode; + } + get imageManager() { + return shadow(this, "imageManager", new ImageManager()); + } + getSelectionBoxes(textLayer) { + if (!textLayer) { + return null; + } + const selection = document.getSelection(); + for (let i = 0, ii = selection.rangeCount; i < ii; i++) { + if (!textLayer.contains(selection.getRangeAt(i).commonAncestorContainer)) { + return null; + } + } + const { + x: layerX, + y: layerY, + width: parentWidth, + height: parentHeight + } = textLayer.getBoundingClientRect(); + let rotator; + switch (textLayer.getAttribute("data-main-rotation")) { + case "90": + rotator = (x, y, w, h) => ({ + x: (y - layerY) / parentHeight, + y: 1 - (x + w - layerX) / parentWidth, + width: h / parentHeight, + height: w / parentWidth + }); + break; + case "180": + rotator = (x, y, w, h) => ({ + x: 1 - (x + w - layerX) / parentWidth, + y: 1 - (y + h - layerY) / parentHeight, + width: w / parentWidth, + height: h / parentHeight + }); + break; + case "270": + rotator = (x, y, w, h) => ({ + x: 1 - (y + h - layerY) / parentHeight, + y: (x - layerX) / parentWidth, + width: h / parentHeight, + height: w / parentWidth + }); + break; + default: + rotator = (x, y, w, h) => ({ + x: (x - layerX) / parentWidth, + y: (y - layerY) / parentHeight, + width: w / parentWidth, + height: h / parentHeight + }); + break; + } + const boxes = []; + for (let i = 0, ii = selection.rangeCount; i < ii; i++) { + const range = selection.getRangeAt(i); + if (range.collapsed) { + continue; + } + for (const { + x, + y, + width, + height + } of range.getClientRects()) { + if (width === 0 || height === 0) { + continue; + } + boxes.push(rotator(x, y, width, height)); + } + } + return boxes.length === 0 ? null : boxes; + } + addChangedExistingAnnotation({ + annotationElementId, + id + }) { + (this.#changedExistingAnnotations ||= new Map()).set(annotationElementId, id); + } + removeChangedExistingAnnotation({ + annotationElementId + }) { + this.#changedExistingAnnotations?.delete(annotationElementId); + } + renderAnnotationElement(annotation) { + const editorId = this.#changedExistingAnnotations?.get(annotation.data.id); + if (!editorId) { + return; + } + const editor = this.#annotationStorage.getRawValue(editorId); + if (!editor) { + return; + } + if (this.#mode === AnnotationEditorType.NONE && !editor.hasBeenModified) { + return; + } + editor.renderAnnotationElement(annotation); + } +} + +;// ./src/display/editor/alt_text.js + +class AltText { + #altText = null; + #altTextDecorative = false; + #altTextButton = null; + #altTextButtonLabel = null; + #altTextTooltip = null; + #altTextTooltipTimeout = null; + #altTextWasFromKeyBoard = false; + #badge = null; + #editor = null; + #guessedText = null; + #textWithDisclaimer = null; + #useNewAltTextFlow = false; + static #l10nNewButton = null; + static _l10n = null; + constructor(editor) { + this.#editor = editor; + this.#useNewAltTextFlow = editor._uiManager.useNewAltTextFlow; + AltText.#l10nNewButton ||= Object.freeze({ + added: "pdfjs-editor-new-alt-text-added-button", + "added-label": "pdfjs-editor-new-alt-text-added-button-label", + missing: "pdfjs-editor-new-alt-text-missing-button", + "missing-label": "pdfjs-editor-new-alt-text-missing-button-label", + review: "pdfjs-editor-new-alt-text-to-review-button", + "review-label": "pdfjs-editor-new-alt-text-to-review-button-label" + }); + } + static initialize(l10n) { + AltText._l10n ??= l10n; + } + async render() { + const altText = this.#altTextButton = document.createElement("button"); + altText.className = "altText"; + altText.tabIndex = "0"; + const label = this.#altTextButtonLabel = document.createElement("span"); + altText.append(label); + if (this.#useNewAltTextFlow) { + altText.classList.add("new"); + altText.setAttribute("data-l10n-id", AltText.#l10nNewButton.missing); + label.setAttribute("data-l10n-id", AltText.#l10nNewButton["missing-label"]); + } else { + altText.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button"); + label.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button-label"); + } + const signal = this.#editor._uiManager._signal; + altText.addEventListener("contextmenu", noContextMenu, { + signal + }); + altText.addEventListener("pointerdown", event => event.stopPropagation(), { + signal + }); + const onClick = event => { + event.preventDefault(); + this.#editor._uiManager.editAltText(this.#editor); + if (this.#useNewAltTextFlow) { + this.#editor._reportTelemetry({ + action: "pdfjs.image.alt_text.image_status_label_clicked", + data: { + label: this.#label + } + }); + } + }; + altText.addEventListener("click", onClick, { + capture: true, + signal + }); + altText.addEventListener("keydown", event => { + if (event.target === altText && event.key === "Enter") { + this.#altTextWasFromKeyBoard = true; + onClick(event); + } + }, { + signal + }); + await this.#setState(); + return altText; + } + get #label() { + return this.#altText && "added" || this.#altText === null && this.guessedText && "review" || "missing"; + } + finish() { + if (!this.#altTextButton) { + return; + } + this.#altTextButton.focus({ + focusVisible: this.#altTextWasFromKeyBoard + }); + this.#altTextWasFromKeyBoard = false; + } + isEmpty() { + if (this.#useNewAltTextFlow) { + return this.#altText === null; + } + return !this.#altText && !this.#altTextDecorative; + } + hasData() { + if (this.#useNewAltTextFlow) { + return this.#altText !== null || !!this.#guessedText; + } + return this.isEmpty(); + } + get guessedText() { + return this.#guessedText; + } + async setGuessedText(guessedText) { + if (this.#altText !== null) { + return; + } + this.#guessedText = guessedText; + this.#textWithDisclaimer = await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer", { + generatedAltText: guessedText + }); + this.#setState(); + } + toggleAltTextBadge(visibility = false) { + if (!this.#useNewAltTextFlow || this.#altText) { + this.#badge?.remove(); + this.#badge = null; + return; + } + if (!this.#badge) { + const badge = this.#badge = document.createElement("div"); + badge.className = "noAltTextBadge"; + this.#editor.div.append(badge); + } + this.#badge.classList.toggle("hidden", !visibility); + } + serialize(isForCopying) { + let altText = this.#altText; + if (!isForCopying && this.#guessedText === altText) { + altText = this.#textWithDisclaimer; + } + return { + altText, + decorative: this.#altTextDecorative, + guessedText: this.#guessedText, + textWithDisclaimer: this.#textWithDisclaimer + }; + } + get data() { + return { + altText: this.#altText, + decorative: this.#altTextDecorative + }; + } + set data({ + altText, + decorative, + guessedText, + textWithDisclaimer, + cancel = false + }) { + if (guessedText) { + this.#guessedText = guessedText; + this.#textWithDisclaimer = textWithDisclaimer; + } + if (this.#altText === altText && this.#altTextDecorative === decorative) { + return; + } + if (!cancel) { + this.#altText = altText; + this.#altTextDecorative = decorative; + } + this.#setState(); + } + toggle(enabled = false) { + if (!this.#altTextButton) { + return; + } + if (!enabled && this.#altTextTooltipTimeout) { + clearTimeout(this.#altTextTooltipTimeout); + this.#altTextTooltipTimeout = null; + } + this.#altTextButton.disabled = !enabled; + } + shown() { + this.#editor._reportTelemetry({ + action: "pdfjs.image.alt_text.image_status_label_displayed", + data: { + label: this.#label + } + }); + } + destroy() { + this.#altTextButton?.remove(); + this.#altTextButton = null; + this.#altTextButtonLabel = null; + this.#altTextTooltip = null; + this.#badge?.remove(); + this.#badge = null; + } + async #setState() { + const button = this.#altTextButton; + if (!button) { + return; + } + if (this.#useNewAltTextFlow) { + button.classList.toggle("done", !!this.#altText); + button.setAttribute("data-l10n-id", AltText.#l10nNewButton[this.#label]); + this.#altTextButtonLabel?.setAttribute("data-l10n-id", AltText.#l10nNewButton[`${this.#label}-label`]); + if (!this.#altText) { + this.#altTextTooltip?.remove(); + return; + } + } else { + if (!this.#altText && !this.#altTextDecorative) { + button.classList.remove("done"); + this.#altTextTooltip?.remove(); + return; + } + button.classList.add("done"); + button.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-edit-button"); + } + let tooltip = this.#altTextTooltip; + if (!tooltip) { + this.#altTextTooltip = tooltip = document.createElement("span"); + tooltip.className = "tooltip"; + tooltip.setAttribute("role", "tooltip"); + tooltip.id = `alt-text-tooltip-${this.#editor.id}`; + const DELAY_TO_SHOW_TOOLTIP = 100; + const signal = this.#editor._uiManager._signal; + signal.addEventListener("abort", () => { + clearTimeout(this.#altTextTooltipTimeout); + this.#altTextTooltipTimeout = null; + }, { + once: true + }); + button.addEventListener("mouseenter", () => { + this.#altTextTooltipTimeout = setTimeout(() => { + this.#altTextTooltipTimeout = null; + this.#altTextTooltip.classList.add("show"); + this.#editor._reportTelemetry({ + action: "alt_text_tooltip" + }); + }, DELAY_TO_SHOW_TOOLTIP); + }, { + signal + }); + button.addEventListener("mouseleave", () => { + if (this.#altTextTooltipTimeout) { + clearTimeout(this.#altTextTooltipTimeout); + this.#altTextTooltipTimeout = null; + } + this.#altTextTooltip?.classList.remove("show"); + }, { + signal + }); + } + if (this.#altTextDecorative) { + tooltip.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-decorative-tooltip"); + } else { + tooltip.removeAttribute("data-l10n-id"); + tooltip.textContent = this.#altText; + } + if (!tooltip.parentNode) { + button.append(tooltip); + } + const element = this.#editor.getImageForAltText(); + element?.setAttribute("aria-describedby", tooltip.id); + } +} + +;// ./src/display/editor/editor.js + + + + + +class AnnotationEditor { + #accessibilityData = null; + #allResizerDivs = null; + #altText = null; + #disabled = false; + #dragPointerId = null; + #dragPointerType = ""; + #keepAspectRatio = false; + #resizersDiv = null; + #lastPointerCoords = null; + #savedDimensions = null; + #focusAC = null; + #focusedResizerName = ""; + #hasBeenClicked = false; + #initialRect = null; + #isEditing = false; + #isInEditMode = false; + #isResizerEnabledForKeyboard = false; + #moveInDOMTimeout = null; + #prevDragX = 0; + #prevDragY = 0; + #telemetryTimeouts = null; + _editToolbar = null; + _initialOptions = Object.create(null); + _initialData = null; + _isVisible = true; + _uiManager = null; + _focusEventsAllowed = true; + static _l10n = null; + static _l10nResizer = null; + #isDraggable = false; + #zIndex = AnnotationEditor._zIndex++; + static _borderLineWidth = -1; + static _colorManager = new ColorManager(); + static _zIndex = 1; + static _telemetryTimeout = 1000; + static get _resizerKeyboardManager() { + const resize = AnnotationEditor.prototype._resizeWithKeyboard; + const small = AnnotationEditorUIManager.TRANSLATE_SMALL; + const big = AnnotationEditorUIManager.TRANSLATE_BIG; + return shadow(this, "_resizerKeyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], resize, { + args: [-small, 0] + }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], resize, { + args: [-big, 0] + }], [["ArrowRight", "mac+ArrowRight"], resize, { + args: [small, 0] + }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], resize, { + args: [big, 0] + }], [["ArrowUp", "mac+ArrowUp"], resize, { + args: [0, -small] + }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], resize, { + args: [0, -big] + }], [["ArrowDown", "mac+ArrowDown"], resize, { + args: [0, small] + }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], resize, { + args: [0, big] + }], [["Escape", "mac+Escape"], AnnotationEditor.prototype._stopResizingWithKeyboard]])); + } + constructor(parameters) { + this.parent = parameters.parent; + this.id = parameters.id; + this.width = this.height = null; + this.pageIndex = parameters.parent.pageIndex; + this.name = parameters.name; + this.div = null; + this._uiManager = parameters.uiManager; + this.annotationElementId = null; + this._willKeepAspectRatio = false; + this._initialOptions.isCentered = parameters.isCentered; + this._structTreeParentId = null; + const { + rotation, + rawDims: { + pageWidth, + pageHeight, + pageX, + pageY + } + } = this.parent.viewport; + this.rotation = rotation; + this.pageRotation = (360 + rotation - this._uiManager.viewParameters.rotation) % 360; + this.pageDimensions = [pageWidth, pageHeight]; + this.pageTranslation = [pageX, pageY]; + const [width, height] = this.parentDimensions; + this.x = parameters.x / width; + this.y = parameters.y / height; + this.isAttachedToDOM = false; + this.deleted = false; + } + get editorType() { + return Object.getPrototypeOf(this).constructor._type; + } + static get isDrawer() { + return false; + } + static get _defaultLineColor() { + return shadow(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText")); + } + static deleteAnnotationElement(editor) { + const fakeEditor = new FakeEditor({ + id: editor.parent.getNextId(), + parent: editor.parent, + uiManager: editor._uiManager + }); + fakeEditor.annotationElementId = editor.annotationElementId; + fakeEditor.deleted = true; + fakeEditor._uiManager.addToAnnotationStorage(fakeEditor); + } + static initialize(l10n, _uiManager) { + AnnotationEditor._l10n ??= l10n; + AnnotationEditor._l10nResizer ||= Object.freeze({ + topLeft: "pdfjs-editor-resizer-top-left", + topMiddle: "pdfjs-editor-resizer-top-middle", + topRight: "pdfjs-editor-resizer-top-right", + middleRight: "pdfjs-editor-resizer-middle-right", + bottomRight: "pdfjs-editor-resizer-bottom-right", + bottomMiddle: "pdfjs-editor-resizer-bottom-middle", + bottomLeft: "pdfjs-editor-resizer-bottom-left", + middleLeft: "pdfjs-editor-resizer-middle-left" + }); + if (AnnotationEditor._borderLineWidth !== -1) { + return; + } + const style = getComputedStyle(document.documentElement); + AnnotationEditor._borderLineWidth = parseFloat(style.getPropertyValue("--outline-width")) || 0; + } + static updateDefaultParams(_type, _value) {} + static get defaultPropertiesToUpdate() { + return []; + } + static isHandlingMimeForPasting(mime) { + return false; + } + static paste(item, parent) { + unreachable("Not implemented"); + } + get propertiesToUpdate() { + return []; + } + get _isDraggable() { + return this.#isDraggable; + } + set _isDraggable(value) { + this.#isDraggable = value; + this.div?.classList.toggle("draggable", value); + } + get isEnterHandled() { + return true; + } + center() { + const [pageWidth, pageHeight] = this.pageDimensions; + switch (this.parentRotation) { + case 90: + this.x -= this.height * pageHeight / (pageWidth * 2); + this.y += this.width * pageWidth / (pageHeight * 2); + break; + case 180: + this.x += this.width / 2; + this.y += this.height / 2; + break; + case 270: + this.x += this.height * pageHeight / (pageWidth * 2); + this.y -= this.width * pageWidth / (pageHeight * 2); + break; + default: + this.x -= this.width / 2; + this.y -= this.height / 2; + break; + } + this.fixAndSetPosition(); + } + addCommands(params) { + this._uiManager.addCommands(params); + } + get currentLayer() { + return this._uiManager.currentLayer; + } + setInBackground() { + this.div.style.zIndex = 0; + } + setInForeground() { + this.div.style.zIndex = this.#zIndex; + } + setParent(parent) { + if (parent !== null) { + this.pageIndex = parent.pageIndex; + this.pageDimensions = parent.pageDimensions; + } else { + this.#stopResizing(); + } + this.parent = parent; + } + focusin(event) { + if (!this._focusEventsAllowed) { + return; + } + if (!this.#hasBeenClicked) { + this.parent.setSelected(this); + } else { + this.#hasBeenClicked = false; + } + } + focusout(event) { + if (!this._focusEventsAllowed) { + return; + } + if (!this.isAttachedToDOM) { + return; + } + const target = event.relatedTarget; + if (target?.closest(`#${this.id}`)) { + return; + } + event.preventDefault(); + if (!this.parent?.isMultipleSelection) { + this.commitOrRemove(); + } + } + commitOrRemove() { + if (this.isEmpty()) { + this.remove(); + } else { + this.commit(); + } + } + commit() { + this.addToAnnotationStorage(); + } + addToAnnotationStorage() { + this._uiManager.addToAnnotationStorage(this); + } + setAt(x, y, tx, ty) { + const [width, height] = this.parentDimensions; + [tx, ty] = this.screenToPageTranslation(tx, ty); + this.x = (x + tx) / width; + this.y = (y + ty) / height; + this.fixAndSetPosition(); + } + #translate([width, height], x, y) { + [x, y] = this.screenToPageTranslation(x, y); + this.x += x / width; + this.y += y / height; + this._onTranslating(this.x, this.y); + this.fixAndSetPosition(); + } + translate(x, y) { + this.#translate(this.parentDimensions, x, y); + } + translateInPage(x, y) { + this.#initialRect ||= [this.x, this.y, this.width, this.height]; + this.#translate(this.pageDimensions, x, y); + this.div.scrollIntoView({ + block: "nearest" + }); + } + drag(tx, ty) { + this.#initialRect ||= [this.x, this.y, this.width, this.height]; + const { + div, + parentDimensions: [parentWidth, parentHeight] + } = this; + this.x += tx / parentWidth; + this.y += ty / parentHeight; + if (this.parent && (this.x < 0 || this.x > 1 || this.y < 0 || this.y > 1)) { + const { + x, + y + } = this.div.getBoundingClientRect(); + if (this.parent.findNewParent(this, x, y)) { + this.x -= Math.floor(this.x); + this.y -= Math.floor(this.y); + } + } + let { + x, + y + } = this; + const [bx, by] = this.getBaseTranslation(); + x += bx; + y += by; + const { + style + } = div; + style.left = `${(100 * x).toFixed(2)}%`; + style.top = `${(100 * y).toFixed(2)}%`; + this._onTranslating(x, y); + div.scrollIntoView({ + block: "nearest" + }); + } + _onTranslating(x, y) {} + _onTranslated(x, y) {} + get _hasBeenMoved() { + return !!this.#initialRect && (this.#initialRect[0] !== this.x || this.#initialRect[1] !== this.y); + } + get _hasBeenResized() { + return !!this.#initialRect && (this.#initialRect[2] !== this.width || this.#initialRect[3] !== this.height); + } + getBaseTranslation() { + const [parentWidth, parentHeight] = this.parentDimensions; + const { + _borderLineWidth + } = AnnotationEditor; + const x = _borderLineWidth / parentWidth; + const y = _borderLineWidth / parentHeight; + switch (this.rotation) { + case 90: + return [-x, y]; + case 180: + return [x, y]; + case 270: + return [x, -y]; + default: + return [-x, -y]; + } + } + get _mustFixPosition() { + return true; + } + fixAndSetPosition(rotation = this.rotation) { + const { + div: { + style + }, + pageDimensions: [pageWidth, pageHeight] + } = this; + let { + x, + y, + width, + height + } = this; + width *= pageWidth; + height *= pageHeight; + x *= pageWidth; + y *= pageHeight; + if (this._mustFixPosition) { + switch (rotation) { + case 0: + x = Math.max(0, Math.min(pageWidth - width, x)); + y = Math.max(0, Math.min(pageHeight - height, y)); + break; + case 90: + x = Math.max(0, Math.min(pageWidth - height, x)); + y = Math.min(pageHeight, Math.max(width, y)); + break; + case 180: + x = Math.min(pageWidth, Math.max(width, x)); + y = Math.min(pageHeight, Math.max(height, y)); + break; + case 270: + x = Math.min(pageWidth, Math.max(height, x)); + y = Math.max(0, Math.min(pageHeight - width, y)); + break; + } + } + this.x = x /= pageWidth; + this.y = y /= pageHeight; + const [bx, by] = this.getBaseTranslation(); + x += bx; + y += by; + style.left = `${(100 * x).toFixed(2)}%`; + style.top = `${(100 * y).toFixed(2)}%`; + this.moveInDOM(); + } + static #rotatePoint(x, y, angle) { + switch (angle) { + case 90: + return [y, -x]; + case 180: + return [-x, -y]; + case 270: + return [-y, x]; + default: + return [x, y]; + } + } + screenToPageTranslation(x, y) { + return AnnotationEditor.#rotatePoint(x, y, this.parentRotation); + } + pageTranslationToScreen(x, y) { + return AnnotationEditor.#rotatePoint(x, y, 360 - this.parentRotation); + } + #getRotationMatrix(rotation) { + switch (rotation) { + case 90: + { + const [pageWidth, pageHeight] = this.pageDimensions; + return [0, -pageWidth / pageHeight, pageHeight / pageWidth, 0]; + } + case 180: + return [-1, 0, 0, -1]; + case 270: + { + const [pageWidth, pageHeight] = this.pageDimensions; + return [0, pageWidth / pageHeight, -pageHeight / pageWidth, 0]; + } + default: + return [1, 0, 0, 1]; + } + } + get parentScale() { + return this._uiManager.viewParameters.realScale; + } + get parentRotation() { + return (this._uiManager.viewParameters.rotation + this.pageRotation) % 360; + } + get parentDimensions() { + const { + parentScale, + pageDimensions: [pageWidth, pageHeight] + } = this; + return [pageWidth * parentScale, pageHeight * parentScale]; + } + setDims(width, height) { + const [parentWidth, parentHeight] = this.parentDimensions; + const { + style + } = this.div; + style.width = `${(100 * width / parentWidth).toFixed(2)}%`; + if (!this.#keepAspectRatio) { + style.height = `${(100 * height / parentHeight).toFixed(2)}%`; + } + } + fixDims() { + const { + style + } = this.div; + const { + height, + width + } = style; + const widthPercent = width.endsWith("%"); + const heightPercent = !this.#keepAspectRatio && height.endsWith("%"); + if (widthPercent && heightPercent) { + return; + } + const [parentWidth, parentHeight] = this.parentDimensions; + if (!widthPercent) { + style.width = `${(100 * parseFloat(width) / parentWidth).toFixed(2)}%`; + } + if (!this.#keepAspectRatio && !heightPercent) { + style.height = `${(100 * parseFloat(height) / parentHeight).toFixed(2)}%`; + } + } + getInitialTranslation() { + return [0, 0]; + } + #createResizers() { + if (this.#resizersDiv) { + return; + } + this.#resizersDiv = document.createElement("div"); + this.#resizersDiv.classList.add("resizers"); + const classes = this._willKeepAspectRatio ? ["topLeft", "topRight", "bottomRight", "bottomLeft"] : ["topLeft", "topMiddle", "topRight", "middleRight", "bottomRight", "bottomMiddle", "bottomLeft", "middleLeft"]; + const signal = this._uiManager._signal; + for (const name of classes) { + const div = document.createElement("div"); + this.#resizersDiv.append(div); + div.classList.add("resizer", name); + div.setAttribute("data-resizer-name", name); + div.addEventListener("pointerdown", this.#resizerPointerdown.bind(this, name), { + signal + }); + div.addEventListener("contextmenu", noContextMenu, { + signal + }); + div.tabIndex = -1; + } + this.div.prepend(this.#resizersDiv); + } + #resizerPointerdown(name, event) { + event.preventDefault(); + const { + isMac + } = util_FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + return; + } + this.#altText?.toggle(false); + const savedDraggable = this._isDraggable; + this._isDraggable = false; + this.#lastPointerCoords = [event.screenX, event.screenY]; + const ac = new AbortController(); + const signal = this._uiManager.combinedSignal(ac); + this.parent.togglePointerEvents(false); + window.addEventListener("pointermove", this.#resizerPointermove.bind(this, name), { + passive: true, + capture: true, + signal + }); + window.addEventListener("touchmove", stopEvent, { + passive: false, + signal + }); + window.addEventListener("contextmenu", noContextMenu, { + signal + }); + this.#savedDimensions = { + savedX: this.x, + savedY: this.y, + savedWidth: this.width, + savedHeight: this.height + }; + const savedParentCursor = this.parent.div.style.cursor; + const savedCursor = this.div.style.cursor; + this.div.style.cursor = this.parent.div.style.cursor = window.getComputedStyle(event.target).cursor; + const pointerUpCallback = () => { + ac.abort(); + this.parent.togglePointerEvents(true); + this.#altText?.toggle(true); + this._isDraggable = savedDraggable; + this.parent.div.style.cursor = savedParentCursor; + this.div.style.cursor = savedCursor; + this.#addResizeToUndoStack(); + }; + window.addEventListener("pointerup", pointerUpCallback, { + signal + }); + window.addEventListener("blur", pointerUpCallback, { + signal + }); + } + #resize(x, y, width, height) { + this.width = width; + this.height = height; + this.x = x; + this.y = y; + const [parentWidth, parentHeight] = this.parentDimensions; + this.setDims(parentWidth * width, parentHeight * height); + this.fixAndSetPosition(); + this._onResized(); + } + _onResized() {} + #addResizeToUndoStack() { + if (!this.#savedDimensions) { + return; + } + const { + savedX, + savedY, + savedWidth, + savedHeight + } = this.#savedDimensions; + this.#savedDimensions = null; + const newX = this.x; + const newY = this.y; + const newWidth = this.width; + const newHeight = this.height; + if (newX === savedX && newY === savedY && newWidth === savedWidth && newHeight === savedHeight) { + return; + } + this.addCommands({ + cmd: this.#resize.bind(this, newX, newY, newWidth, newHeight), + undo: this.#resize.bind(this, savedX, savedY, savedWidth, savedHeight), + mustExec: true + }); + } + #resizerPointermove(name, event) { + const [parentWidth, parentHeight] = this.parentDimensions; + const savedX = this.x; + const savedY = this.y; + const savedWidth = this.width; + const savedHeight = this.height; + const minWidth = AnnotationEditor.MIN_SIZE / parentWidth; + const minHeight = AnnotationEditor.MIN_SIZE / parentHeight; + const round = x => Math.round(x * 10000) / 10000; + const rotationMatrix = this.#getRotationMatrix(this.rotation); + const transf = (x, y) => [rotationMatrix[0] * x + rotationMatrix[2] * y, rotationMatrix[1] * x + rotationMatrix[3] * y]; + const invRotationMatrix = this.#getRotationMatrix(360 - this.rotation); + const invTransf = (x, y) => [invRotationMatrix[0] * x + invRotationMatrix[2] * y, invRotationMatrix[1] * x + invRotationMatrix[3] * y]; + let getPoint; + let getOpposite; + let isDiagonal = false; + let isHorizontal = false; + switch (name) { + case "topLeft": + isDiagonal = true; + getPoint = (w, h) => [0, 0]; + getOpposite = (w, h) => [w, h]; + break; + case "topMiddle": + getPoint = (w, h) => [w / 2, 0]; + getOpposite = (w, h) => [w / 2, h]; + break; + case "topRight": + isDiagonal = true; + getPoint = (w, h) => [w, 0]; + getOpposite = (w, h) => [0, h]; + break; + case "middleRight": + isHorizontal = true; + getPoint = (w, h) => [w, h / 2]; + getOpposite = (w, h) => [0, h / 2]; + break; + case "bottomRight": + isDiagonal = true; + getPoint = (w, h) => [w, h]; + getOpposite = (w, h) => [0, 0]; + break; + case "bottomMiddle": + getPoint = (w, h) => [w / 2, h]; + getOpposite = (w, h) => [w / 2, 0]; + break; + case "bottomLeft": + isDiagonal = true; + getPoint = (w, h) => [0, h]; + getOpposite = (w, h) => [w, 0]; + break; + case "middleLeft": + isHorizontal = true; + getPoint = (w, h) => [0, h / 2]; + getOpposite = (w, h) => [w, h / 2]; + break; + } + const point = getPoint(savedWidth, savedHeight); + const oppositePoint = getOpposite(savedWidth, savedHeight); + let transfOppositePoint = transf(...oppositePoint); + const oppositeX = round(savedX + transfOppositePoint[0]); + const oppositeY = round(savedY + transfOppositePoint[1]); + let ratioX = 1; + let ratioY = 1; + let deltaX, deltaY; + if (!event.fromKeyboard) { + const { + screenX, + screenY + } = event; + const [lastScreenX, lastScreenY] = this.#lastPointerCoords; + [deltaX, deltaY] = this.screenToPageTranslation(screenX - lastScreenX, screenY - lastScreenY); + this.#lastPointerCoords[0] = screenX; + this.#lastPointerCoords[1] = screenY; + } else { + ({ + deltaX, + deltaY + } = event); + } + [deltaX, deltaY] = invTransf(deltaX / parentWidth, deltaY / parentHeight); + if (isDiagonal) { + const oldDiag = Math.hypot(savedWidth, savedHeight); + ratioX = ratioY = Math.max(Math.min(Math.hypot(oppositePoint[0] - point[0] - deltaX, oppositePoint[1] - point[1] - deltaY) / oldDiag, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight); + } else if (isHorizontal) { + ratioX = Math.max(minWidth, Math.min(1, Math.abs(oppositePoint[0] - point[0] - deltaX))) / savedWidth; + } else { + ratioY = Math.max(minHeight, Math.min(1, Math.abs(oppositePoint[1] - point[1] - deltaY))) / savedHeight; + } + const newWidth = round(savedWidth * ratioX); + const newHeight = round(savedHeight * ratioY); + transfOppositePoint = transf(...getOpposite(newWidth, newHeight)); + const newX = oppositeX - transfOppositePoint[0]; + const newY = oppositeY - transfOppositePoint[1]; + this.#initialRect ||= [this.x, this.y, this.width, this.height]; + this.width = newWidth; + this.height = newHeight; + this.x = newX; + this.y = newY; + this.setDims(parentWidth * newWidth, parentHeight * newHeight); + this.fixAndSetPosition(); + this._onResizing(); + } + _onResizing() {} + altTextFinish() { + this.#altText?.finish(); + } + async addEditToolbar() { + if (this._editToolbar || this.#isInEditMode) { + return this._editToolbar; + } + this._editToolbar = new EditorToolbar(this); + this.div.append(this._editToolbar.render()); + if (this.#altText) { + await this._editToolbar.addAltText(this.#altText); + } + return this._editToolbar; + } + removeEditToolbar() { + if (!this._editToolbar) { + return; + } + this._editToolbar.remove(); + this._editToolbar = null; + this.#altText?.destroy(); + } + addContainer(container) { + const editToolbarDiv = this._editToolbar?.div; + if (editToolbarDiv) { + editToolbarDiv.before(container); + } else { + this.div.append(container); + } + } + getClientDimensions() { + return this.div.getBoundingClientRect(); + } + async addAltTextButton() { + if (this.#altText) { + return; + } + AltText.initialize(AnnotationEditor._l10n); + this.#altText = new AltText(this); + if (this.#accessibilityData) { + this.#altText.data = this.#accessibilityData; + this.#accessibilityData = null; + } + await this.addEditToolbar(); + } + get altTextData() { + return this.#altText?.data; + } + set altTextData(data) { + if (!this.#altText) { + return; + } + this.#altText.data = data; + } + get guessedAltText() { + return this.#altText?.guessedText; + } + async setGuessedAltText(text) { + await this.#altText?.setGuessedText(text); + } + serializeAltText(isForCopying) { + return this.#altText?.serialize(isForCopying); + } + hasAltText() { + return !!this.#altText && !this.#altText.isEmpty(); + } + hasAltTextData() { + return this.#altText?.hasData() ?? false; + } + render() { + this.div = document.createElement("div"); + this.div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360); + this.div.className = this.name; + this.div.setAttribute("id", this.id); + this.div.tabIndex = this.#disabled ? -1 : 0; + if (!this._isVisible) { + this.div.classList.add("hidden"); + } + this.setInForeground(); + this.#addFocusListeners(); + const [parentWidth, parentHeight] = this.parentDimensions; + if (this.parentRotation % 180 !== 0) { + this.div.style.maxWidth = `${(100 * parentHeight / parentWidth).toFixed(2)}%`; + this.div.style.maxHeight = `${(100 * parentWidth / parentHeight).toFixed(2)}%`; + } + const [tx, ty] = this.getInitialTranslation(); + this.translate(tx, ty); + bindEvents(this, this.div, ["pointerdown"]); + this._uiManager._editorUndoBar?.hide(); + return this.div; + } + pointerdown(event) { + const { + isMac + } = util_FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + event.preventDefault(); + return; + } + this.#hasBeenClicked = true; + if (this._isDraggable) { + this.#setUpDragSession(event); + return; + } + this.#selectOnPointerEvent(event); + } + get isSelected() { + return this._uiManager.isSelected(this); + } + #selectOnPointerEvent(event) { + const { + isMac + } = util_FeatureTest.platform; + if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) { + this.parent.toggleSelected(this); + } else { + this.parent.setSelected(this); + } + } + #setUpDragSession(event) { + const { + isSelected + } = this; + this._uiManager.setUpDragSession(); + const ac = new AbortController(); + const signal = this._uiManager.combinedSignal(ac); + const opts = { + capture: true, + passive: false, + signal + }; + const cancelDrag = e => { + ac.abort(); + this.#dragPointerId = null; + this.#hasBeenClicked = false; + if (!this._uiManager.endDragSession()) { + this.#selectOnPointerEvent(e); + } + }; + if (isSelected) { + this.#prevDragX = event.clientX; + this.#prevDragY = event.clientY; + this.#dragPointerId = event.pointerId; + this.#dragPointerType = event.pointerType; + window.addEventListener("pointermove", e => { + const { + clientX: x, + clientY: y, + pointerId + } = e; + if (pointerId !== this.#dragPointerId) { + stopEvent(e); + return; + } + const [tx, ty] = this.screenToPageTranslation(x - this.#prevDragX, y - this.#prevDragY); + this.#prevDragX = x; + this.#prevDragY = y; + this._uiManager.dragSelectedEditors(tx, ty); + }, opts); + window.addEventListener("touchmove", stopEvent, opts); + window.addEventListener("pointerdown", e => { + if (e.isPrimary && e.pointerType === this.#dragPointerType) { + cancelDrag(e); + } + stopEvent(e); + }, opts); + } + this._onStartDragging(); + const pointerUpCallback = e => { + if (!this.#dragPointerId || this.#dragPointerId === e.pointerId) { + cancelDrag(e); + this._onStopDragging(); + return; + } + stopEvent(e); + }; + window.addEventListener("pointerup", pointerUpCallback, { + signal + }); + window.addEventListener("blur", pointerUpCallback, { + signal + }); + } + _onStartDragging() {} + _onStopDragging() {} + moveInDOM() { + if (this.#moveInDOMTimeout) { + clearTimeout(this.#moveInDOMTimeout); + } + this.#moveInDOMTimeout = setTimeout(() => { + this.#moveInDOMTimeout = null; + this.parent?.moveEditorInDOM(this); + }, 0); + } + _setParentAndPosition(parent, x, y) { + parent.changeParent(this); + this.x = x; + this.y = y; + this.fixAndSetPosition(); + this._onTranslated(); + } + getRect(tx, ty, rotation = this.rotation) { + const scale = this.parentScale; + const [pageWidth, pageHeight] = this.pageDimensions; + const [pageX, pageY] = this.pageTranslation; + const shiftX = tx / scale; + const shiftY = ty / scale; + const x = this.x * pageWidth; + const y = this.y * pageHeight; + const width = this.width * pageWidth; + const height = this.height * pageHeight; + switch (rotation) { + case 0: + return [x + shiftX + pageX, pageHeight - y - shiftY - height + pageY, x + shiftX + width + pageX, pageHeight - y - shiftY + pageY]; + case 90: + return [x + shiftY + pageX, pageHeight - y + shiftX + pageY, x + shiftY + height + pageX, pageHeight - y + shiftX + width + pageY]; + case 180: + return [x - shiftX - width + pageX, pageHeight - y + shiftY + pageY, x - shiftX + pageX, pageHeight - y + shiftY + height + pageY]; + case 270: + return [x - shiftY - height + pageX, pageHeight - y - shiftX - width + pageY, x - shiftY + pageX, pageHeight - y - shiftX + pageY]; + default: + throw new Error("Invalid rotation"); + } + } + getRectInCurrentCoords(rect, pageHeight) { + const [x1, y1, x2, y2] = rect; + const width = x2 - x1; + const height = y2 - y1; + switch (this.rotation) { + case 0: + return [x1, pageHeight - y2, width, height]; + case 90: + return [x1, pageHeight - y1, height, width]; + case 180: + return [x2, pageHeight - y1, width, height]; + case 270: + return [x2, pageHeight - y2, height, width]; + default: + throw new Error("Invalid rotation"); + } + } + onceAdded() {} + isEmpty() { + return false; + } + enableEditMode() { + this.#isInEditMode = true; + } + disableEditMode() { + this.#isInEditMode = false; + } + isInEditMode() { + return this.#isInEditMode; + } + shouldGetKeyboardEvents() { + return this.#isResizerEnabledForKeyboard; + } + needsToBeRebuilt() { + return this.div && !this.isAttachedToDOM; + } + get isOnScreen() { + const { + top, + left, + bottom, + right + } = this.getClientDimensions(); + const { + innerHeight, + innerWidth + } = window; + return left < innerWidth && right > 0 && top < innerHeight && bottom > 0; + } + #addFocusListeners() { + if (this.#focusAC || !this.div) { + return; + } + this.#focusAC = new AbortController(); + const signal = this._uiManager.combinedSignal(this.#focusAC); + this.div.addEventListener("focusin", this.focusin.bind(this), { + signal + }); + this.div.addEventListener("focusout", this.focusout.bind(this), { + signal + }); + } + rebuild() { + this.#addFocusListeners(); + } + rotate(_angle) {} + resize() {} + serializeDeleted() { + return { + id: this.annotationElementId, + deleted: true, + pageIndex: this.pageIndex, + popupRef: this._initialData?.popupRef || "" + }; + } + serialize(isForCopying = false, context = null) { + unreachable("An editor must be serializable"); + } + static async deserialize(data, parent, uiManager) { + const editor = new this.prototype.constructor({ + parent, + id: parent.getNextId(), + uiManager + }); + editor.rotation = data.rotation; + editor.#accessibilityData = data.accessibilityData; + const [pageWidth, pageHeight] = editor.pageDimensions; + const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight); + editor.x = x / pageWidth; + editor.y = y / pageHeight; + editor.width = width / pageWidth; + editor.height = height / pageHeight; + return editor; + } + get hasBeenModified() { + return !!this.annotationElementId && (this.deleted || this.serialize() !== null); + } + remove() { + this.#focusAC?.abort(); + this.#focusAC = null; + if (!this.isEmpty()) { + this.commit(); + } + if (this.parent) { + this.parent.remove(this); + } else { + this._uiManager.removeEditor(this); + } + if (this.#moveInDOMTimeout) { + clearTimeout(this.#moveInDOMTimeout); + this.#moveInDOMTimeout = null; + } + this.#stopResizing(); + this.removeEditToolbar(); + if (this.#telemetryTimeouts) { + for (const timeout of this.#telemetryTimeouts.values()) { + clearTimeout(timeout); + } + this.#telemetryTimeouts = null; + } + this.parent = null; + } + get isResizable() { + return false; + } + makeResizable() { + if (this.isResizable) { + this.#createResizers(); + this.#resizersDiv.classList.remove("hidden"); + bindEvents(this, this.div, ["keydown"]); + } + } + get toolbarPosition() { + return null; + } + keydown(event) { + if (!this.isResizable || event.target !== this.div || event.key !== "Enter") { + return; + } + this._uiManager.setSelected(this); + this.#savedDimensions = { + savedX: this.x, + savedY: this.y, + savedWidth: this.width, + savedHeight: this.height + }; + const children = this.#resizersDiv.children; + if (!this.#allResizerDivs) { + this.#allResizerDivs = Array.from(children); + const boundResizerKeydown = this.#resizerKeydown.bind(this); + const boundResizerBlur = this.#resizerBlur.bind(this); + const signal = this._uiManager._signal; + for (const div of this.#allResizerDivs) { + const name = div.getAttribute("data-resizer-name"); + div.setAttribute("role", "spinbutton"); + div.addEventListener("keydown", boundResizerKeydown, { + signal + }); + div.addEventListener("blur", boundResizerBlur, { + signal + }); + div.addEventListener("focus", this.#resizerFocus.bind(this, name), { + signal + }); + div.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]); + } + } + const first = this.#allResizerDivs[0]; + let firstPosition = 0; + for (const div of children) { + if (div === first) { + break; + } + firstPosition++; + } + const nextFirstPosition = (360 - this.rotation + this.parentRotation) % 360 / 90 * (this.#allResizerDivs.length / 4); + if (nextFirstPosition !== firstPosition) { + if (nextFirstPosition < firstPosition) { + for (let i = 0; i < firstPosition - nextFirstPosition; i++) { + this.#resizersDiv.append(this.#resizersDiv.firstChild); + } + } else if (nextFirstPosition > firstPosition) { + for (let i = 0; i < nextFirstPosition - firstPosition; i++) { + this.#resizersDiv.firstChild.before(this.#resizersDiv.lastChild); + } + } + let i = 0; + for (const child of children) { + const div = this.#allResizerDivs[i++]; + const name = div.getAttribute("data-resizer-name"); + child.setAttribute("data-l10n-id", AnnotationEditor._l10nResizer[name]); + } + } + this.#setResizerTabIndex(0); + this.#isResizerEnabledForKeyboard = true; + this.#resizersDiv.firstChild.focus({ + focusVisible: true + }); + event.preventDefault(); + event.stopImmediatePropagation(); + } + #resizerKeydown(event) { + AnnotationEditor._resizerKeyboardManager.exec(this, event); + } + #resizerBlur(event) { + if (this.#isResizerEnabledForKeyboard && event.relatedTarget?.parentNode !== this.#resizersDiv) { + this.#stopResizing(); + } + } + #resizerFocus(name) { + this.#focusedResizerName = this.#isResizerEnabledForKeyboard ? name : ""; + } + #setResizerTabIndex(value) { + if (!this.#allResizerDivs) { + return; + } + for (const div of this.#allResizerDivs) { + div.tabIndex = value; + } + } + _resizeWithKeyboard(x, y) { + if (!this.#isResizerEnabledForKeyboard) { + return; + } + this.#resizerPointermove(this.#focusedResizerName, { + deltaX: x, + deltaY: y, + fromKeyboard: true + }); + } + #stopResizing() { + this.#isResizerEnabledForKeyboard = false; + this.#setResizerTabIndex(-1); + this.#addResizeToUndoStack(); + } + _stopResizingWithKeyboard() { + this.#stopResizing(); + this.div.focus(); + } + select() { + this.makeResizable(); + this.div?.classList.add("selectedEditor"); + if (!this._editToolbar) { + this.addEditToolbar().then(() => { + if (this.div?.classList.contains("selectedEditor")) { + this._editToolbar?.show(); + } + }); + return; + } + this._editToolbar?.show(); + this.#altText?.toggleAltTextBadge(false); + } + unselect() { + this.#resizersDiv?.classList.add("hidden"); + this.div?.classList.remove("selectedEditor"); + if (this.div?.contains(document.activeElement)) { + this._uiManager.currentLayer.div.focus({ + preventScroll: true + }); + } + this._editToolbar?.hide(); + this.#altText?.toggleAltTextBadge(true); + } + updateParams(type, value) {} + disableEditing() {} + enableEditing() {} + enterInEditMode() {} + getImageForAltText() { + return null; + } + get contentDiv() { + return this.div; + } + get isEditing() { + return this.#isEditing; + } + set isEditing(value) { + this.#isEditing = value; + if (!this.parent) { + return; + } + if (value) { + this.parent.setSelected(this); + this.parent.setActiveEditor(this); + } else { + this.parent.setActiveEditor(null); + } + } + setAspectRatio(width, height) { + this.#keepAspectRatio = true; + const aspectRatio = width / height; + const { + style + } = this.div; + style.aspectRatio = aspectRatio; + style.height = "auto"; + } + static get MIN_SIZE() { + return 16; + } + static canCreateNewEmptyEditor() { + return true; + } + get telemetryInitialData() { + return { + action: "added" + }; + } + get telemetryFinalData() { + return null; + } + _reportTelemetry(data, mustWait = false) { + if (mustWait) { + this.#telemetryTimeouts ||= new Map(); + const { + action + } = data; + let timeout = this.#telemetryTimeouts.get(action); + if (timeout) { + clearTimeout(timeout); + } + timeout = setTimeout(() => { + this._reportTelemetry(data); + this.#telemetryTimeouts.delete(action); + if (this.#telemetryTimeouts.size === 0) { + this.#telemetryTimeouts = null; + } + }, AnnotationEditor._telemetryTimeout); + this.#telemetryTimeouts.set(action, timeout); + return; + } + data.type ||= this.editorType; + this._uiManager._eventBus.dispatch("reporttelemetry", { + source: this, + details: { + type: "editing", + data + } + }); + } + show(visible = this._isVisible) { + this.div.classList.toggle("hidden", !visible); + this._isVisible = visible; + } + enable() { + if (this.div) { + this.div.tabIndex = 0; + } + this.#disabled = false; + } + disable() { + if (this.div) { + this.div.tabIndex = -1; + } + this.#disabled = true; + } + renderAnnotationElement(annotation) { + let content = annotation.container.querySelector(".annotationContent"); + if (!content) { + content = document.createElement("div"); + content.classList.add("annotationContent", this.editorType); + annotation.container.prepend(content); + } else if (content.nodeName === "CANVAS") { + const canvas = content; + content = document.createElement("div"); + content.classList.add("annotationContent", this.editorType); + canvas.before(content); + } + return content; + } + resetAnnotationElement(annotation) { + const { + firstChild + } = annotation.container; + if (firstChild?.nodeName === "DIV" && firstChild.classList.contains("annotationContent")) { + firstChild.remove(); + } + } +} +class FakeEditor extends AnnotationEditor { + constructor(params) { + super(params); + this.annotationElementId = params.annotationElementId; + this.deleted = true; + } + serialize() { + return this.serializeDeleted(); + } +} + +;// ./src/shared/murmurhash3.js +const SEED = 0xc3d2e1f0; +const MASK_HIGH = 0xffff0000; +const MASK_LOW = 0xffff; +class MurmurHash3_64 { + constructor(seed) { + this.h1 = seed ? seed & 0xffffffff : SEED; + this.h2 = seed ? seed & 0xffffffff : SEED; + } + update(input) { + let data, length; + if (typeof input === "string") { + data = new Uint8Array(input.length * 2); + length = 0; + for (let i = 0, ii = input.length; i < ii; i++) { + const code = input.charCodeAt(i); + if (code <= 0xff) { + data[length++] = code; + } else { + data[length++] = code >>> 8; + data[length++] = code & 0xff; + } + } + } else if (ArrayBuffer.isView(input)) { + data = input.slice(); + length = data.byteLength; + } else { + throw new Error("Invalid data format, must be a string or TypedArray."); + } + const blockCounts = length >> 2; + const tailLength = length - blockCounts * 4; + const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts); + let k1 = 0, + k2 = 0; + let h1 = this.h1, + h2 = this.h2; + const C1 = 0xcc9e2d51, + C2 = 0x1b873593; + const C1_LOW = C1 & MASK_LOW, + C2_LOW = C2 & MASK_LOW; + for (let i = 0; i < blockCounts; i++) { + if (i & 1) { + k1 = dataUint32[i]; + k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW; + k1 = k1 << 15 | k1 >>> 17; + k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW; + h1 ^= k1; + h1 = h1 << 13 | h1 >>> 19; + h1 = h1 * 5 + 0xe6546b64; + } else { + k2 = dataUint32[i]; + k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW; + k2 = k2 << 15 | k2 >>> 17; + k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW; + h2 ^= k2; + h2 = h2 << 13 | h2 >>> 19; + h2 = h2 * 5 + 0xe6546b64; + } + } + k1 = 0; + switch (tailLength) { + case 3: + k1 ^= data[blockCounts * 4 + 2] << 16; + case 2: + k1 ^= data[blockCounts * 4 + 1] << 8; + case 1: + k1 ^= data[blockCounts * 4]; + k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW; + k1 = k1 << 15 | k1 >>> 17; + k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW; + if (blockCounts & 1) { + h1 ^= k1; + } else { + h2 ^= k1; + } + } + this.h1 = h1; + this.h2 = h2; + } + hexdigest() { + let h1 = this.h1, + h2 = this.h2; + h1 ^= h2 >>> 1; + h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW; + h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16; + h1 ^= h2 >>> 1; + h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW; + h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16; + h1 ^= h2 >>> 1; + return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0"); + } +} + +;// ./src/display/annotation_storage.js + + + +const SerializableEmpty = Object.freeze({ + map: null, + hash: "", + transfer: undefined +}); +class AnnotationStorage { + #modified = false; + #modifiedIds = null; + #storage = new Map(); + constructor() { + this.onSetModified = null; + this.onResetModified = null; + this.onAnnotationEditor = null; + } + getValue(key, defaultValue) { + const value = this.#storage.get(key); + if (value === undefined) { + return defaultValue; + } + return Object.assign(defaultValue, value); + } + getRawValue(key) { + return this.#storage.get(key); + } + remove(key) { + this.#storage.delete(key); + if (this.#storage.size === 0) { + this.resetModified(); + } + if (typeof this.onAnnotationEditor === "function") { + for (const value of this.#storage.values()) { + if (value instanceof AnnotationEditor) { + return; + } + } + this.onAnnotationEditor(null); + } + } + setValue(key, value) { + const obj = this.#storage.get(key); + let modified = false; + if (obj !== undefined) { + for (const [entry, val] of Object.entries(value)) { + if (obj[entry] !== val) { + modified = true; + obj[entry] = val; + } + } + } else { + modified = true; + this.#storage.set(key, value); + } + if (modified) { + this.#setModified(); + } + if (value instanceof AnnotationEditor && typeof this.onAnnotationEditor === "function") { + this.onAnnotationEditor(value.constructor._type); + } + } + has(key) { + return this.#storage.has(key); + } + getAll() { + return this.#storage.size > 0 ? objectFromMap(this.#storage) : null; + } + setAll(obj) { + for (const [key, val] of Object.entries(obj)) { + this.setValue(key, val); + } + } + get size() { + return this.#storage.size; + } + #setModified() { + if (!this.#modified) { + this.#modified = true; + if (typeof this.onSetModified === "function") { + this.onSetModified(); + } + } + } + resetModified() { + if (this.#modified) { + this.#modified = false; + if (typeof this.onResetModified === "function") { + this.onResetModified(); + } + } + } + get print() { + return new PrintAnnotationStorage(this); + } + get serializable() { + if (this.#storage.size === 0) { + return SerializableEmpty; + } + const map = new Map(), + hash = new MurmurHash3_64(), + transfer = []; + const context = Object.create(null); + let hasBitmap = false; + for (const [key, val] of this.#storage) { + const serialized = val instanceof AnnotationEditor ? val.serialize(false, context) : val; + if (serialized) { + map.set(key, serialized); + hash.update(`${key}:${JSON.stringify(serialized)}`); + hasBitmap ||= !!serialized.bitmap; + } + } + if (hasBitmap) { + for (const value of map.values()) { + if (value.bitmap) { + transfer.push(value.bitmap); + } + } + } + return map.size > 0 ? { + map, + hash: hash.hexdigest(), + transfer + } : SerializableEmpty; + } + get editorStats() { + let stats = null; + const typeToEditor = new Map(); + for (const value of this.#storage.values()) { + if (!(value instanceof AnnotationEditor)) { + continue; + } + const editorStats = value.telemetryFinalData; + if (!editorStats) { + continue; + } + const { + type + } = editorStats; + if (!typeToEditor.has(type)) { + typeToEditor.set(type, Object.getPrototypeOf(value).constructor); + } + stats ||= Object.create(null); + const map = stats[type] ||= new Map(); + for (const [key, val] of Object.entries(editorStats)) { + if (key === "type") { + continue; + } + let counters = map.get(key); + if (!counters) { + counters = new Map(); + map.set(key, counters); + } + const count = counters.get(val) ?? 0; + counters.set(val, count + 1); + } + } + for (const [type, editor] of typeToEditor) { + stats[type] = editor.computeTelemetryFinalData(stats[type]); + } + return stats; + } + resetModifiedIds() { + this.#modifiedIds = null; + } + get modifiedIds() { + if (this.#modifiedIds) { + return this.#modifiedIds; + } + const ids = []; + for (const value of this.#storage.values()) { + if (!(value instanceof AnnotationEditor) || !value.annotationElementId || !value.serialize()) { + continue; + } + ids.push(value.annotationElementId); + } + return this.#modifiedIds = { + ids: new Set(ids), + hash: ids.join(",") + }; + } +} +class PrintAnnotationStorage extends AnnotationStorage { + #serializable; + constructor(parent) { + super(); + const { + map, + hash, + transfer + } = parent.serializable; + const clone = structuredClone(map, transfer ? { + transfer + } : null); + this.#serializable = { + map: clone, + hash, + transfer + }; + } + get print() { + unreachable("Should not call PrintAnnotationStorage.print"); + } + get serializable() { + return this.#serializable; + } + get modifiedIds() { + return shadow(this, "modifiedIds", { + ids: new Set(), + hash: "" + }); + } +} + +;// ./src/display/font_loader.js + +class FontLoader { + #systemFonts = new Set(); + constructor({ + ownerDocument = globalThis.document, + styleElement = null + }) { + this._document = ownerDocument; + this.nativeFontFaces = new Set(); + this.styleElement = null; + this.loadingRequests = []; + this.loadTestFontId = 0; + } + addNativeFontFace(nativeFontFace) { + this.nativeFontFaces.add(nativeFontFace); + this._document.fonts.add(nativeFontFace); + } + removeNativeFontFace(nativeFontFace) { + this.nativeFontFaces.delete(nativeFontFace); + this._document.fonts.delete(nativeFontFace); + } + insertRule(rule) { + if (!this.styleElement) { + this.styleElement = this._document.createElement("style"); + this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement); + } + const styleSheet = this.styleElement.sheet; + styleSheet.insertRule(rule, styleSheet.cssRules.length); + } + clear() { + for (const nativeFontFace of this.nativeFontFaces) { + this._document.fonts.delete(nativeFontFace); + } + this.nativeFontFaces.clear(); + this.#systemFonts.clear(); + if (this.styleElement) { + this.styleElement.remove(); + this.styleElement = null; + } + } + async loadSystemFont({ + systemFontInfo: info, + _inspectFont + }) { + if (!info || this.#systemFonts.has(info.loadedName)) { + return; + } + assert(!this.disableFontFace, "loadSystemFont shouldn't be called when `disableFontFace` is set."); + if (this.isFontLoadingAPISupported) { + const { + loadedName, + src, + style + } = info; + const fontFace = new FontFace(loadedName, src, style); + this.addNativeFontFace(fontFace); + try { + await fontFace.load(); + this.#systemFonts.add(loadedName); + _inspectFont?.(info); + } catch { + warn(`Cannot load system font: ${info.baseFontName}, installing it could help to improve PDF rendering.`); + this.removeNativeFontFace(fontFace); + } + return; + } + unreachable("Not implemented: loadSystemFont without the Font Loading API."); + } + async bind(font) { + if (font.attached || font.missingFile && !font.systemFontInfo) { + return; + } + font.attached = true; + if (font.systemFontInfo) { + await this.loadSystemFont(font); + return; + } + if (this.isFontLoadingAPISupported) { + const nativeFontFace = font.createNativeFontFace(); + if (nativeFontFace) { + this.addNativeFontFace(nativeFontFace); + try { + await nativeFontFace.loaded; + } catch (ex) { + warn(`Failed to load font '${nativeFontFace.family}': '${ex}'.`); + font.disableFontFace = true; + throw ex; + } + } + return; + } + const rule = font.createFontFaceRule(); + if (rule) { + this.insertRule(rule); + if (this.isSyncFontLoadingSupported) { + return; + } + await new Promise(resolve => { + const request = this._queueLoadingCallback(resolve); + this._prepareFontLoadEvent(font, request); + }); + } + } + get isFontLoadingAPISupported() { + const hasFonts = !!this._document?.fonts; + return shadow(this, "isFontLoadingAPISupported", hasFonts); + } + get isSyncFontLoadingSupported() { + let supported = false; + if (isNodeJS) { + supported = true; + } else if (typeof navigator !== "undefined" && typeof navigator?.userAgent === "string" && /Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent)) { + supported = true; + } + return shadow(this, "isSyncFontLoadingSupported", supported); + } + _queueLoadingCallback(callback) { + function completeRequest() { + assert(!request.done, "completeRequest() cannot be called twice."); + request.done = true; + while (loadingRequests.length > 0 && loadingRequests[0].done) { + const otherRequest = loadingRequests.shift(); + setTimeout(otherRequest.callback, 0); + } + } + const { + loadingRequests + } = this; + const request = { + done: false, + complete: completeRequest, + callback + }; + loadingRequests.push(request); + return request; + } + get _loadTestFont() { + const testFont = atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQA" + "FQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAA" + "ALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgA" + "AAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1" + "AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD" + "6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACM" + "AooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4D" + "IP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAA" + "AAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUA" + "AQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgAB" + "AAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABY" + "AAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAA" + "AC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAA" + "AAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQAC" + "AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3" + "Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj" + "FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="); + return shadow(this, "_loadTestFont", testFont); + } + _prepareFontLoadEvent(font, request) { + function int32(data, offset) { + return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff; + } + function spliceString(s, offset, remove, insert) { + const chunk1 = s.substring(0, offset); + const chunk2 = s.substring(offset + remove); + return chunk1 + insert + chunk2; + } + let i, ii; + const canvas = this._document.createElement("canvas"); + canvas.width = 1; + canvas.height = 1; + const ctx = canvas.getContext("2d"); + let called = 0; + function isFontReady(name, callback) { + if (++called > 30) { + warn("Load test font never loaded."); + callback(); + return; + } + ctx.font = "30px " + name; + ctx.fillText(".", 0, 20); + const imageData = ctx.getImageData(0, 0, 1, 1); + if (imageData.data[3] > 0) { + callback(); + return; + } + setTimeout(isFontReady.bind(null, name, callback)); + } + const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`; + let data = this._loadTestFont; + const COMMENT_OFFSET = 976; + data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId); + const CFF_CHECKSUM_OFFSET = 16; + const XXXX_VALUE = 0x58585858; + let checksum = int32(data, CFF_CHECKSUM_OFFSET); + for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) { + checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0; + } + if (i < loadTestFontId.length) { + checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0; + } + data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum)); + const url = `url(data:font/opentype;base64,${btoa(data)});`; + const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`; + this.insertRule(rule); + const div = this._document.createElement("div"); + div.style.visibility = "hidden"; + div.style.width = div.style.height = "10px"; + div.style.position = "absolute"; + div.style.top = div.style.left = "0px"; + for (const name of [font.loadedName, loadTestFontId]) { + const span = this._document.createElement("span"); + span.textContent = "Hi"; + span.style.fontFamily = name; + div.append(span); + } + this._document.body.append(div); + isFontReady(loadTestFontId, () => { + div.remove(); + request.complete(); + }); + } +} +class FontFaceObject { + constructor(translatedData, { + disableFontFace = false, + inspectFont = null + }) { + this.compiledGlyphs = Object.create(null); + for (const i in translatedData) { + this[i] = translatedData[i]; + } + this.disableFontFace = disableFontFace === true; + this._inspectFont = inspectFont; + } + createNativeFontFace() { + if (!this.data || this.disableFontFace) { + return null; + } + let nativeFontFace; + if (!this.cssFontInfo) { + nativeFontFace = new FontFace(this.loadedName, this.data, {}); + } else { + const css = { + weight: this.cssFontInfo.fontWeight + }; + if (this.cssFontInfo.italicAngle) { + css.style = `oblique ${this.cssFontInfo.italicAngle}deg`; + } + nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css); + } + this._inspectFont?.(this); + return nativeFontFace; + } + createFontFaceRule() { + if (!this.data || this.disableFontFace) { + return null; + } + const url = `url(data:${this.mimetype};base64,${toBase64Util(this.data)});`; + let rule; + if (!this.cssFontInfo) { + rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`; + } else { + let css = `font-weight: ${this.cssFontInfo.fontWeight};`; + if (this.cssFontInfo.italicAngle) { + css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`; + } + rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`; + } + this._inspectFont?.(this, url); + return rule; + } + getPathGenerator(objs, character) { + if (this.compiledGlyphs[character] !== undefined) { + return this.compiledGlyphs[character]; + } + let cmds; + try { + cmds = objs.get(this.loadedName + "_path_" + character); + } catch (ex) { + warn(`getPathGenerator - ignoring character: "${ex}".`); + } + if (!Array.isArray(cmds) || cmds.length === 0) { + return this.compiledGlyphs[character] = function (c, size) {}; + } + const commands = []; + for (let i = 0, ii = cmds.length; i < ii;) { + switch (cmds[i++]) { + case FontRenderOps.BEZIER_CURVE_TO: + { + const [a, b, c, d, e, f] = cmds.slice(i, i + 6); + commands.push(ctx => ctx.bezierCurveTo(a, b, c, d, e, f)); + i += 6; + } + break; + case FontRenderOps.MOVE_TO: + { + const [a, b] = cmds.slice(i, i + 2); + commands.push(ctx => ctx.moveTo(a, b)); + i += 2; + } + break; + case FontRenderOps.LINE_TO: + { + const [a, b] = cmds.slice(i, i + 2); + commands.push(ctx => ctx.lineTo(a, b)); + i += 2; + } + break; + case FontRenderOps.QUADRATIC_CURVE_TO: + { + const [a, b, c, d] = cmds.slice(i, i + 4); + commands.push(ctx => ctx.quadraticCurveTo(a, b, c, d)); + i += 4; + } + break; + case FontRenderOps.RESTORE: + commands.push(ctx => ctx.restore()); + break; + case FontRenderOps.SAVE: + commands.push(ctx => ctx.save()); + break; + case FontRenderOps.SCALE: + assert(commands.length === 2, "Scale command is only valid at the third position."); + break; + case FontRenderOps.TRANSFORM: + { + const [a, b, c, d, e, f] = cmds.slice(i, i + 6); + commands.push(ctx => ctx.transform(a, b, c, d, e, f)); + i += 6; + } + break; + case FontRenderOps.TRANSLATE: + { + const [a, b] = cmds.slice(i, i + 2); + commands.push(ctx => ctx.translate(a, b)); + i += 2; + } + break; + } + } + commands.push(ctx => ctx.closePath()); + return this.compiledGlyphs[character] = function glyphDrawer(ctx, size) { + commands[0](ctx); + commands[1](ctx); + ctx.scale(size, -size); + for (let i = 2, ii = commands.length; i < ii; i++) { + commands[i](ctx); + } + }; + } +} + +;// ./src/display/canvas_factory.js + +class BaseCanvasFactory { + #enableHWA = false; + constructor({ + enableHWA = false + }) { + this.#enableHWA = enableHWA; + } + create(width, height) { + if (width <= 0 || height <= 0) { + throw new Error("Invalid canvas size"); + } + const canvas = this._createCanvas(width, height); + return { + canvas, + context: canvas.getContext("2d", { + willReadFrequently: !this.#enableHWA + }) + }; + } + reset(canvasAndContext, width, height) { + if (!canvasAndContext.canvas) { + throw new Error("Canvas is not specified"); + } + if (width <= 0 || height <= 0) { + throw new Error("Invalid canvas size"); + } + canvasAndContext.canvas.width = width; + canvasAndContext.canvas.height = height; + } + destroy(canvasAndContext) { + if (!canvasAndContext.canvas) { + throw new Error("Canvas is not specified"); + } + canvasAndContext.canvas.width = 0; + canvasAndContext.canvas.height = 0; + canvasAndContext.canvas = null; + canvasAndContext.context = null; + } + _createCanvas(width, height) { + unreachable("Abstract method `_createCanvas` called."); + } +} +class DOMCanvasFactory extends BaseCanvasFactory { + constructor({ + ownerDocument = globalThis.document, + enableHWA = false + }) { + super({ + enableHWA + }); + this._document = ownerDocument; + } + _createCanvas(width, height) { + const canvas = this._document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + return canvas; + } +} + +;// ./src/display/cmap_reader_factory.js + + +class BaseCMapReaderFactory { + constructor({ + baseUrl = null, + isCompressed = true + }) { + this.baseUrl = baseUrl; + this.isCompressed = isCompressed; + } + async fetch({ + name + }) { + if (!this.baseUrl) { + throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided."); + } + if (!name) { + throw new Error("CMap name must be specified."); + } + const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : ""); + return this._fetch(url).then(cMapData => ({ + cMapData, + isCompressed: this.isCompressed + })).catch(reason => { + throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`); + }); + } + async _fetch(url) { + unreachable("Abstract method `_fetch` called."); + } +} +class DOMCMapReaderFactory extends BaseCMapReaderFactory { + async _fetch(url) { + const data = await fetchData(url, this.isCompressed ? "arraybuffer" : "text"); + return data instanceof ArrayBuffer ? new Uint8Array(data) : stringToBytes(data); + } +} + +;// ./src/display/filter_factory.js + + +class BaseFilterFactory { + addFilter(maps) { + return "none"; + } + addHCMFilter(fgColor, bgColor) { + return "none"; + } + addAlphaFilter(map) { + return "none"; + } + addLuminosityFilter(map) { + return "none"; + } + addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) { + return "none"; + } + destroy(keepHCM = false) {} +} +class DOMFilterFactory extends BaseFilterFactory { + #baseUrl; + #_cache; + #_defs; + #docId; + #document; + #_hcmCache; + #id = 0; + constructor({ + docId, + ownerDocument = globalThis.document + }) { + super(); + this.#docId = docId; + this.#document = ownerDocument; + } + get #cache() { + return this.#_cache ||= new Map(); + } + get #hcmCache() { + return this.#_hcmCache ||= new Map(); + } + get #defs() { + if (!this.#_defs) { + const div = this.#document.createElement("div"); + const { + style + } = div; + style.visibility = "hidden"; + style.contain = "strict"; + style.width = style.height = 0; + style.position = "absolute"; + style.top = style.left = 0; + style.zIndex = -1; + const svg = this.#document.createElementNS(SVG_NS, "svg"); + svg.setAttribute("width", 0); + svg.setAttribute("height", 0); + this.#_defs = this.#document.createElementNS(SVG_NS, "defs"); + div.append(svg); + svg.append(this.#_defs); + this.#document.body.append(div); + } + return this.#_defs; + } + #createTables(maps) { + if (maps.length === 1) { + const mapR = maps[0]; + const buffer = new Array(256); + for (let i = 0; i < 256; i++) { + buffer[i] = mapR[i] / 255; + } + const table = buffer.join(","); + return [table, table, table]; + } + const [mapR, mapG, mapB] = maps; + const bufferR = new Array(256); + const bufferG = new Array(256); + const bufferB = new Array(256); + for (let i = 0; i < 256; i++) { + bufferR[i] = mapR[i] / 255; + bufferG[i] = mapG[i] / 255; + bufferB[i] = mapB[i] / 255; + } + return [bufferR.join(","), bufferG.join(","), bufferB.join(",")]; + } + #createUrl(id) { + if (this.#baseUrl === undefined) { + this.#baseUrl = ""; + const url = this.#document.URL; + if (url !== this.#document.baseURI) { + if (isDataScheme(url)) { + warn('#createUrl: ignore "data:"-URL for performance reasons.'); + } else { + this.#baseUrl = url.split("#", 1)[0]; + } + } + } + return `url(${this.#baseUrl}#${id})`; + } + addFilter(maps) { + if (!maps) { + return "none"; + } + let value = this.#cache.get(maps); + if (value) { + return value; + } + const [tableR, tableG, tableB] = this.#createTables(maps); + const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`; + value = this.#cache.get(key); + if (value) { + this.#cache.set(maps, value); + return value; + } + const id = `g_${this.#docId}_transfer_map_${this.#id++}`; + const url = this.#createUrl(id); + this.#cache.set(maps, url); + this.#cache.set(key, url); + const filter = this.#createFilter(id); + this.#addTransferMapConversion(tableR, tableG, tableB, filter); + return url; + } + addHCMFilter(fgColor, bgColor) { + const key = `${fgColor}-${bgColor}`; + const filterName = "base"; + let info = this.#hcmCache.get(filterName); + if (info?.key === key) { + return info.url; + } + if (info) { + info.filter?.remove(); + info.key = key; + info.url = "none"; + info.filter = null; + } else { + info = { + key, + url: "none", + filter: null + }; + this.#hcmCache.set(filterName, info); + } + if (!fgColor || !bgColor) { + return info.url; + } + const fgRGB = this.#getRGB(fgColor); + fgColor = Util.makeHexColor(...fgRGB); + const bgRGB = this.#getRGB(bgColor); + bgColor = Util.makeHexColor(...bgRGB); + this.#defs.style.color = ""; + if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) { + return info.url; + } + const map = new Array(256); + for (let i = 0; i <= 255; i++) { + const x = i / 255; + map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4; + } + const table = map.join(","); + const id = `g_${this.#docId}_hcm_filter`; + const filter = info.filter = this.#createFilter(id); + this.#addTransferMapConversion(table, table, table, filter); + this.#addGrayConversion(filter); + const getSteps = (c, n) => { + const start = fgRGB[c] / 255; + const end = bgRGB[c] / 255; + const arr = new Array(n + 1); + for (let i = 0; i <= n; i++) { + arr[i] = start + i / n * (end - start); + } + return arr.join(","); + }; + this.#addTransferMapConversion(getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter); + info.url = this.#createUrl(id); + return info.url; + } + addAlphaFilter(map) { + let value = this.#cache.get(map); + if (value) { + return value; + } + const [tableA] = this.#createTables([map]); + const key = `alpha_${tableA}`; + value = this.#cache.get(key); + if (value) { + this.#cache.set(map, value); + return value; + } + const id = `g_${this.#docId}_alpha_map_${this.#id++}`; + const url = this.#createUrl(id); + this.#cache.set(map, url); + this.#cache.set(key, url); + const filter = this.#createFilter(id); + this.#addTransferMapAlphaConversion(tableA, filter); + return url; + } + addLuminosityFilter(map) { + let value = this.#cache.get(map || "luminosity"); + if (value) { + return value; + } + let tableA, key; + if (map) { + [tableA] = this.#createTables([map]); + key = `luminosity_${tableA}`; + } else { + key = "luminosity"; + } + value = this.#cache.get(key); + if (value) { + this.#cache.set(map, value); + return value; + } + const id = `g_${this.#docId}_luminosity_map_${this.#id++}`; + const url = this.#createUrl(id); + this.#cache.set(map, url); + this.#cache.set(key, url); + const filter = this.#createFilter(id); + this.#addLuminosityConversion(filter); + if (map) { + this.#addTransferMapAlphaConversion(tableA, filter); + } + return url; + } + addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) { + const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`; + let info = this.#hcmCache.get(filterName); + if (info?.key === key) { + return info.url; + } + if (info) { + info.filter?.remove(); + info.key = key; + info.url = "none"; + info.filter = null; + } else { + info = { + key, + url: "none", + filter: null + }; + this.#hcmCache.set(filterName, info); + } + if (!fgColor || !bgColor) { + return info.url; + } + const [fgRGB, bgRGB] = [fgColor, bgColor].map(this.#getRGB.bind(this)); + let fgGray = Math.round(0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]); + let bgGray = Math.round(0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]); + let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(this.#getRGB.bind(this)); + if (bgGray < fgGray) { + [fgGray, bgGray, newFgRGB, newBgRGB] = [bgGray, fgGray, newBgRGB, newFgRGB]; + } + this.#defs.style.color = ""; + const getSteps = (fg, bg, n) => { + const arr = new Array(256); + const step = (bgGray - fgGray) / n; + const newStart = fg / 255; + const newStep = (bg - fg) / (255 * n); + let prev = 0; + for (let i = 0; i <= n; i++) { + const k = Math.round(fgGray + i * step); + const value = newStart + i * newStep; + for (let j = prev; j <= k; j++) { + arr[j] = value; + } + prev = k + 1; + } + for (let i = prev; i < 256; i++) { + arr[i] = arr[prev - 1]; + } + return arr.join(","); + }; + const id = `g_${this.#docId}_hcm_${filterName}_filter`; + const filter = info.filter = this.#createFilter(id); + this.#addGrayConversion(filter); + this.#addTransferMapConversion(getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter); + info.url = this.#createUrl(id); + return info.url; + } + destroy(keepHCM = false) { + if (keepHCM && this.#_hcmCache?.size) { + return; + } + this.#_defs?.parentNode.parentNode.remove(); + this.#_defs = null; + this.#_cache?.clear(); + this.#_cache = null; + this.#_hcmCache?.clear(); + this.#_hcmCache = null; + this.#id = 0; + } + #addLuminosityConversion(filter) { + const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix"); + feColorMatrix.setAttribute("type", "matrix"); + feColorMatrix.setAttribute("values", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"); + filter.append(feColorMatrix); + } + #addGrayConversion(filter) { + const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix"); + feColorMatrix.setAttribute("type", "matrix"); + feColorMatrix.setAttribute("values", "0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"); + filter.append(feColorMatrix); + } + #createFilter(id) { + const filter = this.#document.createElementNS(SVG_NS, "filter"); + filter.setAttribute("color-interpolation-filters", "sRGB"); + filter.setAttribute("id", id); + this.#defs.append(filter); + return filter; + } + #appendFeFunc(feComponentTransfer, func, table) { + const feFunc = this.#document.createElementNS(SVG_NS, func); + feFunc.setAttribute("type", "discrete"); + feFunc.setAttribute("tableValues", table); + feComponentTransfer.append(feFunc); + } + #addTransferMapConversion(rTable, gTable, bTable, filter) { + const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer"); + filter.append(feComponentTransfer); + this.#appendFeFunc(feComponentTransfer, "feFuncR", rTable); + this.#appendFeFunc(feComponentTransfer, "feFuncG", gTable); + this.#appendFeFunc(feComponentTransfer, "feFuncB", bTable); + } + #addTransferMapAlphaConversion(aTable, filter) { + const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer"); + filter.append(feComponentTransfer); + this.#appendFeFunc(feComponentTransfer, "feFuncA", aTable); + } + #getRGB(color) { + this.#defs.style.color = color; + return getRGB(getComputedStyle(this.#defs).getPropertyValue("color")); + } +} + +;// ./src/display/standard_fontdata_factory.js + + +class BaseStandardFontDataFactory { + constructor({ + baseUrl = null + }) { + this.baseUrl = baseUrl; + } + async fetch({ + filename + }) { + if (!this.baseUrl) { + throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided."); + } + if (!filename) { + throw new Error("Font filename must be specified."); + } + const url = `${this.baseUrl}${filename}`; + return this._fetch(url).catch(reason => { + throw new Error(`Unable to load font data at: ${url}`); + }); + } + async _fetch(url) { + unreachable("Abstract method `_fetch` called."); + } +} +class DOMStandardFontDataFactory extends BaseStandardFontDataFactory { + async _fetch(url) { + const data = await fetchData(url, "arraybuffer"); + return new Uint8Array(data); + } +} + +;// ./src/display/node_utils.js + + + + + +async function node_utils_fetchData(url) { + const fs = process.getBuiltinModule("fs"); + const data = await fs.promises.readFile(url); + return new Uint8Array(data); +} +class NodeFilterFactory extends BaseFilterFactory {} +class NodeCanvasFactory extends BaseCanvasFactory { + _createCanvas(width, height) { + const require = process.getBuiltinModule("module").createRequire(import.meta.url); + const canvas = require("@napi-rs/canvas"); + return canvas.createCanvas(width, height); + } +} +class NodeCMapReaderFactory extends BaseCMapReaderFactory { + async _fetch(url) { + return node_utils_fetchData(url); + } +} +class NodeStandardFontDataFactory extends BaseStandardFontDataFactory { + async _fetch(url) { + return node_utils_fetchData(url); + } +} + +;// ./src/display/pattern_helper.js + + +const PathType = { + FILL: "Fill", + STROKE: "Stroke", + SHADING: "Shading" +}; +function applyBoundingBox(ctx, bbox) { + if (!bbox) { + return; + } + const width = bbox[2] - bbox[0]; + const height = bbox[3] - bbox[1]; + const region = new Path2D(); + region.rect(bbox[0], bbox[1], width, height); + ctx.clip(region); +} +class BaseShadingPattern { + getPattern() { + unreachable("Abstract method `getPattern` called."); + } +} +class RadialAxialShadingPattern extends BaseShadingPattern { + constructor(IR) { + super(); + this._type = IR[1]; + this._bbox = IR[2]; + this._colorStops = IR[3]; + this._p0 = IR[4]; + this._p1 = IR[5]; + this._r0 = IR[6]; + this._r1 = IR[7]; + this.matrix = null; + } + _createGradient(ctx) { + let grad; + if (this._type === "axial") { + grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]); + } else if (this._type === "radial") { + grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1); + } + for (const colorStop of this._colorStops) { + grad.addColorStop(colorStop[0], colorStop[1]); + } + return grad; + } + getPattern(ctx, owner, inverse, pathType) { + let pattern; + if (pathType === PathType.STROKE || pathType === PathType.FILL) { + const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, getCurrentTransform(ctx)) || [0, 0, 0, 0]; + const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1; + const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1; + const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height); + const tmpCtx = tmpCanvas.context; + tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height); + tmpCtx.beginPath(); + tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height); + tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]); + inverse = Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]); + tmpCtx.transform(...owner.baseTransform); + if (this.matrix) { + tmpCtx.transform(...this.matrix); + } + applyBoundingBox(tmpCtx, this._bbox); + tmpCtx.fillStyle = this._createGradient(tmpCtx); + tmpCtx.fill(); + pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat"); + const domMatrix = new DOMMatrix(inverse); + pattern.setTransform(domMatrix); + } else { + applyBoundingBox(ctx, this._bbox); + pattern = this._createGradient(ctx); + } + return pattern; + } +} +function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) { + const coords = context.coords, + colors = context.colors; + const bytes = data.data, + rowSize = data.width * 4; + let tmp; + if (coords[p1 + 1] > coords[p2 + 1]) { + tmp = p1; + p1 = p2; + p2 = tmp; + tmp = c1; + c1 = c2; + c2 = tmp; + } + if (coords[p2 + 1] > coords[p3 + 1]) { + tmp = p2; + p2 = p3; + p3 = tmp; + tmp = c2; + c2 = c3; + c3 = tmp; + } + if (coords[p1 + 1] > coords[p2 + 1]) { + tmp = p1; + p1 = p2; + p2 = tmp; + tmp = c1; + c1 = c2; + c2 = tmp; + } + const x1 = (coords[p1] + context.offsetX) * context.scaleX; + const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY; + const x2 = (coords[p2] + context.offsetX) * context.scaleX; + const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY; + const x3 = (coords[p3] + context.offsetX) * context.scaleX; + const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY; + if (y1 >= y3) { + return; + } + const c1r = colors[c1], + c1g = colors[c1 + 1], + c1b = colors[c1 + 2]; + const c2r = colors[c2], + c2g = colors[c2 + 1], + c2b = colors[c2 + 2]; + const c3r = colors[c3], + c3g = colors[c3 + 1], + c3b = colors[c3 + 2]; + const minY = Math.round(y1), + maxY = Math.round(y3); + let xa, car, cag, cab; + let xb, cbr, cbg, cbb; + for (let y = minY; y <= maxY; y++) { + if (y < y2) { + const k = y < y1 ? 0 : (y1 - y) / (y1 - y2); + xa = x1 - (x1 - x2) * k; + car = c1r - (c1r - c2r) * k; + cag = c1g - (c1g - c2g) * k; + cab = c1b - (c1b - c2b) * k; + } else { + let k; + if (y > y3) { + k = 1; + } else if (y2 === y3) { + k = 0; + } else { + k = (y2 - y) / (y2 - y3); + } + xa = x2 - (x2 - x3) * k; + car = c2r - (c2r - c3r) * k; + cag = c2g - (c2g - c3g) * k; + cab = c2b - (c2b - c3b) * k; + } + let k; + if (y < y1) { + k = 0; + } else if (y > y3) { + k = 1; + } else { + k = (y1 - y) / (y1 - y3); + } + xb = x1 - (x1 - x3) * k; + cbr = c1r - (c1r - c3r) * k; + cbg = c1g - (c1g - c3g) * k; + cbb = c1b - (c1b - c3b) * k; + const x1_ = Math.round(Math.min(xa, xb)); + const x2_ = Math.round(Math.max(xa, xb)); + let j = rowSize * y + x1_ * 4; + for (let x = x1_; x <= x2_; x++) { + k = (xa - x) / (xa - xb); + if (k < 0) { + k = 0; + } else if (k > 1) { + k = 1; + } + bytes[j++] = car - (car - cbr) * k | 0; + bytes[j++] = cag - (cag - cbg) * k | 0; + bytes[j++] = cab - (cab - cbb) * k | 0; + bytes[j++] = 255; + } + } +} +function drawFigure(data, figure, context) { + const ps = figure.coords; + const cs = figure.colors; + let i, ii; + switch (figure.type) { + case "lattice": + const verticesPerRow = figure.verticesPerRow; + const rows = Math.floor(ps.length / verticesPerRow) - 1; + const cols = verticesPerRow - 1; + for (i = 0; i < rows; i++) { + let q = i * verticesPerRow; + for (let j = 0; j < cols; j++, q++) { + drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]); + drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]); + } + } + break; + case "triangles": + for (i = 0, ii = ps.length; i < ii; i += 3) { + drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]); + } + break; + default: + throw new Error("illegal figure"); + } +} +class MeshShadingPattern extends BaseShadingPattern { + constructor(IR) { + super(); + this._coords = IR[2]; + this._colors = IR[3]; + this._figures = IR[4]; + this._bounds = IR[5]; + this._bbox = IR[7]; + this._background = IR[8]; + this.matrix = null; + } + _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) { + const EXPECTED_SCALE = 1.1; + const MAX_PATTERN_SIZE = 3000; + const BORDER_SIZE = 2; + const offsetX = Math.floor(this._bounds[0]); + const offsetY = Math.floor(this._bounds[1]); + const boundsWidth = Math.ceil(this._bounds[2]) - offsetX; + const boundsHeight = Math.ceil(this._bounds[3]) - offsetY; + const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); + const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); + const scaleX = boundsWidth / width; + const scaleY = boundsHeight / height; + const context = { + coords: this._coords, + colors: this._colors, + offsetX: -offsetX, + offsetY: -offsetY, + scaleX: 1 / scaleX, + scaleY: 1 / scaleY + }; + const paddedWidth = width + BORDER_SIZE * 2; + const paddedHeight = height + BORDER_SIZE * 2; + const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight); + const tmpCtx = tmpCanvas.context; + const data = tmpCtx.createImageData(width, height); + if (backgroundColor) { + const bytes = data.data; + for (let i = 0, ii = bytes.length; i < ii; i += 4) { + bytes[i] = backgroundColor[0]; + bytes[i + 1] = backgroundColor[1]; + bytes[i + 2] = backgroundColor[2]; + bytes[i + 3] = 255; + } + } + for (const figure of this._figures) { + drawFigure(data, figure, context); + } + tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE); + const canvas = tmpCanvas.canvas; + return { + canvas, + offsetX: offsetX - BORDER_SIZE * scaleX, + offsetY: offsetY - BORDER_SIZE * scaleY, + scaleX, + scaleY + }; + } + getPattern(ctx, owner, inverse, pathType) { + applyBoundingBox(ctx, this._bbox); + let scale; + if (pathType === PathType.SHADING) { + scale = Util.singularValueDecompose2dScale(getCurrentTransform(ctx)); + } else { + scale = Util.singularValueDecompose2dScale(owner.baseTransform); + if (this.matrix) { + const matrixScale = Util.singularValueDecompose2dScale(this.matrix); + scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]]; + } + } + const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases); + if (pathType !== PathType.SHADING) { + ctx.setTransform(...owner.baseTransform); + if (this.matrix) { + ctx.transform(...this.matrix); + } + } + ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); + ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY); + return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat"); + } +} +class DummyShadingPattern extends BaseShadingPattern { + getPattern() { + return "hotpink"; + } +} +function getShadingPattern(IR) { + switch (IR[0]) { + case "RadialAxial": + return new RadialAxialShadingPattern(IR); + case "Mesh": + return new MeshShadingPattern(IR); + case "Dummy": + return new DummyShadingPattern(); + } + throw new Error(`Unknown IR type: ${IR[0]}`); +} +const PaintType = { + COLORED: 1, + UNCOLORED: 2 +}; +class TilingPattern { + static MAX_PATTERN_SIZE = 3000; + constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) { + this.operatorList = IR[2]; + this.matrix = IR[3]; + this.bbox = IR[4]; + this.xstep = IR[5]; + this.ystep = IR[6]; + this.paintType = IR[7]; + this.tilingType = IR[8]; + this.color = color; + this.ctx = ctx; + this.canvasGraphicsFactory = canvasGraphicsFactory; + this.baseTransform = baseTransform; + } + createPatternCanvas(owner) { + const { + bbox, + operatorList, + paintType, + tilingType, + color, + canvasGraphicsFactory + } = this; + let { + xstep, + ystep + } = this; + xstep = Math.abs(xstep); + ystep = Math.abs(ystep); + info("TilingType: " + tilingType); + const x0 = bbox[0], + y0 = bbox[1], + x1 = bbox[2], + y1 = bbox[3]; + const width = x1 - x0; + const height = y1 - y0; + const matrixScale = Util.singularValueDecompose2dScale(this.matrix); + const curMatrixScale = Util.singularValueDecompose2dScale(this.baseTransform); + const combinedScaleX = matrixScale[0] * curMatrixScale[0]; + const combinedScaleY = matrixScale[1] * curMatrixScale[1]; + let canvasWidth = width, + canvasHeight = height, + redrawHorizontally = false, + redrawVertically = false; + const xScaledStep = Math.ceil(xstep * combinedScaleX); + const yScaledStep = Math.ceil(ystep * combinedScaleY); + const xScaledWidth = Math.ceil(width * combinedScaleX); + const yScaledHeight = Math.ceil(height * combinedScaleY); + if (xScaledStep >= xScaledWidth) { + canvasWidth = xstep; + } else { + redrawHorizontally = true; + } + if (yScaledStep >= yScaledHeight) { + canvasHeight = ystep; + } else { + redrawVertically = true; + } + const dimx = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX); + const dimy = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY); + const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size); + const tmpCtx = tmpCanvas.context; + const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx); + graphics.groupLevel = owner.groupLevel; + this.setFillAndStrokeStyleToContext(graphics, paintType, color); + tmpCtx.translate(-dimx.scale * x0, -dimy.scale * y0); + graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0); + tmpCtx.save(); + this.clipBbox(graphics, x0, y0, x1, y1); + graphics.baseTransform = getCurrentTransform(graphics.ctx); + graphics.executeOperatorList(operatorList); + graphics.endDrawing(); + tmpCtx.restore(); + if (redrawHorizontally || redrawVertically) { + const image = tmpCanvas.canvas; + if (redrawHorizontally) { + canvasWidth = xstep; + } + if (redrawVertically) { + canvasHeight = ystep; + } + const dimx2 = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX); + const dimy2 = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY); + const xSize = dimx2.size; + const ySize = dimy2.size; + const tmpCanvas2 = owner.cachedCanvases.getCanvas("pattern-workaround", xSize, ySize); + const tmpCtx2 = tmpCanvas2.context; + const ii = redrawHorizontally ? Math.floor(width / xstep) : 0; + const jj = redrawVertically ? Math.floor(height / ystep) : 0; + for (let i = 0; i <= ii; i++) { + for (let j = 0; j <= jj; j++) { + tmpCtx2.drawImage(image, xSize * i, ySize * j, xSize, ySize, 0, 0, xSize, ySize); + } + } + return { + canvas: tmpCanvas2.canvas, + scaleX: dimx2.scale, + scaleY: dimy2.scale, + offsetX: x0, + offsetY: y0 + }; + } + return { + canvas: tmpCanvas.canvas, + scaleX: dimx.scale, + scaleY: dimy.scale, + offsetX: x0, + offsetY: y0 + }; + } + getSizeAndScale(step, realOutputSize, scale) { + const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize); + let size = Math.ceil(step * scale); + if (size >= maxSize) { + size = maxSize; + } else { + scale = size / step; + } + return { + scale, + size + }; + } + clipBbox(graphics, x0, y0, x1, y1) { + const bboxWidth = x1 - x0; + const bboxHeight = y1 - y0; + graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight); + graphics.current.updateRectMinMax(getCurrentTransform(graphics.ctx), [x0, y0, x1, y1]); + graphics.clip(); + graphics.endPath(); + } + setFillAndStrokeStyleToContext(graphics, paintType, color) { + const context = graphics.ctx, + current = graphics.current; + switch (paintType) { + case PaintType.COLORED: + const ctx = this.ctx; + context.fillStyle = ctx.fillStyle; + context.strokeStyle = ctx.strokeStyle; + current.fillColor = ctx.fillStyle; + current.strokeColor = ctx.strokeStyle; + break; + case PaintType.UNCOLORED: + const cssColor = Util.makeHexColor(color[0], color[1], color[2]); + context.fillStyle = cssColor; + context.strokeStyle = cssColor; + current.fillColor = cssColor; + current.strokeColor = cssColor; + break; + default: + throw new FormatError(`Unsupported paint type: ${paintType}`); + } + } + getPattern(ctx, owner, inverse, pathType) { + let matrix = inverse; + if (pathType !== PathType.SHADING) { + matrix = Util.transform(matrix, owner.baseTransform); + if (this.matrix) { + matrix = Util.transform(matrix, this.matrix); + } + } + const temporaryPatternCanvas = this.createPatternCanvas(owner); + let domMatrix = new DOMMatrix(matrix); + domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); + domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY); + const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat"); + pattern.setTransform(domMatrix); + return pattern; + } +} + +;// ./src/shared/image_utils.js + +function convertToRGBA(params) { + switch (params.kind) { + case ImageKind.GRAYSCALE_1BPP: + return convertBlackAndWhiteToRGBA(params); + case ImageKind.RGB_24BPP: + return convertRGBToRGBA(params); + } + return null; +} +function convertBlackAndWhiteToRGBA({ + src, + srcPos = 0, + dest, + width, + height, + nonBlackColor = 0xffffffff, + inverseDecode = false +}) { + const black = util_FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff; + const [zeroMapping, oneMapping] = inverseDecode ? [nonBlackColor, black] : [black, nonBlackColor]; + const widthInSource = width >> 3; + const widthRemainder = width & 7; + const srcLength = src.length; + dest = new Uint32Array(dest.buffer); + let destPos = 0; + for (let i = 0; i < height; i++) { + for (const max = srcPos + widthInSource; srcPos < max; srcPos++) { + const elem = srcPos < srcLength ? src[srcPos] : 255; + dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping; + dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping; + dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping; + dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping; + dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping; + dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping; + dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping; + dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping; + } + if (widthRemainder === 0) { + continue; + } + const elem = srcPos < srcLength ? src[srcPos++] : 255; + for (let j = 0; j < widthRemainder; j++) { + dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping; + } + } + return { + srcPos, + destPos + }; +} +function convertRGBToRGBA({ + src, + srcPos = 0, + dest, + destPos = 0, + width, + height +}) { + let i = 0; + const len = width * height * 3; + const len32 = len >> 2; + const src32 = new Uint32Array(src.buffer, srcPos, len32); + if (FeatureTest.isLittleEndian) { + for (; i < len32 - 2; i += 3, destPos += 4) { + const s1 = src32[i]; + const s2 = src32[i + 1]; + const s3 = src32[i + 2]; + dest[destPos] = s1 | 0xff000000; + dest[destPos + 1] = s1 >>> 24 | s2 << 8 | 0xff000000; + dest[destPos + 2] = s2 >>> 16 | s3 << 16 | 0xff000000; + dest[destPos + 3] = s3 >>> 8 | 0xff000000; + } + for (let j = i * 4, jj = srcPos + len; j < jj; j += 3) { + dest[destPos++] = src[j] | src[j + 1] << 8 | src[j + 2] << 16 | 0xff000000; + } + } else { + for (; i < len32 - 2; i += 3, destPos += 4) { + const s1 = src32[i]; + const s2 = src32[i + 1]; + const s3 = src32[i + 2]; + dest[destPos] = s1 | 0xff; + dest[destPos + 1] = s1 << 24 | s2 >>> 8 | 0xff; + dest[destPos + 2] = s2 << 16 | s3 >>> 16 | 0xff; + dest[destPos + 3] = s3 << 8 | 0xff; + } + for (let j = i * 4, jj = srcPos + len; j < jj; j += 3) { + dest[destPos++] = src[j] << 24 | src[j + 1] << 16 | src[j + 2] << 8 | 0xff; + } + } + return { + srcPos: srcPos + len, + destPos + }; +} +function grayToRGBA(src, dest) { + if (FeatureTest.isLittleEndian) { + for (let i = 0, ii = src.length; i < ii; i++) { + dest[i] = src[i] * 0x10101 | 0xff000000; + } + } else { + for (let i = 0, ii = src.length; i < ii; i++) { + dest[i] = src[i] * 0x1010100 | 0x000000ff; + } + } +} + +;// ./src/display/canvas.js + + + + +const MIN_FONT_SIZE = 16; +const MAX_FONT_SIZE = 100; +const EXECUTION_TIME = 15; +const EXECUTION_STEPS = 10; +const MAX_SIZE_TO_COMPILE = 1000; +const FULL_CHUNK_HEIGHT = 16; +function mirrorContextOperations(ctx, destCtx) { + if (ctx._removeMirroring) { + throw new Error("Context is already forwarding operations."); + } + ctx.__originalSave = ctx.save; + ctx.__originalRestore = ctx.restore; + ctx.__originalRotate = ctx.rotate; + ctx.__originalScale = ctx.scale; + ctx.__originalTranslate = ctx.translate; + ctx.__originalTransform = ctx.transform; + ctx.__originalSetTransform = ctx.setTransform; + ctx.__originalResetTransform = ctx.resetTransform; + ctx.__originalClip = ctx.clip; + ctx.__originalMoveTo = ctx.moveTo; + ctx.__originalLineTo = ctx.lineTo; + ctx.__originalBezierCurveTo = ctx.bezierCurveTo; + ctx.__originalRect = ctx.rect; + ctx.__originalClosePath = ctx.closePath; + ctx.__originalBeginPath = ctx.beginPath; + ctx._removeMirroring = () => { + ctx.save = ctx.__originalSave; + ctx.restore = ctx.__originalRestore; + ctx.rotate = ctx.__originalRotate; + ctx.scale = ctx.__originalScale; + ctx.translate = ctx.__originalTranslate; + ctx.transform = ctx.__originalTransform; + ctx.setTransform = ctx.__originalSetTransform; + ctx.resetTransform = ctx.__originalResetTransform; + ctx.clip = ctx.__originalClip; + ctx.moveTo = ctx.__originalMoveTo; + ctx.lineTo = ctx.__originalLineTo; + ctx.bezierCurveTo = ctx.__originalBezierCurveTo; + ctx.rect = ctx.__originalRect; + ctx.closePath = ctx.__originalClosePath; + ctx.beginPath = ctx.__originalBeginPath; + delete ctx._removeMirroring; + }; + ctx.save = function ctxSave() { + destCtx.save(); + this.__originalSave(); + }; + ctx.restore = function ctxRestore() { + destCtx.restore(); + this.__originalRestore(); + }; + ctx.translate = function ctxTranslate(x, y) { + destCtx.translate(x, y); + this.__originalTranslate(x, y); + }; + ctx.scale = function ctxScale(x, y) { + destCtx.scale(x, y); + this.__originalScale(x, y); + }; + ctx.transform = function ctxTransform(a, b, c, d, e, f) { + destCtx.transform(a, b, c, d, e, f); + this.__originalTransform(a, b, c, d, e, f); + }; + ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) { + destCtx.setTransform(a, b, c, d, e, f); + this.__originalSetTransform(a, b, c, d, e, f); + }; + ctx.resetTransform = function ctxResetTransform() { + destCtx.resetTransform(); + this.__originalResetTransform(); + }; + ctx.rotate = function ctxRotate(angle) { + destCtx.rotate(angle); + this.__originalRotate(angle); + }; + ctx.clip = function ctxRotate(rule) { + destCtx.clip(rule); + this.__originalClip(rule); + }; + ctx.moveTo = function (x, y) { + destCtx.moveTo(x, y); + this.__originalMoveTo(x, y); + }; + ctx.lineTo = function (x, y) { + destCtx.lineTo(x, y); + this.__originalLineTo(x, y); + }; + ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) { + destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y); + this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y); + }; + ctx.rect = function (x, y, width, height) { + destCtx.rect(x, y, width, height); + this.__originalRect(x, y, width, height); + }; + ctx.closePath = function () { + destCtx.closePath(); + this.__originalClosePath(); + }; + ctx.beginPath = function () { + destCtx.beginPath(); + this.__originalBeginPath(); + }; +} +class CachedCanvases { + constructor(canvasFactory) { + this.canvasFactory = canvasFactory; + this.cache = Object.create(null); + } + getCanvas(id, width, height) { + let canvasEntry; + if (this.cache[id] !== undefined) { + canvasEntry = this.cache[id]; + this.canvasFactory.reset(canvasEntry, width, height); + } else { + canvasEntry = this.canvasFactory.create(width, height); + this.cache[id] = canvasEntry; + } + return canvasEntry; + } + delete(id) { + delete this.cache[id]; + } + clear() { + for (const id in this.cache) { + const canvasEntry = this.cache[id]; + this.canvasFactory.destroy(canvasEntry); + delete this.cache[id]; + } + } +} +function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) { + const [a, b, c, d, tx, ty] = getCurrentTransform(ctx); + if (b === 0 && c === 0) { + const tlX = destX * a + tx; + const rTlX = Math.round(tlX); + const tlY = destY * d + ty; + const rTlY = Math.round(tlY); + const brX = (destX + destW) * a + tx; + const rWidth = Math.abs(Math.round(brX) - rTlX) || 1; + const brY = (destY + destH) * d + ty; + const rHeight = Math.abs(Math.round(brY) - rTlY) || 1; + ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY); + ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight); + ctx.setTransform(a, b, c, d, tx, ty); + return [rWidth, rHeight]; + } + if (a === 0 && d === 0) { + const tlX = destY * c + tx; + const rTlX = Math.round(tlX); + const tlY = destX * b + ty; + const rTlY = Math.round(tlY); + const brX = (destY + destH) * c + tx; + const rWidth = Math.abs(Math.round(brX) - rTlX) || 1; + const brY = (destX + destW) * b + ty; + const rHeight = Math.abs(Math.round(brY) - rTlY) || 1; + ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY); + ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth); + ctx.setTransform(a, b, c, d, tx, ty); + return [rHeight, rWidth]; + } + ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH); + const scaleX = Math.hypot(a, b); + const scaleY = Math.hypot(c, d); + return [scaleX * destW, scaleY * destH]; +} +function compileType3Glyph(imgData) { + const { + width, + height + } = imgData; + if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) { + return null; + } + const POINT_TO_PROCESS_LIMIT = 1000; + const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]); + const width1 = width + 1; + let points = new Uint8Array(width1 * (height + 1)); + let i, j, j0; + const lineSize = width + 7 & ~7; + let data = new Uint8Array(lineSize * height), + pos = 0; + for (const elem of imgData.data) { + let mask = 128; + while (mask > 0) { + data[pos++] = elem & mask ? 0 : 255; + mask >>= 1; + } + } + let count = 0; + pos = 0; + if (data[pos] !== 0) { + points[0] = 1; + ++count; + } + for (j = 1; j < width; j++) { + if (data[pos] !== data[pos + 1]) { + points[j] = data[pos] ? 2 : 1; + ++count; + } + pos++; + } + if (data[pos] !== 0) { + points[j] = 2; + ++count; + } + for (i = 1; i < height; i++) { + pos = i * lineSize; + j0 = i * width1; + if (data[pos - lineSize] !== data[pos]) { + points[j0] = data[pos] ? 1 : 8; + ++count; + } + let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0); + for (j = 1; j < width; j++) { + sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0); + if (POINT_TYPES[sum]) { + points[j0 + j] = POINT_TYPES[sum]; + ++count; + } + pos++; + } + if (data[pos - lineSize] !== data[pos]) { + points[j0 + j] = data[pos] ? 2 : 4; + ++count; + } + if (count > POINT_TO_PROCESS_LIMIT) { + return null; + } + } + pos = lineSize * (height - 1); + j0 = i * width1; + if (data[pos] !== 0) { + points[j0] = 8; + ++count; + } + for (j = 1; j < width; j++) { + if (data[pos] !== data[pos + 1]) { + points[j0 + j] = data[pos] ? 4 : 8; + ++count; + } + pos++; + } + if (data[pos] !== 0) { + points[j0 + j] = 4; + ++count; + } + if (count > POINT_TO_PROCESS_LIMIT) { + return null; + } + const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]); + const path = new Path2D(); + for (i = 0; count && i <= height; i++) { + let p = i * width1; + const end = p + width; + while (p < end && !points[p]) { + p++; + } + if (p === end) { + continue; + } + path.moveTo(p % width1, i); + const p0 = p; + let type = points[p]; + do { + const step = steps[type]; + do { + p += step; + } while (!points[p]); + const pp = points[p]; + if (pp !== 5 && pp !== 10) { + type = pp; + points[p] = 0; + } else { + type = pp & 0x33 * type >> 4; + points[p] &= type >> 2 | type << 2; + } + path.lineTo(p % width1, p / width1 | 0); + if (!points[p]) { + --count; + } + } while (p0 !== p); + --i; + } + data = null; + points = null; + const drawOutline = function (c) { + c.save(); + c.scale(1 / width, -1 / height); + c.translate(0, -height); + c.fill(path); + c.beginPath(); + c.restore(); + }; + return drawOutline; +} +class CanvasExtraState { + constructor(width, height) { + this.alphaIsShape = false; + this.fontSize = 0; + this.fontSizeScale = 1; + this.textMatrix = IDENTITY_MATRIX; + this.textMatrixScale = 1; + this.fontMatrix = FONT_IDENTITY_MATRIX; + this.leading = 0; + this.x = 0; + this.y = 0; + this.lineX = 0; + this.lineY = 0; + this.charSpacing = 0; + this.wordSpacing = 0; + this.textHScale = 1; + this.textRenderingMode = TextRenderingMode.FILL; + this.textRise = 0; + this.fillColor = "#000000"; + this.strokeColor = "#000000"; + this.patternFill = false; + this.patternStroke = false; + this.fillAlpha = 1; + this.strokeAlpha = 1; + this.lineWidth = 1; + this.activeSMask = null; + this.transferMaps = "none"; + this.startNewPathAndClipBox([0, 0, width, height]); + } + clone() { + const clone = Object.create(this); + clone.clipBox = this.clipBox.slice(); + return clone; + } + setCurrentPoint(x, y) { + this.x = x; + this.y = y; + } + updatePathMinMax(transform, x, y) { + [x, y] = Util.applyTransform([x, y], transform); + this.minX = Math.min(this.minX, x); + this.minY = Math.min(this.minY, y); + this.maxX = Math.max(this.maxX, x); + this.maxY = Math.max(this.maxY, y); + } + updateRectMinMax(transform, rect) { + const p1 = Util.applyTransform(rect, transform); + const p2 = Util.applyTransform(rect.slice(2), transform); + const p3 = Util.applyTransform([rect[0], rect[3]], transform); + const p4 = Util.applyTransform([rect[2], rect[1]], transform); + this.minX = Math.min(this.minX, p1[0], p2[0], p3[0], p4[0]); + this.minY = Math.min(this.minY, p1[1], p2[1], p3[1], p4[1]); + this.maxX = Math.max(this.maxX, p1[0], p2[0], p3[0], p4[0]); + this.maxY = Math.max(this.maxY, p1[1], p2[1], p3[1], p4[1]); + } + updateScalingPathMinMax(transform, minMax) { + Util.scaleMinMax(transform, minMax); + this.minX = Math.min(this.minX, minMax[0]); + this.minY = Math.min(this.minY, minMax[1]); + this.maxX = Math.max(this.maxX, minMax[2]); + this.maxY = Math.max(this.maxY, minMax[3]); + } + updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) { + const box = Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax); + if (minMax) { + return; + } + this.updateRectMinMax(transform, box); + } + getPathBoundingBox(pathType = PathType.FILL, transform = null) { + const box = [this.minX, this.minY, this.maxX, this.maxY]; + if (pathType === PathType.STROKE) { + if (!transform) { + unreachable("Stroke bounding box must include transform."); + } + const scale = Util.singularValueDecompose2dScale(transform); + const xStrokePad = scale[0] * this.lineWidth / 2; + const yStrokePad = scale[1] * this.lineWidth / 2; + box[0] -= xStrokePad; + box[1] -= yStrokePad; + box[2] += xStrokePad; + box[3] += yStrokePad; + } + return box; + } + updateClipFromPath() { + const intersect = Util.intersect(this.clipBox, this.getPathBoundingBox()); + this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]); + } + isEmptyClip() { + return this.minX === Infinity; + } + startNewPathAndClipBox(box) { + this.clipBox = box; + this.minX = Infinity; + this.minY = Infinity; + this.maxX = 0; + this.maxY = 0; + } + getClippedPathBoundingBox(pathType = PathType.FILL, transform = null) { + return Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform)); + } +} +function putBinaryImageData(ctx, imgData) { + if (imgData instanceof ImageData) { + ctx.putImageData(imgData, 0, 0); + return; + } + const height = imgData.height, + width = imgData.width; + const partialChunkHeight = height % FULL_CHUNK_HEIGHT; + const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; + const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; + const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); + let srcPos = 0, + destPos; + const src = imgData.data; + const dest = chunkImgData.data; + let i, j, thisChunkHeight, elemsInThisChunk; + if (imgData.kind === util_ImageKind.GRAYSCALE_1BPP) { + const srcLength = src.byteLength; + const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2); + const dest32DataLength = dest32.length; + const fullSrcDiff = width + 7 >> 3; + const white = 0xffffffff; + const black = util_FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff; + for (i = 0; i < totalChunks; i++) { + thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight; + destPos = 0; + for (j = 0; j < thisChunkHeight; j++) { + const srcDiff = srcLength - srcPos; + let k = 0; + const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7; + const kEndUnrolled = kEnd & ~7; + let mask = 0; + let srcByte = 0; + for (; k < kEndUnrolled; k += 8) { + srcByte = src[srcPos++]; + dest32[destPos++] = srcByte & 128 ? white : black; + dest32[destPos++] = srcByte & 64 ? white : black; + dest32[destPos++] = srcByte & 32 ? white : black; + dest32[destPos++] = srcByte & 16 ? white : black; + dest32[destPos++] = srcByte & 8 ? white : black; + dest32[destPos++] = srcByte & 4 ? white : black; + dest32[destPos++] = srcByte & 2 ? white : black; + dest32[destPos++] = srcByte & 1 ? white : black; + } + for (; k < kEnd; k++) { + if (mask === 0) { + srcByte = src[srcPos++]; + mask = 128; + } + dest32[destPos++] = srcByte & mask ? white : black; + mask >>= 1; + } + } + while (destPos < dest32DataLength) { + dest32[destPos++] = 0; + } + ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); + } + } else if (imgData.kind === util_ImageKind.RGBA_32BPP) { + j = 0; + elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4; + for (i = 0; i < fullChunks; i++) { + dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); + srcPos += elemsInThisChunk; + ctx.putImageData(chunkImgData, 0, j); + j += FULL_CHUNK_HEIGHT; + } + if (i < totalChunks) { + elemsInThisChunk = width * partialChunkHeight * 4; + dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); + ctx.putImageData(chunkImgData, 0, j); + } + } else if (imgData.kind === util_ImageKind.RGB_24BPP) { + thisChunkHeight = FULL_CHUNK_HEIGHT; + elemsInThisChunk = width * thisChunkHeight; + for (i = 0; i < totalChunks; i++) { + if (i >= fullChunks) { + thisChunkHeight = partialChunkHeight; + elemsInThisChunk = width * thisChunkHeight; + } + destPos = 0; + for (j = elemsInThisChunk; j--;) { + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = 255; + } + ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); + } + } else { + throw new Error(`bad image kind: ${imgData.kind}`); + } +} +function putBinaryImageMask(ctx, imgData) { + if (imgData.bitmap) { + ctx.drawImage(imgData.bitmap, 0, 0); + return; + } + const height = imgData.height, + width = imgData.width; + const partialChunkHeight = height % FULL_CHUNK_HEIGHT; + const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; + const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; + const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); + let srcPos = 0; + const src = imgData.data; + const dest = chunkImgData.data; + for (let i = 0; i < totalChunks; i++) { + const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight; + ({ + srcPos + } = convertBlackAndWhiteToRGBA({ + src, + srcPos, + dest, + width, + height: thisChunkHeight, + nonBlackColor: 0 + })); + ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); + } +} +function copyCtxState(sourceCtx, destCtx) { + const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font", "filter"]; + for (const property of properties) { + if (sourceCtx[property] !== undefined) { + destCtx[property] = sourceCtx[property]; + } + } + if (sourceCtx.setLineDash !== undefined) { + destCtx.setLineDash(sourceCtx.getLineDash()); + destCtx.lineDashOffset = sourceCtx.lineDashOffset; + } +} +function resetCtxToDefault(ctx) { + ctx.strokeStyle = ctx.fillStyle = "#000000"; + ctx.fillRule = "nonzero"; + ctx.globalAlpha = 1; + ctx.lineWidth = 1; + ctx.lineCap = "butt"; + ctx.lineJoin = "miter"; + ctx.miterLimit = 10; + ctx.globalCompositeOperation = "source-over"; + ctx.font = "10px sans-serif"; + if (ctx.setLineDash !== undefined) { + ctx.setLineDash([]); + ctx.lineDashOffset = 0; + } + if (!isNodeJS) { + const { + filter + } = ctx; + if (filter !== "none" && filter !== "") { + ctx.filter = "none"; + } + } +} +function getImageSmoothingEnabled(transform, interpolate) { + if (interpolate) { + return true; + } + const scale = Util.singularValueDecompose2dScale(transform); + scale[0] = Math.fround(scale[0]); + scale[1] = Math.fround(scale[1]); + const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * PixelsPerInch.PDF_TO_CSS_UNITS); + return scale[0] <= actualScale && scale[1] <= actualScale; +} +const LINE_CAP_STYLES = ["butt", "round", "square"]; +const LINE_JOIN_STYLES = ["miter", "round", "bevel"]; +const NORMAL_CLIP = {}; +const EO_CLIP = {}; +class CanvasGraphics { + constructor(canvasCtx, commonObjs, objs, canvasFactory, filterFactory, { + optionalContentConfig, + markedContentStack = null + }, annotationCanvasMap, pageColors) { + this.ctx = canvasCtx; + this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height); + this.stateStack = []; + this.pendingClip = null; + this.pendingEOFill = false; + this.res = null; + this.xobjs = null; + this.commonObjs = commonObjs; + this.objs = objs; + this.canvasFactory = canvasFactory; + this.filterFactory = filterFactory; + this.groupStack = []; + this.processingType3 = null; + this.baseTransform = null; + this.baseTransformStack = []; + this.groupLevel = 0; + this.smaskStack = []; + this.smaskCounter = 0; + this.tempSMask = null; + this.suspendedCtx = null; + this.contentVisible = true; + this.markedContentStack = markedContentStack || []; + this.optionalContentConfig = optionalContentConfig; + this.cachedCanvases = new CachedCanvases(this.canvasFactory); + this.cachedPatterns = new Map(); + this.annotationCanvasMap = annotationCanvasMap; + this.viewportScale = 1; + this.outputScaleX = 1; + this.outputScaleY = 1; + this.pageColors = pageColors; + this._cachedScaleForStroking = [-1, 0]; + this._cachedGetSinglePixelWidth = null; + this._cachedBitmapsMap = new Map(); + } + getObject(data, fallback = null) { + if (typeof data === "string") { + return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data); + } + return fallback; + } + beginDrawing({ + transform, + viewport, + transparency = false, + background = null + }) { + const width = this.ctx.canvas.width; + const height = this.ctx.canvas.height; + const savedFillStyle = this.ctx.fillStyle; + this.ctx.fillStyle = background || "#ffffff"; + this.ctx.fillRect(0, 0, width, height); + this.ctx.fillStyle = savedFillStyle; + if (transparency) { + const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height); + this.compositeCtx = this.ctx; + this.transparentCanvas = transparentCanvas.canvas; + this.ctx = transparentCanvas.context; + this.ctx.save(); + this.ctx.transform(...getCurrentTransform(this.compositeCtx)); + } + this.ctx.save(); + resetCtxToDefault(this.ctx); + if (transform) { + this.ctx.transform(...transform); + this.outputScaleX = transform[0]; + this.outputScaleY = transform[0]; + } + this.ctx.transform(...viewport.transform); + this.viewportScale = viewport.scale; + this.baseTransform = getCurrentTransform(this.ctx); + } + executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) { + const argsArray = operatorList.argsArray; + const fnArray = operatorList.fnArray; + let i = executionStartIdx || 0; + const argsArrayLen = argsArray.length; + if (argsArrayLen === i) { + return i; + } + const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function"; + const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0; + let steps = 0; + const commonObjs = this.commonObjs; + const objs = this.objs; + let fnId; + while (true) { + if (stepper !== undefined && i === stepper.nextBreakPoint) { + stepper.breakIt(i, continueCallback); + return i; + } + fnId = fnArray[i]; + if (fnId !== OPS.dependency) { + this[fnId].apply(this, argsArray[i]); + } else { + for (const depObjId of argsArray[i]) { + const objsPool = depObjId.startsWith("g_") ? commonObjs : objs; + if (!objsPool.has(depObjId)) { + objsPool.get(depObjId, continueCallback); + return i; + } + } + } + i++; + if (i === argsArrayLen) { + return i; + } + if (chunkOperations && ++steps > EXECUTION_STEPS) { + if (Date.now() > endTime) { + continueCallback(); + return i; + } + steps = 0; + } + } + } + #restoreInitialState() { + while (this.stateStack.length || this.inSMaskMode) { + this.restore(); + } + this.current.activeSMask = null; + this.ctx.restore(); + if (this.transparentCanvas) { + this.ctx = this.compositeCtx; + this.ctx.save(); + this.ctx.setTransform(1, 0, 0, 1, 0, 0); + this.ctx.drawImage(this.transparentCanvas, 0, 0); + this.ctx.restore(); + this.transparentCanvas = null; + } + } + endDrawing() { + this.#restoreInitialState(); + this.cachedCanvases.clear(); + this.cachedPatterns.clear(); + for (const cache of this._cachedBitmapsMap.values()) { + for (const canvas of cache.values()) { + if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) { + canvas.width = canvas.height = 0; + } + } + cache.clear(); + } + this._cachedBitmapsMap.clear(); + this.#drawFilter(); + } + #drawFilter() { + if (this.pageColors) { + const hcmFilterId = this.filterFactory.addHCMFilter(this.pageColors.foreground, this.pageColors.background); + if (hcmFilterId !== "none") { + const savedFilter = this.ctx.filter; + this.ctx.filter = hcmFilterId; + this.ctx.drawImage(this.ctx.canvas, 0, 0); + this.ctx.filter = savedFilter; + } + } + } + _scaleImage(img, inverseTransform) { + const width = img.width ?? img.displayWidth; + const height = img.height ?? img.displayHeight; + let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1); + let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1); + let paintWidth = width, + paintHeight = height; + let tmpCanvasId = "prescale1"; + let tmpCanvas, tmpCtx; + while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) { + let newWidth = paintWidth, + newHeight = paintHeight; + if (widthScale > 2 && paintWidth > 1) { + newWidth = paintWidth >= 16384 ? Math.floor(paintWidth / 2) - 1 || 1 : Math.ceil(paintWidth / 2); + widthScale /= paintWidth / newWidth; + } + if (heightScale > 2 && paintHeight > 1) { + newHeight = paintHeight >= 16384 ? Math.floor(paintHeight / 2) - 1 || 1 : Math.ceil(paintHeight) / 2; + heightScale /= paintHeight / newHeight; + } + tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight); + tmpCtx = tmpCanvas.context; + tmpCtx.clearRect(0, 0, newWidth, newHeight); + tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight); + img = tmpCanvas.canvas; + paintWidth = newWidth; + paintHeight = newHeight; + tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1"; + } + return { + img, + paintWidth, + paintHeight + }; + } + _createMaskCanvas(img) { + const ctx = this.ctx; + const { + width, + height + } = img; + const fillColor = this.current.fillColor; + const isPatternFill = this.current.patternFill; + const currentTransform = getCurrentTransform(ctx); + let cache, cacheKey, scaled, maskCanvas; + if ((img.bitmap || img.data) && img.count > 1) { + const mainKey = img.bitmap || img.data.buffer; + cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]); + cache = this._cachedBitmapsMap.get(mainKey); + if (!cache) { + cache = new Map(); + this._cachedBitmapsMap.set(mainKey, cache); + } + const cachedImage = cache.get(cacheKey); + if (cachedImage && !isPatternFill) { + const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]); + const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]); + return { + canvas: cachedImage, + offsetX, + offsetY + }; + } + scaled = cachedImage; + } + if (!scaled) { + maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height); + putBinaryImageMask(maskCanvas.context, img); + } + let maskToCanvas = Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]); + maskToCanvas = Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]); + const [minX, minY, maxX, maxY] = Util.getAxialAlignedBoundingBox([0, 0, width, height], maskToCanvas); + const drawnWidth = Math.round(maxX - minX) || 1; + const drawnHeight = Math.round(maxY - minY) || 1; + const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight); + const fillCtx = fillCanvas.context; + const offsetX = minX; + const offsetY = minY; + fillCtx.translate(-offsetX, -offsetY); + fillCtx.transform(...maskToCanvas); + if (!scaled) { + scaled = this._scaleImage(maskCanvas.canvas, getCurrentTransformInverse(fillCtx)); + scaled = scaled.img; + if (cache && isPatternFill) { + cache.set(cacheKey, scaled); + } + } + fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(fillCtx), img.interpolate); + drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height); + fillCtx.globalCompositeOperation = "source-in"; + const inverse = Util.transform(getCurrentTransformInverse(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]); + fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, PathType.FILL) : fillColor; + fillCtx.fillRect(0, 0, width, height); + if (cache && !isPatternFill) { + this.cachedCanvases.delete("fillCanvas"); + cache.set(cacheKey, fillCanvas.canvas); + } + return { + canvas: fillCanvas.canvas, + offsetX: Math.round(offsetX), + offsetY: Math.round(offsetY) + }; + } + setLineWidth(width) { + if (width !== this.current.lineWidth) { + this._cachedScaleForStroking[0] = -1; + } + this.current.lineWidth = width; + this.ctx.lineWidth = width; + } + setLineCap(style) { + this.ctx.lineCap = LINE_CAP_STYLES[style]; + } + setLineJoin(style) { + this.ctx.lineJoin = LINE_JOIN_STYLES[style]; + } + setMiterLimit(limit) { + this.ctx.miterLimit = limit; + } + setDash(dashArray, dashPhase) { + const ctx = this.ctx; + if (ctx.setLineDash !== undefined) { + ctx.setLineDash(dashArray); + ctx.lineDashOffset = dashPhase; + } + } + setRenderingIntent(intent) {} + setFlatness(flatness) {} + setGState(states) { + for (const [key, value] of states) { + switch (key) { + case "LW": + this.setLineWidth(value); + break; + case "LC": + this.setLineCap(value); + break; + case "LJ": + this.setLineJoin(value); + break; + case "ML": + this.setMiterLimit(value); + break; + case "D": + this.setDash(value[0], value[1]); + break; + case "RI": + this.setRenderingIntent(value); + break; + case "FL": + this.setFlatness(value); + break; + case "Font": + this.setFont(value[0], value[1]); + break; + case "CA": + this.current.strokeAlpha = value; + break; + case "ca": + this.current.fillAlpha = value; + this.ctx.globalAlpha = value; + break; + case "BM": + this.ctx.globalCompositeOperation = value; + break; + case "SMask": + this.current.activeSMask = value ? this.tempSMask : null; + this.tempSMask = null; + this.checkSMaskState(); + break; + case "TR": + this.ctx.filter = this.current.transferMaps = this.filterFactory.addFilter(value); + break; + } + } + } + get inSMaskMode() { + return !!this.suspendedCtx; + } + checkSMaskState() { + const inSMaskMode = this.inSMaskMode; + if (this.current.activeSMask && !inSMaskMode) { + this.beginSMaskMode(); + } else if (!this.current.activeSMask && inSMaskMode) { + this.endSMaskMode(); + } + } + beginSMaskMode() { + if (this.inSMaskMode) { + throw new Error("beginSMaskMode called while already in smask mode"); + } + const drawnWidth = this.ctx.canvas.width; + const drawnHeight = this.ctx.canvas.height; + const cacheId = "smaskGroupAt" + this.groupLevel; + const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight); + this.suspendedCtx = this.ctx; + this.ctx = scratchCanvas.context; + const ctx = this.ctx; + ctx.setTransform(...getCurrentTransform(this.suspendedCtx)); + copyCtxState(this.suspendedCtx, ctx); + mirrorContextOperations(ctx, this.suspendedCtx); + this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]); + } + endSMaskMode() { + if (!this.inSMaskMode) { + throw new Error("endSMaskMode called while not in smask mode"); + } + this.ctx._removeMirroring(); + copyCtxState(this.ctx, this.suspendedCtx); + this.ctx = this.suspendedCtx; + this.suspendedCtx = null; + } + compose(dirtyBox) { + if (!this.current.activeSMask) { + return; + } + if (!dirtyBox) { + dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height]; + } else { + dirtyBox[0] = Math.floor(dirtyBox[0]); + dirtyBox[1] = Math.floor(dirtyBox[1]); + dirtyBox[2] = Math.ceil(dirtyBox[2]); + dirtyBox[3] = Math.ceil(dirtyBox[3]); + } + const smask = this.current.activeSMask; + const suspendedCtx = this.suspendedCtx; + this.composeSMask(suspendedCtx, smask, this.ctx, dirtyBox); + this.ctx.save(); + this.ctx.setTransform(1, 0, 0, 1, 0, 0); + this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height); + this.ctx.restore(); + } + composeSMask(ctx, smask, layerCtx, layerBox) { + const layerOffsetX = layerBox[0]; + const layerOffsetY = layerBox[1]; + const layerWidth = layerBox[2] - layerOffsetX; + const layerHeight = layerBox[3] - layerOffsetY; + if (layerWidth === 0 || layerHeight === 0) { + return; + } + this.genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY); + ctx.save(); + ctx.globalAlpha = 1; + ctx.globalCompositeOperation = "source-over"; + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.drawImage(layerCtx.canvas, 0, 0); + ctx.restore(); + } + genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) { + let maskCanvas = maskCtx.canvas; + let maskX = layerOffsetX - maskOffsetX; + let maskY = layerOffsetY - maskOffsetY; + if (backdrop) { + const backdropRGB = Util.makeHexColor(...backdrop); + if (maskX < 0 || maskY < 0 || maskX + width > maskCanvas.width || maskY + height > maskCanvas.height) { + const canvas = this.cachedCanvases.getCanvas("maskExtension", width, height); + const ctx = canvas.context; + ctx.drawImage(maskCanvas, -maskX, -maskY); + ctx.globalCompositeOperation = "destination-atop"; + ctx.fillStyle = backdropRGB; + ctx.fillRect(0, 0, width, height); + ctx.globalCompositeOperation = "source-over"; + maskCanvas = canvas.canvas; + maskX = maskY = 0; + } else { + maskCtx.save(); + maskCtx.globalAlpha = 1; + maskCtx.setTransform(1, 0, 0, 1, 0, 0); + const clip = new Path2D(); + clip.rect(maskX, maskY, width, height); + maskCtx.clip(clip); + maskCtx.globalCompositeOperation = "destination-atop"; + maskCtx.fillStyle = backdropRGB; + maskCtx.fillRect(maskX, maskY, width, height); + maskCtx.restore(); + } + } + layerCtx.save(); + layerCtx.globalAlpha = 1; + layerCtx.setTransform(1, 0, 0, 1, 0, 0); + if (subtype === "Alpha" && transferMap) { + layerCtx.filter = this.filterFactory.addAlphaFilter(transferMap); + } else if (subtype === "Luminosity") { + layerCtx.filter = this.filterFactory.addLuminosityFilter(transferMap); + } + const clip = new Path2D(); + clip.rect(layerOffsetX, layerOffsetY, width, height); + layerCtx.clip(clip); + layerCtx.globalCompositeOperation = "destination-in"; + layerCtx.drawImage(maskCanvas, maskX, maskY, width, height, layerOffsetX, layerOffsetY, width, height); + layerCtx.restore(); + } + save() { + if (this.inSMaskMode) { + copyCtxState(this.ctx, this.suspendedCtx); + this.suspendedCtx.save(); + } else { + this.ctx.save(); + } + const old = this.current; + this.stateStack.push(old); + this.current = old.clone(); + } + restore() { + if (this.stateStack.length === 0 && this.inSMaskMode) { + this.endSMaskMode(); + } + if (this.stateStack.length !== 0) { + this.current = this.stateStack.pop(); + if (this.inSMaskMode) { + this.suspendedCtx.restore(); + copyCtxState(this.suspendedCtx, this.ctx); + } else { + this.ctx.restore(); + } + this.checkSMaskState(); + this.pendingClip = null; + this._cachedScaleForStroking[0] = -1; + this._cachedGetSinglePixelWidth = null; + } + } + transform(a, b, c, d, e, f) { + this.ctx.transform(a, b, c, d, e, f); + this._cachedScaleForStroking[0] = -1; + this._cachedGetSinglePixelWidth = null; + } + constructPath(ops, args, minMax) { + const ctx = this.ctx; + const current = this.current; + let x = current.x, + y = current.y; + let startX, startY; + const currentTransform = getCurrentTransform(ctx); + const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0; + const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null; + for (let i = 0, j = 0, ii = ops.length; i < ii; i++) { + switch (ops[i] | 0) { + case OPS.rectangle: + x = args[j++]; + y = args[j++]; + const width = args[j++]; + const height = args[j++]; + const xw = x + width; + const yh = y + height; + ctx.moveTo(x, y); + if (width === 0 || height === 0) { + ctx.lineTo(xw, yh); + } else { + ctx.lineTo(xw, y); + ctx.lineTo(xw, yh); + ctx.lineTo(x, yh); + } + if (!isScalingMatrix) { + current.updateRectMinMax(currentTransform, [x, y, xw, yh]); + } + ctx.closePath(); + break; + case OPS.moveTo: + x = args[j++]; + y = args[j++]; + ctx.moveTo(x, y); + if (!isScalingMatrix) { + current.updatePathMinMax(currentTransform, x, y); + } + break; + case OPS.lineTo: + x = args[j++]; + y = args[j++]; + ctx.lineTo(x, y); + if (!isScalingMatrix) { + current.updatePathMinMax(currentTransform, x, y); + } + break; + case OPS.curveTo: + startX = x; + startY = y; + x = args[j + 4]; + y = args[j + 5]; + ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y); + current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier); + j += 6; + break; + case OPS.curveTo2: + startX = x; + startY = y; + ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]); + current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier); + x = args[j + 2]; + y = args[j + 3]; + j += 4; + break; + case OPS.curveTo3: + startX = x; + startY = y; + x = args[j + 2]; + y = args[j + 3]; + ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y); + current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier); + j += 4; + break; + case OPS.closePath: + ctx.closePath(); + break; + } + } + if (isScalingMatrix) { + current.updateScalingPathMinMax(currentTransform, minMaxForBezier); + } + current.setCurrentPoint(x, y); + } + closePath() { + this.ctx.closePath(); + } + stroke(consumePath = true) { + const ctx = this.ctx; + const strokeColor = this.current.strokeColor; + ctx.globalAlpha = this.current.strokeAlpha; + if (this.contentVisible) { + if (typeof strokeColor === "object" && strokeColor?.getPattern) { + ctx.save(); + ctx.strokeStyle = strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE); + this.rescaleAndStroke(false); + ctx.restore(); + } else { + this.rescaleAndStroke(true); + } + } + if (consumePath) { + this.consumePath(this.current.getClippedPathBoundingBox()); + } + ctx.globalAlpha = this.current.fillAlpha; + } + closeStroke() { + this.closePath(); + this.stroke(); + } + fill(consumePath = true) { + const ctx = this.ctx; + const fillColor = this.current.fillColor; + const isPatternFill = this.current.patternFill; + let needRestore = false; + if (isPatternFill) { + ctx.save(); + ctx.fillStyle = fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL); + needRestore = true; + } + const intersect = this.current.getClippedPathBoundingBox(); + if (this.contentVisible && intersect !== null) { + if (this.pendingEOFill) { + ctx.fill("evenodd"); + this.pendingEOFill = false; + } else { + ctx.fill(); + } + } + if (needRestore) { + ctx.restore(); + } + if (consumePath) { + this.consumePath(intersect); + } + } + eoFill() { + this.pendingEOFill = true; + this.fill(); + } + fillStroke() { + this.fill(false); + this.stroke(false); + this.consumePath(); + } + eoFillStroke() { + this.pendingEOFill = true; + this.fillStroke(); + } + closeFillStroke() { + this.closePath(); + this.fillStroke(); + } + closeEOFillStroke() { + this.pendingEOFill = true; + this.closePath(); + this.fillStroke(); + } + endPath() { + this.consumePath(); + } + clip() { + this.pendingClip = NORMAL_CLIP; + } + eoClip() { + this.pendingClip = EO_CLIP; + } + beginText() { + this.current.textMatrix = IDENTITY_MATRIX; + this.current.textMatrixScale = 1; + this.current.x = this.current.lineX = 0; + this.current.y = this.current.lineY = 0; + } + endText() { + const paths = this.pendingTextPaths; + const ctx = this.ctx; + if (paths === undefined) { + ctx.beginPath(); + return; + } + ctx.save(); + ctx.beginPath(); + for (const path of paths) { + ctx.setTransform(...path.transform); + ctx.translate(path.x, path.y); + path.addToPath(ctx, path.fontSize); + } + ctx.restore(); + ctx.clip(); + ctx.beginPath(); + delete this.pendingTextPaths; + } + setCharSpacing(spacing) { + this.current.charSpacing = spacing; + } + setWordSpacing(spacing) { + this.current.wordSpacing = spacing; + } + setHScale(scale) { + this.current.textHScale = scale / 100; + } + setLeading(leading) { + this.current.leading = -leading; + } + setFont(fontRefName, size) { + const fontObj = this.commonObjs.get(fontRefName); + const current = this.current; + if (!fontObj) { + throw new Error(`Can't find font for ${fontRefName}`); + } + current.fontMatrix = fontObj.fontMatrix || FONT_IDENTITY_MATRIX; + if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) { + warn("Invalid font matrix for font " + fontRefName); + } + if (size < 0) { + size = -size; + current.fontDirection = -1; + } else { + current.fontDirection = 1; + } + this.current.font = fontObj; + this.current.fontSize = size; + if (fontObj.isType3Font) { + return; + } + const name = fontObj.loadedName || "sans-serif"; + const typeface = fontObj.systemFontInfo?.css || `"${name}", ${fontObj.fallbackName}`; + let bold = "normal"; + if (fontObj.black) { + bold = "900"; + } else if (fontObj.bold) { + bold = "bold"; + } + const italic = fontObj.italic ? "italic" : "normal"; + let browserFontSize = size; + if (size < MIN_FONT_SIZE) { + browserFontSize = MIN_FONT_SIZE; + } else if (size > MAX_FONT_SIZE) { + browserFontSize = MAX_FONT_SIZE; + } + this.current.fontSizeScale = size / browserFontSize; + this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`; + } + setTextRenderingMode(mode) { + this.current.textRenderingMode = mode; + } + setTextRise(rise) { + this.current.textRise = rise; + } + moveText(x, y) { + this.current.x = this.current.lineX += x; + this.current.y = this.current.lineY += y; + } + setLeadingMoveText(x, y) { + this.setLeading(-y); + this.moveText(x, y); + } + setTextMatrix(a, b, c, d, e, f) { + this.current.textMatrix = [a, b, c, d, e, f]; + this.current.textMatrixScale = Math.hypot(a, b); + this.current.x = this.current.lineX = 0; + this.current.y = this.current.lineY = 0; + } + nextLine() { + this.moveText(0, this.current.leading); + } + paintChar(character, x, y, patternFillTransform, patternStrokeTransform) { + const ctx = this.ctx; + const current = this.current; + const font = current.font; + const textRenderingMode = current.textRenderingMode; + const fontSize = current.fontSize / current.fontSizeScale; + const fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; + const isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG); + const patternFill = current.patternFill && !font.missingFile; + const patternStroke = current.patternStroke && !font.missingFile; + let addToPath; + if (font.disableFontFace || isAddToPathSet || patternFill || patternStroke) { + addToPath = font.getPathGenerator(this.commonObjs, character); + } + if (font.disableFontFace || patternFill || patternStroke) { + ctx.save(); + ctx.translate(x, y); + ctx.beginPath(); + addToPath(ctx, fontSize); + if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + if (patternFillTransform) { + ctx.setTransform(...patternFillTransform); + } + ctx.fill(); + } + if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + if (patternStrokeTransform) { + ctx.setTransform(...patternStrokeTransform); + } + ctx.stroke(); + } + ctx.restore(); + } else { + if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + ctx.fillText(character, x, y); + } + if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + ctx.strokeText(character, x, y); + } + } + if (isAddToPathSet) { + const paths = this.pendingTextPaths ||= []; + paths.push({ + transform: getCurrentTransform(ctx), + x, + y, + fontSize, + addToPath + }); + } + } + get isFontSubpixelAAEnabled() { + const { + context: ctx + } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10); + ctx.scale(1.5, 1); + ctx.fillText("I", 0, 10); + const data = ctx.getImageData(0, 0, 10, 10).data; + let enabled = false; + for (let i = 3; i < data.length; i += 4) { + if (data[i] > 0 && data[i] < 255) { + enabled = true; + break; + } + } + return shadow(this, "isFontSubpixelAAEnabled", enabled); + } + showText(glyphs) { + const current = this.current; + const font = current.font; + if (font.isType3Font) { + return this.showType3Text(glyphs); + } + const fontSize = current.fontSize; + if (fontSize === 0) { + return undefined; + } + const ctx = this.ctx; + const fontSizeScale = current.fontSizeScale; + const charSpacing = current.charSpacing; + const wordSpacing = current.wordSpacing; + const fontDirection = current.fontDirection; + const textHScale = current.textHScale * fontDirection; + const glyphsLength = glyphs.length; + const vertical = font.vertical; + const spacingDir = vertical ? 1 : -1; + const defaultVMetrics = font.defaultVMetrics; + const widthAdvanceScale = fontSize * current.fontMatrix[0]; + const simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill; + ctx.save(); + ctx.transform(...current.textMatrix); + ctx.translate(current.x, current.y + current.textRise); + if (fontDirection > 0) { + ctx.scale(textHScale, -1); + } else { + ctx.scale(textHScale, 1); + } + let patternFillTransform, patternStrokeTransform; + if (current.patternFill) { + ctx.save(); + const pattern = current.fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL); + patternFillTransform = getCurrentTransform(ctx); + ctx.restore(); + ctx.fillStyle = pattern; + } + if (current.patternStroke) { + ctx.save(); + const pattern = current.strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE); + patternStrokeTransform = getCurrentTransform(ctx); + ctx.restore(); + ctx.strokeStyle = pattern; + } + let lineWidth = current.lineWidth; + const scale = current.textMatrixScale; + if (scale === 0 || lineWidth === 0) { + const fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; + if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + lineWidth = this.getSinglePixelWidth(); + } + } else { + lineWidth /= scale; + } + if (fontSizeScale !== 1.0) { + ctx.scale(fontSizeScale, fontSizeScale); + lineWidth /= fontSizeScale; + } + ctx.lineWidth = lineWidth; + if (font.isInvalidPDFjsFont) { + const chars = []; + let width = 0; + for (const glyph of glyphs) { + chars.push(glyph.unicode); + width += glyph.width; + } + ctx.fillText(chars.join(""), 0, 0); + current.x += width * widthAdvanceScale * textHScale; + ctx.restore(); + this.compose(); + return undefined; + } + let x = 0, + i; + for (i = 0; i < glyphsLength; ++i) { + const glyph = glyphs[i]; + if (typeof glyph === "number") { + x += spacingDir * glyph * fontSize / 1000; + continue; + } + let restoreNeeded = false; + const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; + const character = glyph.fontChar; + const accent = glyph.accent; + let scaledX, scaledY; + let width = glyph.width; + if (vertical) { + const vmetric = glyph.vmetric || defaultVMetrics; + const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale; + const vy = vmetric[2] * widthAdvanceScale; + width = vmetric ? -vmetric[0] : width; + scaledX = vx / fontSizeScale; + scaledY = (x + vy) / fontSizeScale; + } else { + scaledX = x / fontSizeScale; + scaledY = 0; + } + if (font.remeasure && width > 0) { + const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale; + if (width < measuredWidth && this.isFontSubpixelAAEnabled) { + const characterScaleX = width / measuredWidth; + restoreNeeded = true; + ctx.save(); + ctx.scale(characterScaleX, 1); + scaledX /= characterScaleX; + } else if (width !== measuredWidth) { + scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale; + } + } + if (this.contentVisible && (glyph.isInFont || font.missingFile)) { + if (simpleFillText && !accent) { + ctx.fillText(character, scaledX, scaledY); + } else { + this.paintChar(character, scaledX, scaledY, patternFillTransform, patternStrokeTransform); + if (accent) { + const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale; + const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale; + this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternFillTransform, patternStrokeTransform); + } + } + } + const charWidth = vertical ? width * widthAdvanceScale - spacing * fontDirection : width * widthAdvanceScale + spacing * fontDirection; + x += charWidth; + if (restoreNeeded) { + ctx.restore(); + } + } + if (vertical) { + current.y -= x; + } else { + current.x += x * textHScale; + } + ctx.restore(); + this.compose(); + return undefined; + } + showType3Text(glyphs) { + const ctx = this.ctx; + const current = this.current; + const font = current.font; + const fontSize = current.fontSize; + const fontDirection = current.fontDirection; + const spacingDir = font.vertical ? 1 : -1; + const charSpacing = current.charSpacing; + const wordSpacing = current.wordSpacing; + const textHScale = current.textHScale * fontDirection; + const fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX; + const glyphsLength = glyphs.length; + const isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE; + let i, glyph, width, spacingLength; + if (isTextInvisible || fontSize === 0) { + return; + } + this._cachedScaleForStroking[0] = -1; + this._cachedGetSinglePixelWidth = null; + ctx.save(); + ctx.transform(...current.textMatrix); + ctx.translate(current.x, current.y); + ctx.scale(textHScale, fontDirection); + for (i = 0; i < glyphsLength; ++i) { + glyph = glyphs[i]; + if (typeof glyph === "number") { + spacingLength = spacingDir * glyph * fontSize / 1000; + this.ctx.translate(spacingLength, 0); + current.x += spacingLength * textHScale; + continue; + } + const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; + const operatorList = font.charProcOperatorList[glyph.operatorListId]; + if (!operatorList) { + warn(`Type3 character "${glyph.operatorListId}" is not available.`); + continue; + } + if (this.contentVisible) { + this.processingType3 = glyph; + this.save(); + ctx.scale(fontSize, fontSize); + ctx.transform(...fontMatrix); + this.executeOperatorList(operatorList); + this.restore(); + } + const transformed = Util.applyTransform([glyph.width, 0], fontMatrix); + width = transformed[0] * fontSize + spacing; + ctx.translate(width, 0); + current.x += width * textHScale; + } + ctx.restore(); + this.processingType3 = null; + } + setCharWidth(xWidth, yWidth) {} + setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) { + this.ctx.rect(llx, lly, urx - llx, ury - lly); + this.ctx.clip(); + this.endPath(); + } + getColorN_Pattern(IR) { + let pattern; + if (IR[0] === "TilingPattern") { + const color = IR[1]; + const baseTransform = this.baseTransform || getCurrentTransform(this.ctx); + const canvasGraphicsFactory = { + createCanvasGraphics: ctx => new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, { + optionalContentConfig: this.optionalContentConfig, + markedContentStack: this.markedContentStack + }) + }; + pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform); + } else { + pattern = this._getPattern(IR[1], IR[2]); + } + return pattern; + } + setStrokeColorN() { + this.current.strokeColor = this.getColorN_Pattern(arguments); + this.current.patternStroke = true; + } + setFillColorN() { + this.current.fillColor = this.getColorN_Pattern(arguments); + this.current.patternFill = true; + } + setStrokeRGBColor(r, g, b) { + this.ctx.strokeStyle = this.current.strokeColor = Util.makeHexColor(r, g, b); + this.current.patternStroke = false; + } + setStrokeTransparent() { + this.ctx.strokeStyle = this.current.strokeColor = "transparent"; + this.current.patternStroke = false; + } + setFillRGBColor(r, g, b) { + this.ctx.fillStyle = this.current.fillColor = Util.makeHexColor(r, g, b); + this.current.patternFill = false; + } + setFillTransparent() { + this.ctx.fillStyle = this.current.fillColor = "transparent"; + this.current.patternFill = false; + } + _getPattern(objId, matrix = null) { + let pattern; + if (this.cachedPatterns.has(objId)) { + pattern = this.cachedPatterns.get(objId); + } else { + pattern = getShadingPattern(this.getObject(objId)); + this.cachedPatterns.set(objId, pattern); + } + if (matrix) { + pattern.matrix = matrix; + } + return pattern; + } + shadingFill(objId) { + if (!this.contentVisible) { + return; + } + const ctx = this.ctx; + this.save(); + const pattern = this._getPattern(objId); + ctx.fillStyle = pattern.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.SHADING); + const inv = getCurrentTransformInverse(ctx); + if (inv) { + const { + width, + height + } = ctx.canvas; + const [x0, y0, x1, y1] = Util.getAxialAlignedBoundingBox([0, 0, width, height], inv); + this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0); + } else { + this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10); + } + this.compose(this.current.getClippedPathBoundingBox()); + this.restore(); + } + beginInlineImage() { + unreachable("Should not call beginInlineImage"); + } + beginImageData() { + unreachable("Should not call beginImageData"); + } + paintFormXObjectBegin(matrix, bbox) { + if (!this.contentVisible) { + return; + } + this.save(); + this.baseTransformStack.push(this.baseTransform); + if (matrix) { + this.transform(...matrix); + } + this.baseTransform = getCurrentTransform(this.ctx); + if (bbox) { + const width = bbox[2] - bbox[0]; + const height = bbox[3] - bbox[1]; + this.ctx.rect(bbox[0], bbox[1], width, height); + this.current.updateRectMinMax(getCurrentTransform(this.ctx), bbox); + this.clip(); + this.endPath(); + } + } + paintFormXObjectEnd() { + if (!this.contentVisible) { + return; + } + this.restore(); + this.baseTransform = this.baseTransformStack.pop(); + } + beginGroup(group) { + if (!this.contentVisible) { + return; + } + this.save(); + if (this.inSMaskMode) { + this.endSMaskMode(); + this.current.activeSMask = null; + } + const currentCtx = this.ctx; + if (!group.isolated) { + info("TODO: Support non-isolated groups."); + } + if (group.knockout) { + warn("Knockout groups not supported."); + } + const currentTransform = getCurrentTransform(currentCtx); + if (group.matrix) { + currentCtx.transform(...group.matrix); + } + if (!group.bbox) { + throw new Error("Bounding box is required."); + } + let bounds = Util.getAxialAlignedBoundingBox(group.bbox, getCurrentTransform(currentCtx)); + const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height]; + bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0]; + const offsetX = Math.floor(bounds[0]); + const offsetY = Math.floor(bounds[1]); + const drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1); + const drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1); + this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]); + let cacheId = "groupAt" + this.groupLevel; + if (group.smask) { + cacheId += "_smask_" + this.smaskCounter++ % 2; + } + const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight); + const groupCtx = scratchCanvas.context; + groupCtx.translate(-offsetX, -offsetY); + groupCtx.transform(...currentTransform); + if (group.smask) { + this.smaskStack.push({ + canvas: scratchCanvas.canvas, + context: groupCtx, + offsetX, + offsetY, + subtype: group.smask.subtype, + backdrop: group.smask.backdrop, + transferMap: group.smask.transferMap || null, + startTransformInverse: null + }); + } else { + currentCtx.setTransform(1, 0, 0, 1, 0, 0); + currentCtx.translate(offsetX, offsetY); + currentCtx.save(); + } + copyCtxState(currentCtx, groupCtx); + this.ctx = groupCtx; + this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]); + this.groupStack.push(currentCtx); + this.groupLevel++; + } + endGroup(group) { + if (!this.contentVisible) { + return; + } + this.groupLevel--; + const groupCtx = this.ctx; + const ctx = this.groupStack.pop(); + this.ctx = ctx; + this.ctx.imageSmoothingEnabled = false; + if (group.smask) { + this.tempSMask = this.smaskStack.pop(); + this.restore(); + } else { + this.ctx.restore(); + const currentMtx = getCurrentTransform(this.ctx); + this.restore(); + this.ctx.save(); + this.ctx.setTransform(...currentMtx); + const dirtyBox = Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx); + this.ctx.drawImage(groupCtx.canvas, 0, 0); + this.ctx.restore(); + this.compose(dirtyBox); + } + } + beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) { + this.#restoreInitialState(); + resetCtxToDefault(this.ctx); + this.ctx.save(); + this.save(); + if (this.baseTransform) { + this.ctx.setTransform(...this.baseTransform); + } + if (rect) { + const width = rect[2] - rect[0]; + const height = rect[3] - rect[1]; + if (hasOwnCanvas && this.annotationCanvasMap) { + transform = transform.slice(); + transform[4] -= rect[0]; + transform[5] -= rect[1]; + rect = rect.slice(); + rect[0] = rect[1] = 0; + rect[2] = width; + rect[3] = height; + const [scaleX, scaleY] = Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx)); + const { + viewportScale + } = this; + const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale); + const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale); + this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight); + const { + canvas, + context + } = this.annotationCanvas; + this.annotationCanvasMap.set(id, canvas); + this.annotationCanvas.savedCtx = this.ctx; + this.ctx = context; + this.ctx.save(); + this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY); + resetCtxToDefault(this.ctx); + } else { + resetCtxToDefault(this.ctx); + this.endPath(); + this.ctx.rect(rect[0], rect[1], width, height); + this.ctx.clip(); + this.ctx.beginPath(); + } + } + this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height); + this.transform(...transform); + this.transform(...matrix); + } + endAnnotation() { + if (this.annotationCanvas) { + this.ctx.restore(); + this.#drawFilter(); + this.ctx = this.annotationCanvas.savedCtx; + delete this.annotationCanvas.savedCtx; + delete this.annotationCanvas; + } + } + paintImageMaskXObject(img) { + if (!this.contentVisible) { + return; + } + const count = img.count; + img = this.getObject(img.data, img); + img.count = count; + const ctx = this.ctx; + const glyph = this.processingType3; + if (glyph) { + if (glyph.compiled === undefined) { + glyph.compiled = compileType3Glyph(img); + } + if (glyph.compiled) { + glyph.compiled(ctx); + return; + } + } + const mask = this._createMaskCanvas(img); + const maskCanvas = mask.canvas; + ctx.save(); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY); + ctx.restore(); + this.compose(); + } + paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) { + if (!this.contentVisible) { + return; + } + img = this.getObject(img.data, img); + const ctx = this.ctx; + ctx.save(); + const currentTransform = getCurrentTransform(ctx); + ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0); + const mask = this._createMaskCanvas(img); + ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]); + for (let i = 0, ii = positions.length; i < ii; i += 2) { + const trans = Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]); + const [x, y] = Util.applyTransform([0, 0], trans); + ctx.drawImage(mask.canvas, x, y); + } + ctx.restore(); + this.compose(); + } + paintImageMaskXObjectGroup(images) { + if (!this.contentVisible) { + return; + } + const ctx = this.ctx; + const fillColor = this.current.fillColor; + const isPatternFill = this.current.patternFill; + for (const image of images) { + const { + data, + width, + height, + transform + } = image; + const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height); + const maskCtx = maskCanvas.context; + maskCtx.save(); + const img = this.getObject(data, image); + putBinaryImageMask(maskCtx, img); + maskCtx.globalCompositeOperation = "source-in"; + maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, getCurrentTransformInverse(ctx), PathType.FILL) : fillColor; + maskCtx.fillRect(0, 0, width, height); + maskCtx.restore(); + ctx.save(); + ctx.transform(...transform); + ctx.scale(1, -1); + drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); + ctx.restore(); + } + this.compose(); + } + paintImageXObject(objId) { + if (!this.contentVisible) { + return; + } + const imgData = this.getObject(objId); + if (!imgData) { + warn("Dependent image isn't ready yet"); + return; + } + this.paintInlineImageXObject(imgData); + } + paintImageXObjectRepeat(objId, scaleX, scaleY, positions) { + if (!this.contentVisible) { + return; + } + const imgData = this.getObject(objId); + if (!imgData) { + warn("Dependent image isn't ready yet"); + return; + } + const width = imgData.width; + const height = imgData.height; + const map = []; + for (let i = 0, ii = positions.length; i < ii; i += 2) { + map.push({ + transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]], + x: 0, + y: 0, + w: width, + h: height + }); + } + this.paintInlineImageXObjectGroup(imgData, map); + } + applyTransferMapsToCanvas(ctx) { + if (this.current.transferMaps !== "none") { + ctx.filter = this.current.transferMaps; + ctx.drawImage(ctx.canvas, 0, 0); + ctx.filter = "none"; + } + return ctx.canvas; + } + applyTransferMapsToBitmap(imgData) { + if (this.current.transferMaps === "none") { + return imgData.bitmap; + } + const { + bitmap, + width, + height + } = imgData; + const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height); + const tmpCtx = tmpCanvas.context; + tmpCtx.filter = this.current.transferMaps; + tmpCtx.drawImage(bitmap, 0, 0); + tmpCtx.filter = "none"; + return tmpCanvas.canvas; + } + paintInlineImageXObject(imgData) { + if (!this.contentVisible) { + return; + } + const width = imgData.width; + const height = imgData.height; + const ctx = this.ctx; + this.save(); + if (!isNodeJS) { + const { + filter + } = ctx; + if (filter !== "none" && filter !== "") { + ctx.filter = "none"; + } + } + ctx.scale(1 / width, -1 / height); + let imgToPaint; + if (imgData.bitmap) { + imgToPaint = this.applyTransferMapsToBitmap(imgData); + } else if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) { + imgToPaint = imgData; + } else { + const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height); + const tmpCtx = tmpCanvas.context; + putBinaryImageData(tmpCtx, imgData); + imgToPaint = this.applyTransferMapsToCanvas(tmpCtx); + } + const scaled = this._scaleImage(imgToPaint, getCurrentTransformInverse(ctx)); + ctx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(ctx), imgData.interpolate); + drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height); + this.compose(); + this.restore(); + } + paintInlineImageXObjectGroup(imgData, map) { + if (!this.contentVisible) { + return; + } + const ctx = this.ctx; + let imgToPaint; + if (imgData.bitmap) { + imgToPaint = imgData.bitmap; + } else { + const w = imgData.width; + const h = imgData.height; + const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h); + const tmpCtx = tmpCanvas.context; + putBinaryImageData(tmpCtx, imgData); + imgToPaint = this.applyTransferMapsToCanvas(tmpCtx); + } + for (const entry of map) { + ctx.save(); + ctx.transform(...entry.transform); + ctx.scale(1, -1); + drawImageAtIntegerCoords(ctx, imgToPaint, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1); + ctx.restore(); + } + this.compose(); + } + paintSolidColorImageMask() { + if (!this.contentVisible) { + return; + } + this.ctx.fillRect(0, 0, 1, 1); + this.compose(); + } + markPoint(tag) {} + markPointProps(tag, properties) {} + beginMarkedContent(tag) { + this.markedContentStack.push({ + visible: true + }); + } + beginMarkedContentProps(tag, properties) { + if (tag === "OC") { + this.markedContentStack.push({ + visible: this.optionalContentConfig.isVisible(properties) + }); + } else { + this.markedContentStack.push({ + visible: true + }); + } + this.contentVisible = this.isContentVisible(); + } + endMarkedContent() { + this.markedContentStack.pop(); + this.contentVisible = this.isContentVisible(); + } + beginCompat() {} + endCompat() {} + consumePath(clipBox) { + const isEmpty = this.current.isEmptyClip(); + if (this.pendingClip) { + this.current.updateClipFromPath(); + } + if (!this.pendingClip) { + this.compose(clipBox); + } + const ctx = this.ctx; + if (this.pendingClip) { + if (!isEmpty) { + if (this.pendingClip === EO_CLIP) { + ctx.clip("evenodd"); + } else { + ctx.clip(); + } + } + this.pendingClip = null; + } + this.current.startNewPathAndClipBox(this.current.clipBox); + ctx.beginPath(); + } + getSinglePixelWidth() { + if (!this._cachedGetSinglePixelWidth) { + const m = getCurrentTransform(this.ctx); + if (m[1] === 0 && m[2] === 0) { + this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3])); + } else { + const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]); + const normX = Math.hypot(m[0], m[2]); + const normY = Math.hypot(m[1], m[3]); + this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet; + } + } + return this._cachedGetSinglePixelWidth; + } + getScaleForStroking() { + if (this._cachedScaleForStroking[0] === -1) { + const { + lineWidth + } = this.current; + const { + a, + b, + c, + d + } = this.ctx.getTransform(); + let scaleX, scaleY; + if (b === 0 && c === 0) { + const normX = Math.abs(a); + const normY = Math.abs(d); + if (normX === normY) { + if (lineWidth === 0) { + scaleX = scaleY = 1 / normX; + } else { + const scaledLineWidth = normX * lineWidth; + scaleX = scaleY = scaledLineWidth < 1 ? 1 / scaledLineWidth : 1; + } + } else if (lineWidth === 0) { + scaleX = 1 / normX; + scaleY = 1 / normY; + } else { + const scaledXLineWidth = normX * lineWidth; + const scaledYLineWidth = normY * lineWidth; + scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1; + scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1; + } + } else { + const absDet = Math.abs(a * d - b * c); + const normX = Math.hypot(a, b); + const normY = Math.hypot(c, d); + if (lineWidth === 0) { + scaleX = normY / absDet; + scaleY = normX / absDet; + } else { + const baseArea = lineWidth * absDet; + scaleX = normY > baseArea ? normY / baseArea : 1; + scaleY = normX > baseArea ? normX / baseArea : 1; + } + } + this._cachedScaleForStroking[0] = scaleX; + this._cachedScaleForStroking[1] = scaleY; + } + return this._cachedScaleForStroking; + } + rescaleAndStroke(saveRestore) { + const { + ctx + } = this; + const { + lineWidth + } = this.current; + const [scaleX, scaleY] = this.getScaleForStroking(); + ctx.lineWidth = lineWidth || 1; + if (scaleX === 1 && scaleY === 1) { + ctx.stroke(); + return; + } + const dashes = ctx.getLineDash(); + if (saveRestore) { + ctx.save(); + } + ctx.scale(scaleX, scaleY); + if (dashes.length > 0) { + const scale = Math.max(scaleX, scaleY); + ctx.setLineDash(dashes.map(x => x / scale)); + ctx.lineDashOffset /= scale; + } + ctx.stroke(); + if (saveRestore) { + ctx.restore(); + } + } + isContentVisible() { + for (let i = this.markedContentStack.length - 1; i >= 0; i--) { + if (!this.markedContentStack[i].visible) { + return false; + } + } + return true; + } +} +for (const op in OPS) { + if (CanvasGraphics.prototype[op] !== undefined) { + CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op]; + } +} + +;// ./src/display/worker_options.js +class GlobalWorkerOptions { + static #port = null; + static #src = ""; + static get workerPort() { + return this.#port; + } + static set workerPort(val) { + if (!(typeof Worker !== "undefined" && val instanceof Worker) && val !== null) { + throw new Error("Invalid `workerPort` type."); + } + this.#port = val; + } + static get workerSrc() { + return this.#src; + } + static set workerSrc(val) { + if (typeof val !== "string") { + throw new Error("Invalid `workerSrc` type."); + } + this.#src = val; + } +} + +;// ./src/shared/message_handler.js + +const CallbackKind = { + UNKNOWN: 0, + DATA: 1, + ERROR: 2 +}; +const StreamKind = { + UNKNOWN: 0, + CANCEL: 1, + CANCEL_COMPLETE: 2, + CLOSE: 3, + ENQUEUE: 4, + ERROR: 5, + PULL: 6, + PULL_COMPLETE: 7, + START_COMPLETE: 8 +}; +function onFn() {} +function wrapReason(reason) { + if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) { + unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.'); + } + switch (reason.name) { + case "AbortException": + return new AbortException(reason.message); + case "MissingPDFException": + return new MissingPDFException(reason.message); + case "PasswordException": + return new PasswordException(reason.message, reason.code); + case "UnexpectedResponseException": + return new UnexpectedResponseException(reason.message, reason.status); + case "UnknownErrorException": + return new UnknownErrorException(reason.message, reason.details); + default: + return new UnknownErrorException(reason.message, reason.toString()); + } +} +class MessageHandler { + #messageAC = new AbortController(); + constructor(sourceName, targetName, comObj) { + this.sourceName = sourceName; + this.targetName = targetName; + this.comObj = comObj; + this.callbackId = 1; + this.streamId = 1; + this.streamSinks = Object.create(null); + this.streamControllers = Object.create(null); + this.callbackCapabilities = Object.create(null); + this.actionHandler = Object.create(null); + comObj.addEventListener("message", this.#onMessage.bind(this), { + signal: this.#messageAC.signal + }); + } + #onMessage({ + data + }) { + if (data.targetName !== this.sourceName) { + return; + } + if (data.stream) { + this.#processStreamMessage(data); + return; + } + if (data.callback) { + const callbackId = data.callbackId; + const capability = this.callbackCapabilities[callbackId]; + if (!capability) { + throw new Error(`Cannot resolve callback ${callbackId}`); + } + delete this.callbackCapabilities[callbackId]; + if (data.callback === CallbackKind.DATA) { + capability.resolve(data.data); + } else if (data.callback === CallbackKind.ERROR) { + capability.reject(wrapReason(data.reason)); + } else { + throw new Error("Unexpected callback case"); + } + return; + } + const action = this.actionHandler[data.action]; + if (!action) { + throw new Error(`Unknown action from worker: ${data.action}`); + } + if (data.callbackId) { + const sourceName = this.sourceName, + targetName = data.sourceName, + comObj = this.comObj; + Promise.try(action, data.data).then(function (result) { + comObj.postMessage({ + sourceName, + targetName, + callback: CallbackKind.DATA, + callbackId: data.callbackId, + data: result + }); + }, function (reason) { + comObj.postMessage({ + sourceName, + targetName, + callback: CallbackKind.ERROR, + callbackId: data.callbackId, + reason: wrapReason(reason) + }); + }); + return; + } + if (data.streamId) { + this.#createStreamSink(data); + return; + } + action(data.data); + } + on(actionName, handler) { + const ah = this.actionHandler; + if (ah[actionName]) { + throw new Error(`There is already an actionName called "${actionName}"`); + } + ah[actionName] = handler; + } + send(actionName, data, transfers) { + this.comObj.postMessage({ + sourceName: this.sourceName, + targetName: this.targetName, + action: actionName, + data + }, transfers); + } + sendWithPromise(actionName, data, transfers) { + const callbackId = this.callbackId++; + const capability = Promise.withResolvers(); + this.callbackCapabilities[callbackId] = capability; + try { + this.comObj.postMessage({ + sourceName: this.sourceName, + targetName: this.targetName, + action: actionName, + callbackId, + data + }, transfers); + } catch (ex) { + capability.reject(ex); + } + return capability.promise; + } + sendWithStream(actionName, data, queueingStrategy, transfers) { + const streamId = this.streamId++, + sourceName = this.sourceName, + targetName = this.targetName, + comObj = this.comObj; + return new ReadableStream({ + start: controller => { + const startCapability = Promise.withResolvers(); + this.streamControllers[streamId] = { + controller, + startCall: startCapability, + pullCall: null, + cancelCall: null, + isClosed: false + }; + comObj.postMessage({ + sourceName, + targetName, + action: actionName, + streamId, + data, + desiredSize: controller.desiredSize + }, transfers); + return startCapability.promise; + }, + pull: controller => { + const pullCapability = Promise.withResolvers(); + this.streamControllers[streamId].pullCall = pullCapability; + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.PULL, + streamId, + desiredSize: controller.desiredSize + }); + return pullCapability.promise; + }, + cancel: reason => { + assert(reason instanceof Error, "cancel must have a valid reason"); + const cancelCapability = Promise.withResolvers(); + this.streamControllers[streamId].cancelCall = cancelCapability; + this.streamControllers[streamId].isClosed = true; + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.CANCEL, + streamId, + reason: wrapReason(reason) + }); + return cancelCapability.promise; + } + }, queueingStrategy); + } + #createStreamSink(data) { + const streamId = data.streamId, + sourceName = this.sourceName, + targetName = data.sourceName, + comObj = this.comObj; + const self = this, + action = this.actionHandler[data.action]; + const streamSink = { + enqueue(chunk, size = 1, transfers) { + if (this.isCancelled) { + return; + } + const lastDesiredSize = this.desiredSize; + this.desiredSize -= size; + if (lastDesiredSize > 0 && this.desiredSize <= 0) { + this.sinkCapability = Promise.withResolvers(); + this.ready = this.sinkCapability.promise; + } + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.ENQUEUE, + streamId, + chunk + }, transfers); + }, + close() { + if (this.isCancelled) { + return; + } + this.isCancelled = true; + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.CLOSE, + streamId + }); + delete self.streamSinks[streamId]; + }, + error(reason) { + assert(reason instanceof Error, "error must have a valid reason"); + if (this.isCancelled) { + return; + } + this.isCancelled = true; + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.ERROR, + streamId, + reason: wrapReason(reason) + }); + }, + sinkCapability: Promise.withResolvers(), + onPull: null, + onCancel: null, + isCancelled: false, + desiredSize: data.desiredSize, + ready: null + }; + streamSink.sinkCapability.resolve(); + streamSink.ready = streamSink.sinkCapability.promise; + this.streamSinks[streamId] = streamSink; + Promise.try(action, data.data, streamSink).then(function () { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.START_COMPLETE, + streamId, + success: true + }); + }, function (reason) { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.START_COMPLETE, + streamId, + reason: wrapReason(reason) + }); + }); + } + #processStreamMessage(data) { + const streamId = data.streamId, + sourceName = this.sourceName, + targetName = data.sourceName, + comObj = this.comObj; + const streamController = this.streamControllers[streamId], + streamSink = this.streamSinks[streamId]; + switch (data.stream) { + case StreamKind.START_COMPLETE: + if (data.success) { + streamController.startCall.resolve(); + } else { + streamController.startCall.reject(wrapReason(data.reason)); + } + break; + case StreamKind.PULL_COMPLETE: + if (data.success) { + streamController.pullCall.resolve(); + } else { + streamController.pullCall.reject(wrapReason(data.reason)); + } + break; + case StreamKind.PULL: + if (!streamSink) { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.PULL_COMPLETE, + streamId, + success: true + }); + break; + } + if (streamSink.desiredSize <= 0 && data.desiredSize > 0) { + streamSink.sinkCapability.resolve(); + } + streamSink.desiredSize = data.desiredSize; + Promise.try(streamSink.onPull || onFn).then(function () { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.PULL_COMPLETE, + streamId, + success: true + }); + }, function (reason) { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.PULL_COMPLETE, + streamId, + reason: wrapReason(reason) + }); + }); + break; + case StreamKind.ENQUEUE: + assert(streamController, "enqueue should have stream controller"); + if (streamController.isClosed) { + break; + } + streamController.controller.enqueue(data.chunk); + break; + case StreamKind.CLOSE: + assert(streamController, "close should have stream controller"); + if (streamController.isClosed) { + break; + } + streamController.isClosed = true; + streamController.controller.close(); + this.#deleteStreamController(streamController, streamId); + break; + case StreamKind.ERROR: + assert(streamController, "error should have stream controller"); + streamController.controller.error(wrapReason(data.reason)); + this.#deleteStreamController(streamController, streamId); + break; + case StreamKind.CANCEL_COMPLETE: + if (data.success) { + streamController.cancelCall.resolve(); + } else { + streamController.cancelCall.reject(wrapReason(data.reason)); + } + this.#deleteStreamController(streamController, streamId); + break; + case StreamKind.CANCEL: + if (!streamSink) { + break; + } + const dataReason = wrapReason(data.reason); + Promise.try(streamSink.onCancel || onFn, dataReason).then(function () { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.CANCEL_COMPLETE, + streamId, + success: true + }); + }, function (reason) { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.CANCEL_COMPLETE, + streamId, + reason: wrapReason(reason) + }); + }); + streamSink.sinkCapability.reject(dataReason); + streamSink.isCancelled = true; + delete this.streamSinks[streamId]; + break; + default: + throw new Error("Unexpected stream case"); + } + } + async #deleteStreamController(streamController, streamId) { + await Promise.allSettled([streamController.startCall?.promise, streamController.pullCall?.promise, streamController.cancelCall?.promise]); + delete this.streamControllers[streamId]; + } + destroy() { + this.#messageAC?.abort(); + this.#messageAC = null; + } +} + +;// ./src/display/metadata.js + +class Metadata { + #metadataMap; + #data; + constructor({ + parsedData, + rawData + }) { + this.#metadataMap = parsedData; + this.#data = rawData; + } + getRaw() { + return this.#data; + } + get(name) { + return this.#metadataMap.get(name) ?? null; + } + getAll() { + return objectFromMap(this.#metadataMap); + } + has(name) { + return this.#metadataMap.has(name); + } +} + +;// ./src/display/optional_content_config.js + + +const INTERNAL = Symbol("INTERNAL"); +class OptionalContentGroup { + #isDisplay = false; + #isPrint = false; + #userSet = false; + #visible = true; + constructor(renderingIntent, { + name, + intent, + usage, + rbGroups + }) { + this.#isDisplay = !!(renderingIntent & RenderingIntentFlag.DISPLAY); + this.#isPrint = !!(renderingIntent & RenderingIntentFlag.PRINT); + this.name = name; + this.intent = intent; + this.usage = usage; + this.rbGroups = rbGroups; + } + get visible() { + if (this.#userSet) { + return this.#visible; + } + if (!this.#visible) { + return false; + } + const { + print, + view + } = this.usage; + if (this.#isDisplay) { + return view?.viewState !== "OFF"; + } else if (this.#isPrint) { + return print?.printState !== "OFF"; + } + return true; + } + _setVisible(internal, visible, userSet = false) { + if (internal !== INTERNAL) { + unreachable("Internal method `_setVisible` called."); + } + this.#userSet = userSet; + this.#visible = visible; + } +} +class OptionalContentConfig { + #cachedGetHash = null; + #groups = new Map(); + #initialHash = null; + #order = null; + constructor(data, renderingIntent = RenderingIntentFlag.DISPLAY) { + this.renderingIntent = renderingIntent; + this.name = null; + this.creator = null; + if (data === null) { + return; + } + this.name = data.name; + this.creator = data.creator; + this.#order = data.order; + for (const group of data.groups) { + this.#groups.set(group.id, new OptionalContentGroup(renderingIntent, group)); + } + if (data.baseState === "OFF") { + for (const group of this.#groups.values()) { + group._setVisible(INTERNAL, false); + } + } + for (const on of data.on) { + this.#groups.get(on)._setVisible(INTERNAL, true); + } + for (const off of data.off) { + this.#groups.get(off)._setVisible(INTERNAL, false); + } + this.#initialHash = this.getHash(); + } + #evaluateVisibilityExpression(array) { + const length = array.length; + if (length < 2) { + return true; + } + const operator = array[0]; + for (let i = 1; i < length; i++) { + const element = array[i]; + let state; + if (Array.isArray(element)) { + state = this.#evaluateVisibilityExpression(element); + } else if (this.#groups.has(element)) { + state = this.#groups.get(element).visible; + } else { + warn(`Optional content group not found: ${element}`); + return true; + } + switch (operator) { + case "And": + if (!state) { + return false; + } + break; + case "Or": + if (state) { + return true; + } + break; + case "Not": + return !state; + default: + return true; + } + } + return operator === "And"; + } + isVisible(group) { + if (this.#groups.size === 0) { + return true; + } + if (!group) { + info("Optional content group not defined."); + return true; + } + if (group.type === "OCG") { + if (!this.#groups.has(group.id)) { + warn(`Optional content group not found: ${group.id}`); + return true; + } + return this.#groups.get(group.id).visible; + } else if (group.type === "OCMD") { + if (group.expression) { + return this.#evaluateVisibilityExpression(group.expression); + } + if (!group.policy || group.policy === "AnyOn") { + for (const id of group.ids) { + if (!this.#groups.has(id)) { + warn(`Optional content group not found: ${id}`); + return true; + } + if (this.#groups.get(id).visible) { + return true; + } + } + return false; + } else if (group.policy === "AllOn") { + for (const id of group.ids) { + if (!this.#groups.has(id)) { + warn(`Optional content group not found: ${id}`); + return true; + } + if (!this.#groups.get(id).visible) { + return false; + } + } + return true; + } else if (group.policy === "AnyOff") { + for (const id of group.ids) { + if (!this.#groups.has(id)) { + warn(`Optional content group not found: ${id}`); + return true; + } + if (!this.#groups.get(id).visible) { + return true; + } + } + return false; + } else if (group.policy === "AllOff") { + for (const id of group.ids) { + if (!this.#groups.has(id)) { + warn(`Optional content group not found: ${id}`); + return true; + } + if (this.#groups.get(id).visible) { + return false; + } + } + return true; + } + warn(`Unknown optional content policy ${group.policy}.`); + return true; + } + warn(`Unknown group type ${group.type}.`); + return true; + } + setVisibility(id, visible = true, preserveRB = true) { + const group = this.#groups.get(id); + if (!group) { + warn(`Optional content group not found: ${id}`); + return; + } + if (preserveRB && visible && group.rbGroups.length) { + for (const rbGroup of group.rbGroups) { + for (const otherId of rbGroup) { + if (otherId !== id) { + this.#groups.get(otherId)?._setVisible(INTERNAL, false, true); + } + } + } + } + group._setVisible(INTERNAL, !!visible, true); + this.#cachedGetHash = null; + } + setOCGState({ + state, + preserveRB + }) { + let operator; + for (const elem of state) { + switch (elem) { + case "ON": + case "OFF": + case "Toggle": + operator = elem; + continue; + } + const group = this.#groups.get(elem); + if (!group) { + continue; + } + switch (operator) { + case "ON": + this.setVisibility(elem, true, preserveRB); + break; + case "OFF": + this.setVisibility(elem, false, preserveRB); + break; + case "Toggle": + this.setVisibility(elem, !group.visible, preserveRB); + break; + } + } + this.#cachedGetHash = null; + } + get hasInitialVisibility() { + return this.#initialHash === null || this.getHash() === this.#initialHash; + } + getOrder() { + if (!this.#groups.size) { + return null; + } + if (this.#order) { + return this.#order.slice(); + } + return [...this.#groups.keys()]; + } + getGroups() { + return this.#groups.size > 0 ? objectFromMap(this.#groups) : null; + } + getGroup(id) { + return this.#groups.get(id) || null; + } + getHash() { + if (this.#cachedGetHash !== null) { + return this.#cachedGetHash; + } + const hash = new MurmurHash3_64(); + for (const [id, group] of this.#groups) { + hash.update(`${id}:${group.visible}`); + } + return this.#cachedGetHash = hash.hexdigest(); + } +} + +;// ./src/display/transport_stream.js + + +class PDFDataTransportStream { + constructor(pdfDataRangeTransport, { + disableRange = false, + disableStream = false + }) { + assert(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.'); + const { + length, + initialData, + progressiveDone, + contentDispositionFilename + } = pdfDataRangeTransport; + this._queuedChunks = []; + this._progressiveDone = progressiveDone; + this._contentDispositionFilename = contentDispositionFilename; + if (initialData?.length > 0) { + const buffer = initialData instanceof Uint8Array && initialData.byteLength === initialData.buffer.byteLength ? initialData.buffer : new Uint8Array(initialData).buffer; + this._queuedChunks.push(buffer); + } + this._pdfDataRangeTransport = pdfDataRangeTransport; + this._isStreamingSupported = !disableStream; + this._isRangeSupported = !disableRange; + this._contentLength = length; + this._fullRequestReader = null; + this._rangeReaders = []; + pdfDataRangeTransport.addRangeListener((begin, chunk) => { + this._onReceiveData({ + begin, + chunk + }); + }); + pdfDataRangeTransport.addProgressListener((loaded, total) => { + this._onProgress({ + loaded, + total + }); + }); + pdfDataRangeTransport.addProgressiveReadListener(chunk => { + this._onReceiveData({ + chunk + }); + }); + pdfDataRangeTransport.addProgressiveDoneListener(() => { + this._onProgressiveDone(); + }); + pdfDataRangeTransport.transportReady(); + } + _onReceiveData({ + begin, + chunk + }) { + const buffer = chunk instanceof Uint8Array && chunk.byteLength === chunk.buffer.byteLength ? chunk.buffer : new Uint8Array(chunk).buffer; + if (begin === undefined) { + if (this._fullRequestReader) { + this._fullRequestReader._enqueue(buffer); + } else { + this._queuedChunks.push(buffer); + } + } else { + const found = this._rangeReaders.some(function (rangeReader) { + if (rangeReader._begin !== begin) { + return false; + } + rangeReader._enqueue(buffer); + return true; + }); + assert(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."); + } + } + get _progressiveDataLength() { + return this._fullRequestReader?._loaded ?? 0; + } + _onProgress(evt) { + if (evt.total === undefined) { + this._rangeReaders[0]?.onProgress?.({ + loaded: evt.loaded + }); + } else { + this._fullRequestReader?.onProgress?.({ + loaded: evt.loaded, + total: evt.total + }); + } + } + _onProgressiveDone() { + this._fullRequestReader?.progressiveDone(); + this._progressiveDone = true; + } + _removeRangeReader(reader) { + const i = this._rangeReaders.indexOf(reader); + if (i >= 0) { + this._rangeReaders.splice(i, 1); + } + } + getFullReader() { + assert(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once."); + const queuedChunks = this._queuedChunks; + this._queuedChunks = null; + return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename); + } + getRangeReader(begin, end) { + if (end <= this._progressiveDataLength) { + return null; + } + const reader = new PDFDataTransportStreamRangeReader(this, begin, end); + this._pdfDataRangeTransport.requestDataRange(begin, end); + this._rangeReaders.push(reader); + return reader; + } + cancelAllRequests(reason) { + this._fullRequestReader?.cancel(reason); + for (const reader of this._rangeReaders.slice(0)) { + reader.cancel(reason); + } + this._pdfDataRangeTransport.abort(); + } +} +class PDFDataTransportStreamReader { + constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) { + this._stream = stream; + this._done = progressiveDone || false; + this._filename = isPdfFile(contentDispositionFilename) ? contentDispositionFilename : null; + this._queuedChunks = queuedChunks || []; + this._loaded = 0; + for (const chunk of this._queuedChunks) { + this._loaded += chunk.byteLength; + } + this._requests = []; + this._headersReady = Promise.resolve(); + stream._fullRequestReader = this; + this.onProgress = null; + } + _enqueue(chunk) { + if (this._done) { + return; + } + if (this._requests.length > 0) { + const requestCapability = this._requests.shift(); + requestCapability.resolve({ + value: chunk, + done: false + }); + } else { + this._queuedChunks.push(chunk); + } + this._loaded += chunk.byteLength; + } + get headersReady() { + return this._headersReady; + } + get filename() { + return this._filename; + } + get isRangeSupported() { + return this._stream._isRangeSupported; + } + get isStreamingSupported() { + return this._stream._isStreamingSupported; + } + get contentLength() { + return this._stream._contentLength; + } + async read() { + if (this._queuedChunks.length > 0) { + const chunk = this._queuedChunks.shift(); + return { + value: chunk, + done: false + }; + } + if (this._done) { + return { + value: undefined, + done: true + }; + } + const requestCapability = Promise.withResolvers(); + this._requests.push(requestCapability); + return requestCapability.promise; + } + cancel(reason) { + this._done = true; + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: undefined, + done: true + }); + } + this._requests.length = 0; + } + progressiveDone() { + if (this._done) { + return; + } + this._done = true; + } +} +class PDFDataTransportStreamRangeReader { + constructor(stream, begin, end) { + this._stream = stream; + this._begin = begin; + this._end = end; + this._queuedChunk = null; + this._requests = []; + this._done = false; + this.onProgress = null; + } + _enqueue(chunk) { + if (this._done) { + return; + } + if (this._requests.length === 0) { + this._queuedChunk = chunk; + } else { + const requestsCapability = this._requests.shift(); + requestsCapability.resolve({ + value: chunk, + done: false + }); + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: undefined, + done: true + }); + } + this._requests.length = 0; + } + this._done = true; + this._stream._removeRangeReader(this); + } + get isStreamingSupported() { + return false; + } + async read() { + if (this._queuedChunk) { + const chunk = this._queuedChunk; + this._queuedChunk = null; + return { + value: chunk, + done: false + }; + } + if (this._done) { + return { + value: undefined, + done: true + }; + } + const requestCapability = Promise.withResolvers(); + this._requests.push(requestCapability); + return requestCapability.promise; + } + cancel(reason) { + this._done = true; + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: undefined, + done: true + }); + } + this._requests.length = 0; + this._stream._removeRangeReader(this); + } +} + +;// ./src/display/content_disposition.js + +function getFilenameFromContentDispositionHeader(contentDisposition) { + let needsEncodingFixup = true; + let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition); + if (tmp) { + tmp = tmp[1]; + let filename = rfc2616unquote(tmp); + filename = unescape(filename); + filename = rfc5987decode(filename); + filename = rfc2047decode(filename); + return fixupEncoding(filename); + } + tmp = rfc2231getparam(contentDisposition); + if (tmp) { + const filename = rfc2047decode(tmp); + return fixupEncoding(filename); + } + tmp = toParamRegExp("filename", "i").exec(contentDisposition); + if (tmp) { + tmp = tmp[1]; + let filename = rfc2616unquote(tmp); + filename = rfc2047decode(filename); + return fixupEncoding(filename); + } + function toParamRegExp(attributePattern, flags) { + return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags); + } + function textdecode(encoding, value) { + if (encoding) { + if (!/^[\x00-\xFF]+$/.test(value)) { + return value; + } + try { + const decoder = new TextDecoder(encoding, { + fatal: true + }); + const buffer = stringToBytes(value); + value = decoder.decode(buffer); + needsEncodingFixup = false; + } catch {} + } + return value; + } + function fixupEncoding(value) { + if (needsEncodingFixup && /[\x80-\xff]/.test(value)) { + value = textdecode("utf-8", value); + if (needsEncodingFixup) { + value = textdecode("iso-8859-1", value); + } + } + return value; + } + function rfc2231getparam(contentDispositionStr) { + const matches = []; + let match; + const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig"); + while ((match = iter.exec(contentDispositionStr)) !== null) { + let [, n, quot, part] = match; + n = parseInt(n, 10); + if (n in matches) { + if (n === 0) { + break; + } + continue; + } + matches[n] = [quot, part]; + } + const parts = []; + for (let n = 0; n < matches.length; ++n) { + if (!(n in matches)) { + break; + } + let [quot, part] = matches[n]; + part = rfc2616unquote(part); + if (quot) { + part = unescape(part); + if (n === 0) { + part = rfc5987decode(part); + } + } + parts.push(part); + } + return parts.join(""); + } + function rfc2616unquote(value) { + if (value.startsWith('"')) { + const parts = value.slice(1).split('\\"'); + for (let i = 0; i < parts.length; ++i) { + const quotindex = parts[i].indexOf('"'); + if (quotindex !== -1) { + parts[i] = parts[i].slice(0, quotindex); + parts.length = i + 1; + } + parts[i] = parts[i].replaceAll(/\\(.)/g, "$1"); + } + value = parts.join('"'); + } + return value; + } + function rfc5987decode(extvalue) { + const encodingend = extvalue.indexOf("'"); + if (encodingend === -1) { + return extvalue; + } + const encoding = extvalue.slice(0, encodingend); + const langvalue = extvalue.slice(encodingend + 1); + const value = langvalue.replace(/^[^']*'/, ""); + return textdecode(encoding, value); + } + function rfc2047decode(value) { + if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) { + return value; + } + return value.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) { + if (encoding === "q" || encoding === "Q") { + text = text.replaceAll("_", " "); + text = text.replaceAll(/=([0-9a-fA-F]{2})/g, function (match, hex) { + return String.fromCharCode(parseInt(hex, 16)); + }); + return textdecode(charset, text); + } + try { + text = atob(text); + } catch {} + return textdecode(charset, text); + }); + } + return ""; +} + +;// ./src/display/network_utils.js + + + +function createHeaders(isHttp, httpHeaders) { + const headers = new Headers(); + if (!isHttp || !httpHeaders || typeof httpHeaders !== "object") { + return headers; + } + for (const key in httpHeaders) { + const val = httpHeaders[key]; + if (val !== undefined) { + headers.append(key, val); + } + } + return headers; +} +function getResponseOrigin(url) { + try { + return new URL(url).origin; + } catch {} + return null; +} +function validateRangeRequestCapabilities({ + responseHeaders, + isHttp, + rangeChunkSize, + disableRange +}) { + const returnValues = { + allowRangeRequests: false, + suggestedLength: undefined + }; + const length = parseInt(responseHeaders.get("Content-Length"), 10); + if (!Number.isInteger(length)) { + return returnValues; + } + returnValues.suggestedLength = length; + if (length <= 2 * rangeChunkSize) { + return returnValues; + } + if (disableRange || !isHttp) { + return returnValues; + } + if (responseHeaders.get("Accept-Ranges") !== "bytes") { + return returnValues; + } + const contentEncoding = responseHeaders.get("Content-Encoding") || "identity"; + if (contentEncoding !== "identity") { + return returnValues; + } + returnValues.allowRangeRequests = true; + return returnValues; +} +function extractFilenameFromHeader(responseHeaders) { + const contentDisposition = responseHeaders.get("Content-Disposition"); + if (contentDisposition) { + let filename = getFilenameFromContentDispositionHeader(contentDisposition); + if (filename.includes("%")) { + try { + filename = decodeURIComponent(filename); + } catch {} + } + if (isPdfFile(filename)) { + return filename; + } + } + return null; +} +function createResponseStatusError(status, url) { + if (status === 404 || status === 0 && url.startsWith("file:")) { + return new MissingPDFException('Missing PDF "' + url + '".'); + } + return new UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status); +} +function validateResponseStatus(status) { + return status === 200 || status === 206; +} + +;// ./src/display/fetch_stream.js + + +function createFetchOptions(headers, withCredentials, abortController) { + return { + method: "GET", + headers, + signal: abortController.signal, + mode: "cors", + credentials: withCredentials ? "include" : "same-origin", + redirect: "follow" + }; +} +function getArrayBuffer(val) { + if (val instanceof Uint8Array) { + return val.buffer; + } + if (val instanceof ArrayBuffer) { + return val; + } + warn(`getArrayBuffer - unexpected data format: ${val}`); + return new Uint8Array(val).buffer; +} +class PDFFetchStream { + _responseOrigin = null; + constructor(source) { + this.source = source; + this.isHttp = /^https?:/i.test(source.url); + this.headers = createHeaders(this.isHttp, source.httpHeaders); + this._fullRequestReader = null; + this._rangeRequestReaders = []; + } + get _progressiveDataLength() { + return this._fullRequestReader?._loaded ?? 0; + } + getFullReader() { + assert(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once."); + this._fullRequestReader = new PDFFetchStreamReader(this); + return this._fullRequestReader; + } + getRangeReader(begin, end) { + if (end <= this._progressiveDataLength) { + return null; + } + const reader = new PDFFetchStreamRangeReader(this, begin, end); + this._rangeRequestReaders.push(reader); + return reader; + } + cancelAllRequests(reason) { + this._fullRequestReader?.cancel(reason); + for (const reader of this._rangeRequestReaders.slice(0)) { + reader.cancel(reason); + } + } +} +class PDFFetchStreamReader { + constructor(stream) { + this._stream = stream; + this._reader = null; + this._loaded = 0; + this._filename = null; + const source = stream.source; + this._withCredentials = source.withCredentials || false; + this._contentLength = source.length; + this._headersCapability = Promise.withResolvers(); + this._disableRange = source.disableRange || false; + this._rangeChunkSize = source.rangeChunkSize; + if (!this._rangeChunkSize && !this._disableRange) { + this._disableRange = true; + } + this._abortController = new AbortController(); + this._isStreamingSupported = !source.disableStream; + this._isRangeSupported = !source.disableRange; + const headers = new Headers(stream.headers); + const url = source.url; + fetch(url, createFetchOptions(headers, this._withCredentials, this._abortController)).then(response => { + stream._responseOrigin = getResponseOrigin(response.url); + if (!validateResponseStatus(response.status)) { + throw createResponseStatusError(response.status, url); + } + this._reader = response.body.getReader(); + this._headersCapability.resolve(); + const responseHeaders = response.headers; + const { + allowRangeRequests, + suggestedLength + } = validateRangeRequestCapabilities({ + responseHeaders, + isHttp: stream.isHttp, + rangeChunkSize: this._rangeChunkSize, + disableRange: this._disableRange + }); + this._isRangeSupported = allowRangeRequests; + this._contentLength = suggestedLength || this._contentLength; + this._filename = extractFilenameFromHeader(responseHeaders); + if (!this._isStreamingSupported && this._isRangeSupported) { + this.cancel(new AbortException("Streaming is disabled.")); + } + }).catch(this._headersCapability.reject); + this.onProgress = null; + } + get headersReady() { + return this._headersCapability.promise; + } + get filename() { + return this._filename; + } + get contentLength() { + return this._contentLength; + } + get isRangeSupported() { + return this._isRangeSupported; + } + get isStreamingSupported() { + return this._isStreamingSupported; + } + async read() { + await this._headersCapability.promise; + const { + value, + done + } = await this._reader.read(); + if (done) { + return { + value, + done + }; + } + this._loaded += value.byteLength; + this.onProgress?.({ + loaded: this._loaded, + total: this._contentLength + }); + return { + value: getArrayBuffer(value), + done: false + }; + } + cancel(reason) { + this._reader?.cancel(reason); + this._abortController.abort(); + } +} +class PDFFetchStreamRangeReader { + constructor(stream, begin, end) { + this._stream = stream; + this._reader = null; + this._loaded = 0; + const source = stream.source; + this._withCredentials = source.withCredentials || false; + this._readCapability = Promise.withResolvers(); + this._isStreamingSupported = !source.disableStream; + this._abortController = new AbortController(); + const headers = new Headers(stream.headers); + headers.append("Range", `bytes=${begin}-${end - 1}`); + const url = source.url; + fetch(url, createFetchOptions(headers, this._withCredentials, this._abortController)).then(response => { + const responseOrigin = getResponseOrigin(response.url); + if (responseOrigin !== stream._responseOrigin) { + throw new Error(`Expected range response-origin "${responseOrigin}" to match "${stream._responseOrigin}".`); + } + if (!validateResponseStatus(response.status)) { + throw createResponseStatusError(response.status, url); + } + this._readCapability.resolve(); + this._reader = response.body.getReader(); + }).catch(this._readCapability.reject); + this.onProgress = null; + } + get isStreamingSupported() { + return this._isStreamingSupported; + } + async read() { + await this._readCapability.promise; + const { + value, + done + } = await this._reader.read(); + if (done) { + return { + value, + done + }; + } + this._loaded += value.byteLength; + this.onProgress?.({ + loaded: this._loaded + }); + return { + value: getArrayBuffer(value), + done: false + }; + } + cancel(reason) { + this._reader?.cancel(reason); + this._abortController.abort(); + } +} + +;// ./src/display/network.js + + +const OK_RESPONSE = 200; +const PARTIAL_CONTENT_RESPONSE = 206; +function network_getArrayBuffer(xhr) { + const data = xhr.response; + if (typeof data !== "string") { + return data; + } + return stringToBytes(data).buffer; +} +class NetworkManager { + _responseOrigin = null; + constructor({ + url, + httpHeaders, + withCredentials + }) { + this.url = url; + this.isHttp = /^https?:/i.test(url); + this.headers = createHeaders(this.isHttp, httpHeaders); + this.withCredentials = withCredentials || false; + this.currXhrId = 0; + this.pendingRequests = Object.create(null); + } + requestRange(begin, end, listeners) { + const args = { + begin, + end + }; + for (const prop in listeners) { + args[prop] = listeners[prop]; + } + return this.request(args); + } + requestFull(listeners) { + return this.request(listeners); + } + request(args) { + const xhr = new XMLHttpRequest(); + const xhrId = this.currXhrId++; + const pendingRequest = this.pendingRequests[xhrId] = { + xhr + }; + xhr.open("GET", this.url); + xhr.withCredentials = this.withCredentials; + for (const [key, val] of this.headers) { + xhr.setRequestHeader(key, val); + } + if (this.isHttp && "begin" in args && "end" in args) { + xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`); + pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE; + } else { + pendingRequest.expectedStatus = OK_RESPONSE; + } + xhr.responseType = "arraybuffer"; + if (args.onError) { + xhr.onerror = function (evt) { + args.onError(xhr.status); + }; + } + xhr.onreadystatechange = this.onStateChange.bind(this, xhrId); + xhr.onprogress = this.onProgress.bind(this, xhrId); + pendingRequest.onHeadersReceived = args.onHeadersReceived; + pendingRequest.onDone = args.onDone; + pendingRequest.onError = args.onError; + pendingRequest.onProgress = args.onProgress; + xhr.send(null); + return xhrId; + } + onProgress(xhrId, evt) { + const pendingRequest = this.pendingRequests[xhrId]; + if (!pendingRequest) { + return; + } + pendingRequest.onProgress?.(evt); + } + onStateChange(xhrId, evt) { + const pendingRequest = this.pendingRequests[xhrId]; + if (!pendingRequest) { + return; + } + const xhr = pendingRequest.xhr; + if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) { + pendingRequest.onHeadersReceived(); + delete pendingRequest.onHeadersReceived; + } + if (xhr.readyState !== 4) { + return; + } + if (!(xhrId in this.pendingRequests)) { + return; + } + delete this.pendingRequests[xhrId]; + if (xhr.status === 0 && this.isHttp) { + pendingRequest.onError?.(xhr.status); + return; + } + const xhrStatus = xhr.status || OK_RESPONSE; + const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE; + if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) { + pendingRequest.onError?.(xhr.status); + return; + } + const chunk = network_getArrayBuffer(xhr); + if (xhrStatus === PARTIAL_CONTENT_RESPONSE) { + const rangeHeader = xhr.getResponseHeader("Content-Range"); + const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader); + pendingRequest.onDone({ + begin: parseInt(matches[1], 10), + chunk + }); + } else if (chunk) { + pendingRequest.onDone({ + begin: 0, + chunk + }); + } else { + pendingRequest.onError?.(xhr.status); + } + } + getRequestXhr(xhrId) { + return this.pendingRequests[xhrId].xhr; + } + isPendingRequest(xhrId) { + return xhrId in this.pendingRequests; + } + abortRequest(xhrId) { + const xhr = this.pendingRequests[xhrId].xhr; + delete this.pendingRequests[xhrId]; + xhr.abort(); + } +} +class PDFNetworkStream { + constructor(source) { + this._source = source; + this._manager = new NetworkManager(source); + this._rangeChunkSize = source.rangeChunkSize; + this._fullRequestReader = null; + this._rangeRequestReaders = []; + } + _onRangeRequestReaderClosed(reader) { + const i = this._rangeRequestReaders.indexOf(reader); + if (i >= 0) { + this._rangeRequestReaders.splice(i, 1); + } + } + getFullReader() { + assert(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once."); + this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source); + return this._fullRequestReader; + } + getRangeReader(begin, end) { + const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end); + reader.onClosed = this._onRangeRequestReaderClosed.bind(this); + this._rangeRequestReaders.push(reader); + return reader; + } + cancelAllRequests(reason) { + this._fullRequestReader?.cancel(reason); + for (const reader of this._rangeRequestReaders.slice(0)) { + reader.cancel(reason); + } + } +} +class PDFNetworkStreamFullRequestReader { + constructor(manager, source) { + this._manager = manager; + const args = { + onHeadersReceived: this._onHeadersReceived.bind(this), + onDone: this._onDone.bind(this), + onError: this._onError.bind(this), + onProgress: this._onProgress.bind(this) + }; + this._url = source.url; + this._fullRequestId = manager.requestFull(args); + this._headersCapability = Promise.withResolvers(); + this._disableRange = source.disableRange || false; + this._contentLength = source.length; + this._rangeChunkSize = source.rangeChunkSize; + if (!this._rangeChunkSize && !this._disableRange) { + this._disableRange = true; + } + this._isStreamingSupported = false; + this._isRangeSupported = false; + this._cachedChunks = []; + this._requests = []; + this._done = false; + this._storedError = undefined; + this._filename = null; + this.onProgress = null; + } + _onHeadersReceived() { + const fullRequestXhrId = this._fullRequestId; + const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId); + this._manager._responseOrigin = getResponseOrigin(fullRequestXhr.responseURL); + const rawResponseHeaders = fullRequestXhr.getAllResponseHeaders(); + const responseHeaders = new Headers(rawResponseHeaders ? rawResponseHeaders.trim().split(/[\r\n]+/).map(x => { + const [key, ...val] = x.split(": "); + return [key, val.join(": ")]; + }) : []); + const { + allowRangeRequests, + suggestedLength + } = validateRangeRequestCapabilities({ + responseHeaders, + isHttp: this._manager.isHttp, + rangeChunkSize: this._rangeChunkSize, + disableRange: this._disableRange + }); + if (allowRangeRequests) { + this._isRangeSupported = true; + } + this._contentLength = suggestedLength || this._contentLength; + this._filename = extractFilenameFromHeader(responseHeaders); + if (this._isRangeSupported) { + this._manager.abortRequest(fullRequestXhrId); + } + this._headersCapability.resolve(); + } + _onDone(data) { + if (data) { + if (this._requests.length > 0) { + const requestCapability = this._requests.shift(); + requestCapability.resolve({ + value: data.chunk, + done: false + }); + } else { + this._cachedChunks.push(data.chunk); + } + } + this._done = true; + if (this._cachedChunks.length > 0) { + return; + } + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: undefined, + done: true + }); + } + this._requests.length = 0; + } + _onError(status) { + this._storedError = createResponseStatusError(status, this._url); + this._headersCapability.reject(this._storedError); + for (const requestCapability of this._requests) { + requestCapability.reject(this._storedError); + } + this._requests.length = 0; + this._cachedChunks.length = 0; + } + _onProgress(evt) { + this.onProgress?.({ + loaded: evt.loaded, + total: evt.lengthComputable ? evt.total : this._contentLength + }); + } + get filename() { + return this._filename; + } + get isRangeSupported() { + return this._isRangeSupported; + } + get isStreamingSupported() { + return this._isStreamingSupported; + } + get contentLength() { + return this._contentLength; + } + get headersReady() { + return this._headersCapability.promise; + } + async read() { + await this._headersCapability.promise; + if (this._storedError) { + throw this._storedError; + } + if (this._cachedChunks.length > 0) { + const chunk = this._cachedChunks.shift(); + return { + value: chunk, + done: false + }; + } + if (this._done) { + return { + value: undefined, + done: true + }; + } + const requestCapability = Promise.withResolvers(); + this._requests.push(requestCapability); + return requestCapability.promise; + } + cancel(reason) { + this._done = true; + this._headersCapability.reject(reason); + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: undefined, + done: true + }); + } + this._requests.length = 0; + if (this._manager.isPendingRequest(this._fullRequestId)) { + this._manager.abortRequest(this._fullRequestId); + } + this._fullRequestReader = null; + } +} +class PDFNetworkStreamRangeRequestReader { + constructor(manager, begin, end) { + this._manager = manager; + const args = { + onHeadersReceived: this._onHeadersReceived.bind(this), + onDone: this._onDone.bind(this), + onError: this._onError.bind(this), + onProgress: this._onProgress.bind(this) + }; + this._url = manager.url; + this._requestId = manager.requestRange(begin, end, args); + this._requests = []; + this._queuedChunk = null; + this._done = false; + this._storedError = undefined; + this.onProgress = null; + this.onClosed = null; + } + _onHeadersReceived() { + const responseOrigin = getResponseOrigin(this._manager.getRequestXhr(this._requestId)?.responseURL); + if (responseOrigin !== this._manager._responseOrigin) { + this._storedError = new Error(`Expected range response-origin "${responseOrigin}" to match "${this._manager._responseOrigin}".`); + this._onError(0); + } + } + _close() { + this.onClosed?.(this); + } + _onDone(data) { + const chunk = data.chunk; + if (this._requests.length > 0) { + const requestCapability = this._requests.shift(); + requestCapability.resolve({ + value: chunk, + done: false + }); + } else { + this._queuedChunk = chunk; + } + this._done = true; + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: undefined, + done: true + }); + } + this._requests.length = 0; + this._close(); + } + _onError(status) { + this._storedError ??= createResponseStatusError(status, this._url); + for (const requestCapability of this._requests) { + requestCapability.reject(this._storedError); + } + this._requests.length = 0; + this._queuedChunk = null; + } + _onProgress(evt) { + if (!this.isStreamingSupported) { + this.onProgress?.({ + loaded: evt.loaded + }); + } + } + get isStreamingSupported() { + return false; + } + async read() { + if (this._storedError) { + throw this._storedError; + } + if (this._queuedChunk !== null) { + const chunk = this._queuedChunk; + this._queuedChunk = null; + return { + value: chunk, + done: false + }; + } + if (this._done) { + return { + value: undefined, + done: true + }; + } + const requestCapability = Promise.withResolvers(); + this._requests.push(requestCapability); + return requestCapability.promise; + } + cancel(reason) { + this._done = true; + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: undefined, + done: true + }); + } + this._requests.length = 0; + if (this._manager.isPendingRequest(this._requestId)) { + this._manager.abortRequest(this._requestId); + } + this._close(); + } +} + +;// ./src/display/node_stream.js + +const urlRegex = /^[a-z][a-z0-9\-+.]+:/i; +function parseUrlOrPath(sourceUrl) { + if (urlRegex.test(sourceUrl)) { + return new URL(sourceUrl); + } + const url = process.getBuiltinModule("url"); + return new URL(url.pathToFileURL(sourceUrl)); +} +class PDFNodeStream { + constructor(source) { + this.source = source; + this.url = parseUrlOrPath(source.url); + assert(this.url.protocol === "file:", "PDFNodeStream only supports file:// URLs."); + this._fullRequestReader = null; + this._rangeRequestReaders = []; + } + get _progressiveDataLength() { + return this._fullRequestReader?._loaded ?? 0; + } + getFullReader() { + assert(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once."); + this._fullRequestReader = new PDFNodeStreamFsFullReader(this); + return this._fullRequestReader; + } + getRangeReader(start, end) { + if (end <= this._progressiveDataLength) { + return null; + } + const rangeReader = new PDFNodeStreamFsRangeReader(this, start, end); + this._rangeRequestReaders.push(rangeReader); + return rangeReader; + } + cancelAllRequests(reason) { + this._fullRequestReader?.cancel(reason); + for (const reader of this._rangeRequestReaders.slice(0)) { + reader.cancel(reason); + } + } +} +class PDFNodeStreamFsFullReader { + constructor(stream) { + this._url = stream.url; + this._done = false; + this._storedError = null; + this.onProgress = null; + const source = stream.source; + this._contentLength = source.length; + this._loaded = 0; + this._filename = null; + this._disableRange = source.disableRange || false; + this._rangeChunkSize = source.rangeChunkSize; + if (!this._rangeChunkSize && !this._disableRange) { + this._disableRange = true; + } + this._isStreamingSupported = !source.disableStream; + this._isRangeSupported = !source.disableRange; + this._readableStream = null; + this._readCapability = Promise.withResolvers(); + this._headersCapability = Promise.withResolvers(); + const fs = process.getBuiltinModule("fs"); + fs.promises.lstat(this._url).then(stat => { + this._contentLength = stat.size; + this._setReadableStream(fs.createReadStream(this._url)); + this._headersCapability.resolve(); + }, error => { + if (error.code === "ENOENT") { + error = new MissingPDFException(`Missing PDF "${this._url}".`); + } + this._storedError = error; + this._headersCapability.reject(error); + }); + } + get headersReady() { + return this._headersCapability.promise; + } + get filename() { + return this._filename; + } + get contentLength() { + return this._contentLength; + } + get isRangeSupported() { + return this._isRangeSupported; + } + get isStreamingSupported() { + return this._isStreamingSupported; + } + async read() { + await this._readCapability.promise; + if (this._done) { + return { + value: undefined, + done: true + }; + } + if (this._storedError) { + throw this._storedError; + } + const chunk = this._readableStream.read(); + if (chunk === null) { + this._readCapability = Promise.withResolvers(); + return this.read(); + } + this._loaded += chunk.length; + this.onProgress?.({ + loaded: this._loaded, + total: this._contentLength + }); + const buffer = new Uint8Array(chunk).buffer; + return { + value: buffer, + done: false + }; + } + cancel(reason) { + if (!this._readableStream) { + this._error(reason); + return; + } + this._readableStream.destroy(reason); + } + _error(reason) { + this._storedError = reason; + this._readCapability.resolve(); + } + _setReadableStream(readableStream) { + this._readableStream = readableStream; + readableStream.on("readable", () => { + this._readCapability.resolve(); + }); + readableStream.on("end", () => { + readableStream.destroy(); + this._done = true; + this._readCapability.resolve(); + }); + readableStream.on("error", reason => { + this._error(reason); + }); + if (!this._isStreamingSupported && this._isRangeSupported) { + this._error(new AbortException("streaming is disabled")); + } + if (this._storedError) { + this._readableStream.destroy(this._storedError); + } + } +} +class PDFNodeStreamFsRangeReader { + constructor(stream, start, end) { + this._url = stream.url; + this._done = false; + this._storedError = null; + this.onProgress = null; + this._loaded = 0; + this._readableStream = null; + this._readCapability = Promise.withResolvers(); + const source = stream.source; + this._isStreamingSupported = !source.disableStream; + const fs = process.getBuiltinModule("fs"); + this._setReadableStream(fs.createReadStream(this._url, { + start, + end: end - 1 + })); + } + get isStreamingSupported() { + return this._isStreamingSupported; + } + async read() { + await this._readCapability.promise; + if (this._done) { + return { + value: undefined, + done: true + }; + } + if (this._storedError) { + throw this._storedError; + } + const chunk = this._readableStream.read(); + if (chunk === null) { + this._readCapability = Promise.withResolvers(); + return this.read(); + } + this._loaded += chunk.length; + this.onProgress?.({ + loaded: this._loaded + }); + const buffer = new Uint8Array(chunk).buffer; + return { + value: buffer, + done: false + }; + } + cancel(reason) { + if (!this._readableStream) { + this._error(reason); + return; + } + this._readableStream.destroy(reason); + } + _error(reason) { + this._storedError = reason; + this._readCapability.resolve(); + } + _setReadableStream(readableStream) { + this._readableStream = readableStream; + readableStream.on("readable", () => { + this._readCapability.resolve(); + }); + readableStream.on("end", () => { + readableStream.destroy(); + this._done = true; + this._readCapability.resolve(); + }); + readableStream.on("error", reason => { + this._error(reason); + }); + if (this._storedError) { + this._readableStream.destroy(this._storedError); + } + } +} + +;// ./src/display/text_layer.js + + +const MAX_TEXT_DIVS_TO_RENDER = 100000; +const DEFAULT_FONT_SIZE = 30; +const DEFAULT_FONT_ASCENT = 0.8; +class TextLayer { + #capability = Promise.withResolvers(); + #container = null; + #disableProcessItems = false; + #fontInspectorEnabled = !!globalThis.FontInspector?.enabled; + #lang = null; + #layoutTextParams = null; + #pageHeight = 0; + #pageWidth = 0; + #reader = null; + #rootContainer = null; + #rotation = 0; + #scale = 0; + #styleCache = Object.create(null); + #textContentItemsStr = []; + #textContentSource = null; + #textDivs = []; + #textDivProperties = new WeakMap(); + #transform = null; + static #ascentCache = new Map(); + static #canvasContexts = new Map(); + static #canvasCtxFonts = new WeakMap(); + static #minFontSize = null; + static #pendingTextLayers = new Set(); + constructor({ + textContentSource, + container, + viewport + }) { + if (textContentSource instanceof ReadableStream) { + this.#textContentSource = textContentSource; + } else if (typeof textContentSource === "object") { + this.#textContentSource = new ReadableStream({ + start(controller) { + controller.enqueue(textContentSource); + controller.close(); + } + }); + } else { + throw new Error('No "textContentSource" parameter specified.'); + } + this.#container = this.#rootContainer = container; + this.#scale = viewport.scale * (globalThis.devicePixelRatio || 1); + this.#rotation = viewport.rotation; + this.#layoutTextParams = { + div: null, + properties: null, + ctx: null + }; + const { + pageWidth, + pageHeight, + pageX, + pageY + } = viewport.rawDims; + this.#transform = [1, 0, 0, -1, -pageX, pageY + pageHeight]; + this.#pageWidth = pageWidth; + this.#pageHeight = pageHeight; + TextLayer.#ensureMinFontSizeComputed(); + setLayerDimensions(container, viewport); + this.#capability.promise.finally(() => { + TextLayer.#pendingTextLayers.delete(this); + this.#layoutTextParams = null; + this.#styleCache = null; + }).catch(() => {}); + } + static get fontFamilyMap() { + const { + isWindows, + isFirefox + } = util_FeatureTest.platform; + return shadow(this, "fontFamilyMap", new Map([["sans-serif", `${isWindows && isFirefox ? "Calibri, " : ""}sans-serif`], ["monospace", `${isWindows && isFirefox ? "Lucida Console, " : ""}monospace`]])); + } + render() { + const pump = () => { + this.#reader.read().then(({ + value, + done + }) => { + if (done) { + this.#capability.resolve(); + return; + } + this.#lang ??= value.lang; + Object.assign(this.#styleCache, value.styles); + this.#processItems(value.items); + pump(); + }, this.#capability.reject); + }; + this.#reader = this.#textContentSource.getReader(); + TextLayer.#pendingTextLayers.add(this); + pump(); + return this.#capability.promise; + } + update({ + viewport, + onBefore = null + }) { + const scale = viewport.scale * (globalThis.devicePixelRatio || 1); + const rotation = viewport.rotation; + if (rotation !== this.#rotation) { + onBefore?.(); + this.#rotation = rotation; + setLayerDimensions(this.#rootContainer, { + rotation + }); + } + if (scale !== this.#scale) { + onBefore?.(); + this.#scale = scale; + const params = { + div: null, + properties: null, + ctx: TextLayer.#getCtx(this.#lang) + }; + for (const div of this.#textDivs) { + params.properties = this.#textDivProperties.get(div); + params.div = div; + this.#layout(params); + } + } + } + cancel() { + const abortEx = new AbortException("TextLayer task cancelled."); + this.#reader?.cancel(abortEx).catch(() => {}); + this.#reader = null; + this.#capability.reject(abortEx); + } + get textDivs() { + return this.#textDivs; + } + get textContentItemsStr() { + return this.#textContentItemsStr; + } + #processItems(items) { + if (this.#disableProcessItems) { + return; + } + this.#layoutTextParams.ctx ??= TextLayer.#getCtx(this.#lang); + const textDivs = this.#textDivs, + textContentItemsStr = this.#textContentItemsStr; + for (const item of items) { + if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) { + warn("Ignoring additional textDivs for performance reasons."); + this.#disableProcessItems = true; + return; + } + if (item.str === undefined) { + if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") { + const parent = this.#container; + this.#container = document.createElement("span"); + this.#container.classList.add("markedContent"); + if (item.id !== null) { + this.#container.setAttribute("id", `${item.id}`); + } + parent.append(this.#container); + } else if (item.type === "endMarkedContent") { + this.#container = this.#container.parentNode; + } + continue; + } + textContentItemsStr.push(item.str); + this.#appendText(item); + } + } + #appendText(geom) { + const textDiv = document.createElement("span"); + const textDivProperties = { + angle: 0, + canvasWidth: 0, + hasText: geom.str !== "", + hasEOL: geom.hasEOL, + fontSize: 0 + }; + this.#textDivs.push(textDiv); + const tx = Util.transform(this.#transform, geom.transform); + let angle = Math.atan2(tx[1], tx[0]); + const style = this.#styleCache[geom.fontName]; + if (style.vertical) { + angle += Math.PI / 2; + } + let fontFamily = this.#fontInspectorEnabled && style.fontSubstitution || style.fontFamily; + fontFamily = TextLayer.fontFamilyMap.get(fontFamily) || fontFamily; + const fontHeight = Math.hypot(tx[2], tx[3]); + const fontAscent = fontHeight * TextLayer.#getAscent(fontFamily, this.#lang); + let left, top; + if (angle === 0) { + left = tx[4]; + top = tx[5] - fontAscent; + } else { + left = tx[4] + fontAscent * Math.sin(angle); + top = tx[5] - fontAscent * Math.cos(angle); + } + const scaleFactorStr = "calc(var(--scale-factor)*"; + const divStyle = textDiv.style; + if (this.#container === this.#rootContainer) { + divStyle.left = `${(100 * left / this.#pageWidth).toFixed(2)}%`; + divStyle.top = `${(100 * top / this.#pageHeight).toFixed(2)}%`; + } else { + divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`; + divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`; + } + divStyle.fontSize = `${scaleFactorStr}${(TextLayer.#minFontSize * fontHeight).toFixed(2)}px)`; + divStyle.fontFamily = fontFamily; + textDivProperties.fontSize = fontHeight; + textDiv.setAttribute("role", "presentation"); + textDiv.textContent = geom.str; + textDiv.dir = geom.dir; + if (this.#fontInspectorEnabled) { + textDiv.dataset.fontName = style.fontSubstitutionLoadedName || geom.fontName; + } + if (angle !== 0) { + textDivProperties.angle = angle * (180 / Math.PI); + } + let shouldScaleText = false; + if (geom.str.length > 1) { + shouldScaleText = true; + } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) { + const absScaleX = Math.abs(geom.transform[0]), + absScaleY = Math.abs(geom.transform[3]); + if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) { + shouldScaleText = true; + } + } + if (shouldScaleText) { + textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width; + } + this.#textDivProperties.set(textDiv, textDivProperties); + this.#layoutTextParams.div = textDiv; + this.#layoutTextParams.properties = textDivProperties; + this.#layout(this.#layoutTextParams); + if (textDivProperties.hasText) { + this.#container.append(textDiv); + } + if (textDivProperties.hasEOL) { + const br = document.createElement("br"); + br.setAttribute("role", "presentation"); + this.#container.append(br); + } + } + #layout(params) { + const { + div, + properties, + ctx + } = params; + const { + style + } = div; + let transform = ""; + if (TextLayer.#minFontSize > 1) { + transform = `scale(${1 / TextLayer.#minFontSize})`; + } + if (properties.canvasWidth !== 0 && properties.hasText) { + const { + fontFamily + } = style; + const { + canvasWidth, + fontSize + } = properties; + TextLayer.#ensureCtxFont(ctx, fontSize * this.#scale, fontFamily); + const { + width + } = ctx.measureText(div.textContent); + if (width > 0) { + transform = `scaleX(${canvasWidth * this.#scale / width}) ${transform}`; + } + } + if (properties.angle !== 0) { + transform = `rotate(${properties.angle}deg) ${transform}`; + } + if (transform.length > 0) { + style.transform = transform; + } + } + static cleanup() { + if (this.#pendingTextLayers.size > 0) { + return; + } + this.#ascentCache.clear(); + for (const { + canvas + } of this.#canvasContexts.values()) { + canvas.remove(); + } + this.#canvasContexts.clear(); + } + static #getCtx(lang = null) { + let ctx = this.#canvasContexts.get(lang ||= ""); + if (!ctx) { + const canvas = document.createElement("canvas"); + canvas.className = "hiddenCanvasElement"; + canvas.lang = lang; + document.body.append(canvas); + ctx = canvas.getContext("2d", { + alpha: false, + willReadFrequently: true + }); + this.#canvasContexts.set(lang, ctx); + this.#canvasCtxFonts.set(ctx, { + size: 0, + family: "" + }); + } + return ctx; + } + static #ensureCtxFont(ctx, size, family) { + const cached = this.#canvasCtxFonts.get(ctx); + if (size === cached.size && family === cached.family) { + return; + } + ctx.font = `${size}px ${family}`; + cached.size = size; + cached.family = family; + } + static #ensureMinFontSizeComputed() { + if (this.#minFontSize !== null) { + return; + } + const div = document.createElement("div"); + div.style.opacity = 0; + div.style.lineHeight = 1; + div.style.fontSize = "1px"; + div.style.position = "absolute"; + div.textContent = "X"; + document.body.append(div); + this.#minFontSize = div.getBoundingClientRect().height; + div.remove(); + } + static #getAscent(fontFamily, lang) { + const cachedAscent = this.#ascentCache.get(fontFamily); + if (cachedAscent) { + return cachedAscent; + } + const ctx = this.#getCtx(lang); + ctx.canvas.width = ctx.canvas.height = DEFAULT_FONT_SIZE; + this.#ensureCtxFont(ctx, DEFAULT_FONT_SIZE, fontFamily); + const metrics = ctx.measureText(""); + let ascent = metrics.fontBoundingBoxAscent; + let descent = Math.abs(metrics.fontBoundingBoxDescent); + if (ascent) { + const ratio = ascent / (ascent + descent); + this.#ascentCache.set(fontFamily, ratio); + ctx.canvas.width = ctx.canvas.height = 0; + return ratio; + } + ctx.strokeStyle = "red"; + ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE); + ctx.strokeText("g", 0, 0); + let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data; + descent = 0; + for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) { + if (pixels[i] > 0) { + descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE); + break; + } + } + ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE); + ctx.strokeText("A", 0, DEFAULT_FONT_SIZE); + pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data; + ascent = 0; + for (let i = 0, ii = pixels.length; i < ii; i += 4) { + if (pixels[i] > 0) { + ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE); + break; + } + } + ctx.canvas.width = ctx.canvas.height = 0; + const ratio = ascent ? ascent / (ascent + descent) : DEFAULT_FONT_ASCENT; + this.#ascentCache.set(fontFamily, ratio); + return ratio; + } +} + +;// ./src/display/xfa_text.js +class XfaText { + static textContent(xfa) { + const items = []; + const output = { + items, + styles: Object.create(null) + }; + function walk(node) { + if (!node) { + return; + } + let str = null; + const name = node.name; + if (name === "#text") { + str = node.value; + } else if (!XfaText.shouldBuildText(name)) { + return; + } else if (node?.attributes?.textContent) { + str = node.attributes.textContent; + } else if (node.value) { + str = node.value; + } + if (str !== null) { + items.push({ + str + }); + } + if (!node.children) { + return; + } + for (const child of node.children) { + walk(child); + } + } + walk(xfa); + return output; + } + static shouldBuildText(name) { + return !(name === "textarea" || name === "input" || name === "option" || name === "select"); + } +} + +;// ./src/display/api.js + + + + + + + + + + + + + + + + + + + + +const DEFAULT_RANGE_CHUNK_SIZE = 65536; +const RENDERING_CANCELLED_TIMEOUT = 100; +const DELAYED_CLEANUP_TIMEOUT = 5000; +const DefaultCanvasFactory = isNodeJS ? NodeCanvasFactory : DOMCanvasFactory; +const DefaultCMapReaderFactory = isNodeJS ? NodeCMapReaderFactory : DOMCMapReaderFactory; +const DefaultFilterFactory = isNodeJS ? NodeFilterFactory : DOMFilterFactory; +const DefaultStandardFontDataFactory = isNodeJS ? NodeStandardFontDataFactory : DOMStandardFontDataFactory; +function getDocument(src = {}) { + if (typeof src === "string" || src instanceof URL) { + src = { + url: src + }; + } else if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) { + src = { + data: src + }; + } + const task = new PDFDocumentLoadingTask(); + const { + docId + } = task; + const url = src.url ? getUrlProp(src.url) : null; + const data = src.data ? getDataProp(src.data) : null; + const httpHeaders = src.httpHeaders || null; + const withCredentials = src.withCredentials === true; + const password = src.password ?? null; + const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null; + const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : DEFAULT_RANGE_CHUNK_SIZE; + let worker = src.worker instanceof PDFWorker ? src.worker : null; + const verbosity = src.verbosity; + const docBaseUrl = typeof src.docBaseUrl === "string" && !isDataScheme(src.docBaseUrl) ? src.docBaseUrl : null; + const cMapUrl = typeof src.cMapUrl === "string" ? src.cMapUrl : null; + const cMapPacked = src.cMapPacked !== false; + const CMapReaderFactory = src.CMapReaderFactory || DefaultCMapReaderFactory; + const standardFontDataUrl = typeof src.standardFontDataUrl === "string" ? src.standardFontDataUrl : null; + const StandardFontDataFactory = src.StandardFontDataFactory || DefaultStandardFontDataFactory; + const ignoreErrors = src.stopAtErrors !== true; + const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1; + const isEvalSupported = src.isEvalSupported !== false; + const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !isNodeJS; + const isImageDecoderSupported = typeof src.isImageDecoderSupported === "boolean" ? src.isImageDecoderSupported : !isNodeJS && (util_FeatureTest.platform.isFirefox || !globalThis.chrome); + const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes) ? src.canvasMaxAreaInBytes : -1; + const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : isNodeJS; + const fontExtraProperties = src.fontExtraProperties === true; + const enableXfa = src.enableXfa === true; + const ownerDocument = src.ownerDocument || globalThis.document; + const disableRange = src.disableRange === true; + const disableStream = src.disableStream === true; + const disableAutoFetch = src.disableAutoFetch === true; + const pdfBug = src.pdfBug === true; + const CanvasFactory = src.CanvasFactory || DefaultCanvasFactory; + const FilterFactory = src.FilterFactory || DefaultFilterFactory; + const enableHWA = src.enableHWA === true; + const length = rangeTransport ? rangeTransport.length : src.length ?? NaN; + const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !isNodeJS && !disableFontFace; + const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : CMapReaderFactory === DOMCMapReaderFactory && StandardFontDataFactory === DOMStandardFontDataFactory && cMapUrl && standardFontDataUrl && isValidFetchUrl(cMapUrl, document.baseURI) && isValidFetchUrl(standardFontDataUrl, document.baseURI); + if (src.canvasFactory) { + deprecated("`canvasFactory`-instance option, please use `CanvasFactory` instead."); + } + if (src.filterFactory) { + deprecated("`filterFactory`-instance option, please use `FilterFactory` instead."); + } + const styleElement = null; + setVerbosityLevel(verbosity); + const transportFactory = { + canvasFactory: new CanvasFactory({ + ownerDocument, + enableHWA + }), + filterFactory: new FilterFactory({ + docId, + ownerDocument + }), + cMapReaderFactory: useWorkerFetch ? null : new CMapReaderFactory({ + baseUrl: cMapUrl, + isCompressed: cMapPacked + }), + standardFontDataFactory: useWorkerFetch ? null : new StandardFontDataFactory({ + baseUrl: standardFontDataUrl + }) + }; + if (!worker) { + const workerParams = { + verbosity, + port: GlobalWorkerOptions.workerPort + }; + worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams); + task._worker = worker; + } + const docParams = { + docId, + apiVersion: "4.9.155", + data, + password, + disableAutoFetch, + rangeChunkSize, + length, + docBaseUrl, + enableXfa, + evaluatorOptions: { + maxImageSize, + disableFontFace, + ignoreErrors, + isEvalSupported, + isOffscreenCanvasSupported, + isImageDecoderSupported, + canvasMaxAreaInBytes, + fontExtraProperties, + useSystemFonts, + cMapUrl: useWorkerFetch ? cMapUrl : null, + standardFontDataUrl: useWorkerFetch ? standardFontDataUrl : null + } + }; + const transportParams = { + disableFontFace, + fontExtraProperties, + ownerDocument, + pdfBug, + styleElement, + loadingParams: { + disableAutoFetch, + enableXfa + } + }; + worker.promise.then(function () { + if (task.destroyed) { + throw new Error("Loading aborted"); + } + if (worker.destroyed) { + throw new Error("Worker was destroyed"); + } + const workerIdPromise = worker.messageHandler.sendWithPromise("GetDocRequest", docParams, data ? [data.buffer] : null); + let networkStream; + if (rangeTransport) { + networkStream = new PDFDataTransportStream(rangeTransport, { + disableRange, + disableStream + }); + } else if (!data) { + if (!url) { + throw new Error("getDocument - no `url` parameter provided."); + } + let NetworkStream; + if (isNodeJS) { + if (isValidFetchUrl(url)) { + if (typeof fetch === "undefined" || typeof Response === "undefined" || !("body" in Response.prototype)) { + throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`."); + } + NetworkStream = PDFFetchStream; + } else { + NetworkStream = PDFNodeStream; + } + } else { + NetworkStream = isValidFetchUrl(url) ? PDFFetchStream : PDFNetworkStream; + } + networkStream = new NetworkStream({ + url, + length, + httpHeaders, + withCredentials, + rangeChunkSize, + disableRange, + disableStream + }); + } + return workerIdPromise.then(workerId => { + if (task.destroyed) { + throw new Error("Loading aborted"); + } + if (worker.destroyed) { + throw new Error("Worker was destroyed"); + } + const messageHandler = new MessageHandler(docId, workerId, worker.port); + const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory); + task._transport = transport; + messageHandler.send("Ready", null); + }); + }).catch(task._capability.reject); + return task; +} +function getUrlProp(val) { + if (val instanceof URL) { + return val.href; + } + try { + return new URL(val, window.location).href; + } catch { + if (isNodeJS && typeof val === "string") { + return val; + } + } + throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property."); +} +function getDataProp(val) { + if (isNodeJS && typeof Buffer !== "undefined" && val instanceof Buffer) { + throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`."); + } + if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) { + return val; + } + if (typeof val === "string") { + return stringToBytes(val); + } + if (val instanceof ArrayBuffer || ArrayBuffer.isView(val) || typeof val === "object" && !isNaN(val?.length)) { + return new Uint8Array(val); + } + throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property."); +} +function isRefProxy(ref) { + return typeof ref === "object" && Number.isInteger(ref?.num) && ref.num >= 0 && Number.isInteger(ref?.gen) && ref.gen >= 0; +} +class PDFDocumentLoadingTask { + static #docId = 0; + constructor() { + this._capability = Promise.withResolvers(); + this._transport = null; + this._worker = null; + this.docId = `d${PDFDocumentLoadingTask.#docId++}`; + this.destroyed = false; + this.onPassword = null; + this.onProgress = null; + } + get promise() { + return this._capability.promise; + } + async destroy() { + this.destroyed = true; + try { + if (this._worker?.port) { + this._worker._pendingDestroy = true; + } + await this._transport?.destroy(); + } catch (ex) { + if (this._worker?.port) { + delete this._worker._pendingDestroy; + } + throw ex; + } + this._transport = null; + this._worker?.destroy(); + this._worker = null; + } +} +class PDFDataRangeTransport { + constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) { + this.length = length; + this.initialData = initialData; + this.progressiveDone = progressiveDone; + this.contentDispositionFilename = contentDispositionFilename; + this._rangeListeners = []; + this._progressListeners = []; + this._progressiveReadListeners = []; + this._progressiveDoneListeners = []; + this._readyCapability = Promise.withResolvers(); + } + addRangeListener(listener) { + this._rangeListeners.push(listener); + } + addProgressListener(listener) { + this._progressListeners.push(listener); + } + addProgressiveReadListener(listener) { + this._progressiveReadListeners.push(listener); + } + addProgressiveDoneListener(listener) { + this._progressiveDoneListeners.push(listener); + } + onDataRange(begin, chunk) { + for (const listener of this._rangeListeners) { + listener(begin, chunk); + } + } + onDataProgress(loaded, total) { + this._readyCapability.promise.then(() => { + for (const listener of this._progressListeners) { + listener(loaded, total); + } + }); + } + onDataProgressiveRead(chunk) { + this._readyCapability.promise.then(() => { + for (const listener of this._progressiveReadListeners) { + listener(chunk); + } + }); + } + onDataProgressiveDone() { + this._readyCapability.promise.then(() => { + for (const listener of this._progressiveDoneListeners) { + listener(); + } + }); + } + transportReady() { + this._readyCapability.resolve(); + } + requestDataRange(begin, end) { + unreachable("Abstract method PDFDataRangeTransport.requestDataRange"); + } + abort() {} +} +class PDFDocumentProxy { + constructor(pdfInfo, transport) { + this._pdfInfo = pdfInfo; + this._transport = transport; + } + get annotationStorage() { + return this._transport.annotationStorage; + } + get canvasFactory() { + return this._transport.canvasFactory; + } + get filterFactory() { + return this._transport.filterFactory; + } + get numPages() { + return this._pdfInfo.numPages; + } + get fingerprints() { + return this._pdfInfo.fingerprints; + } + get isPureXfa() { + return shadow(this, "isPureXfa", !!this._transport._htmlForXfa); + } + get allXfaHtml() { + return this._transport._htmlForXfa; + } + getPage(pageNumber) { + return this._transport.getPage(pageNumber); + } + getPageIndex(ref) { + return this._transport.getPageIndex(ref); + } + getDestinations() { + return this._transport.getDestinations(); + } + getDestination(id) { + return this._transport.getDestination(id); + } + getPageLabels() { + return this._transport.getPageLabels(); + } + getPageLayout() { + return this._transport.getPageLayout(); + } + getPageMode() { + return this._transport.getPageMode(); + } + getViewerPreferences() { + return this._transport.getViewerPreferences(); + } + getOpenAction() { + return this._transport.getOpenAction(); + } + getAttachments() { + return this._transport.getAttachments(); + } + getJSActions() { + return this._transport.getDocJSActions(); + } + getOutline() { + return this._transport.getOutline(); + } + getOptionalContentConfig({ + intent = "display" + } = {}) { + const { + renderingIntent + } = this._transport.getRenderingIntent(intent); + return this._transport.getOptionalContentConfig(renderingIntent); + } + getPermissions() { + return this._transport.getPermissions(); + } + getMetadata() { + return this._transport.getMetadata(); + } + getMarkInfo() { + return this._transport.getMarkInfo(); + } + getData() { + return this._transport.getData(); + } + saveDocument() { + return this._transport.saveDocument(); + } + getDownloadInfo() { + return this._transport.downloadInfoCapability.promise; + } + cleanup(keepLoadedFonts = false) { + return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa); + } + destroy() { + return this.loadingTask.destroy(); + } + cachedPageNumber(ref) { + return this._transport.cachedPageNumber(ref); + } + get loadingParams() { + return this._transport.loadingParams; + } + get loadingTask() { + return this._transport.loadingTask; + } + getFieldObjects() { + return this._transport.getFieldObjects(); + } + hasJSActions() { + return this._transport.hasJSActions(); + } + getCalculationOrderIds() { + return this._transport.getCalculationOrderIds(); + } +} +class PDFPageProxy { + #delayedCleanupTimeout = null; + #pendingCleanup = false; + constructor(pageIndex, pageInfo, transport, pdfBug = false) { + this._pageIndex = pageIndex; + this._pageInfo = pageInfo; + this._transport = transport; + this._stats = pdfBug ? new StatTimer() : null; + this._pdfBug = pdfBug; + this.commonObjs = transport.commonObjs; + this.objs = new PDFObjects(); + this._maybeCleanupAfterRender = false; + this._intentStates = new Map(); + this.destroyed = false; + } + get pageNumber() { + return this._pageIndex + 1; + } + get rotate() { + return this._pageInfo.rotate; + } + get ref() { + return this._pageInfo.ref; + } + get userUnit() { + return this._pageInfo.userUnit; + } + get view() { + return this._pageInfo.view; + } + getViewport({ + scale, + rotation = this.rotate, + offsetX = 0, + offsetY = 0, + dontFlip = false + } = {}) { + return new PageViewport({ + viewBox: this.view, + scale, + rotation, + offsetX, + offsetY, + dontFlip + }); + } + getAnnotations({ + intent = "display" + } = {}) { + const { + renderingIntent + } = this._transport.getRenderingIntent(intent); + return this._transport.getAnnotations(this._pageIndex, renderingIntent); + } + getJSActions() { + return this._transport.getPageJSActions(this._pageIndex); + } + get filterFactory() { + return this._transport.filterFactory; + } + get isPureXfa() { + return shadow(this, "isPureXfa", !!this._transport._htmlForXfa); + } + async getXfa() { + return this._transport._htmlForXfa?.children[this._pageIndex] || null; + } + render({ + canvasContext, + viewport, + intent = "display", + annotationMode = AnnotationMode.ENABLE, + transform = null, + background = null, + optionalContentConfigPromise = null, + annotationCanvasMap = null, + pageColors = null, + printAnnotationStorage = null, + isEditing = false + }) { + this._stats?.time("Overall"); + const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing); + const { + renderingIntent, + cacheKey + } = intentArgs; + this.#pendingCleanup = false; + this.#abortDelayedCleanup(); + optionalContentConfigPromise ||= this._transport.getOptionalContentConfig(renderingIntent); + let intentState = this._intentStates.get(cacheKey); + if (!intentState) { + intentState = Object.create(null); + this._intentStates.set(cacheKey, intentState); + } + if (intentState.streamReaderCancelTimeout) { + clearTimeout(intentState.streamReaderCancelTimeout); + intentState.streamReaderCancelTimeout = null; + } + const intentPrint = !!(renderingIntent & RenderingIntentFlag.PRINT); + if (!intentState.displayReadyCapability) { + intentState.displayReadyCapability = Promise.withResolvers(); + intentState.operatorList = { + fnArray: [], + argsArray: [], + lastChunk: false, + separateAnnots: null + }; + this._stats?.time("Page Request"); + this._pumpOperatorList(intentArgs); + } + const complete = error => { + intentState.renderTasks.delete(internalRenderTask); + if (this._maybeCleanupAfterRender || intentPrint) { + this.#pendingCleanup = true; + } + this.#tryCleanup(!intentPrint); + if (error) { + internalRenderTask.capability.reject(error); + this._abortOperatorList({ + intentState, + reason: error instanceof Error ? error : new Error(error) + }); + } else { + internalRenderTask.capability.resolve(); + } + if (this._stats) { + this._stats.timeEnd("Rendering"); + this._stats.timeEnd("Overall"); + if (globalThis.Stats?.enabled) { + globalThis.Stats.add(this.pageNumber, this._stats); + } + } + }; + const internalRenderTask = new InternalRenderTask({ + callback: complete, + params: { + canvasContext, + viewport, + transform, + background + }, + objs: this.objs, + commonObjs: this.commonObjs, + annotationCanvasMap, + operatorList: intentState.operatorList, + pageIndex: this._pageIndex, + canvasFactory: this._transport.canvasFactory, + filterFactory: this._transport.filterFactory, + useRequestAnimationFrame: !intentPrint, + pdfBug: this._pdfBug, + pageColors + }); + (intentState.renderTasks ||= new Set()).add(internalRenderTask); + const renderTask = internalRenderTask.task; + Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => { + if (this.destroyed) { + complete(); + return; + } + this._stats?.time("Rendering"); + if (!(optionalContentConfig.renderingIntent & renderingIntent)) { + throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` " + "and `PDFDocumentProxy.getOptionalContentConfig` methods."); + } + internalRenderTask.initializeGraphics({ + transparency, + optionalContentConfig + }); + internalRenderTask.operatorListChanged(); + }).catch(complete); + return renderTask; + } + getOperatorList({ + intent = "display", + annotationMode = AnnotationMode.ENABLE, + printAnnotationStorage = null, + isEditing = false + } = {}) { + function operatorListChanged() { + if (intentState.operatorList.lastChunk) { + intentState.opListReadCapability.resolve(intentState.operatorList); + intentState.renderTasks.delete(opListTask); + } + } + const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing, true); + let intentState = this._intentStates.get(intentArgs.cacheKey); + if (!intentState) { + intentState = Object.create(null); + this._intentStates.set(intentArgs.cacheKey, intentState); + } + let opListTask; + if (!intentState.opListReadCapability) { + opListTask = Object.create(null); + opListTask.operatorListChanged = operatorListChanged; + intentState.opListReadCapability = Promise.withResolvers(); + (intentState.renderTasks ||= new Set()).add(opListTask); + intentState.operatorList = { + fnArray: [], + argsArray: [], + lastChunk: false, + separateAnnots: null + }; + this._stats?.time("Page Request"); + this._pumpOperatorList(intentArgs); + } + return intentState.opListReadCapability.promise; + } + streamTextContent({ + includeMarkedContent = false, + disableNormalization = false + } = {}) { + const TEXT_CONTENT_CHUNK_SIZE = 100; + return this._transport.messageHandler.sendWithStream("GetTextContent", { + pageIndex: this._pageIndex, + includeMarkedContent: includeMarkedContent === true, + disableNormalization: disableNormalization === true + }, { + highWaterMark: TEXT_CONTENT_CHUNK_SIZE, + size(textContent) { + return textContent.items.length; + } + }); + } + getTextContent(params = {}) { + if (this._transport._htmlForXfa) { + return this.getXfa().then(xfa => XfaText.textContent(xfa)); + } + const readableStream = this.streamTextContent(params); + return new Promise(function (resolve, reject) { + function pump() { + reader.read().then(function ({ + value, + done + }) { + if (done) { + resolve(textContent); + return; + } + textContent.lang ??= value.lang; + Object.assign(textContent.styles, value.styles); + textContent.items.push(...value.items); + pump(); + }, reject); + } + const reader = readableStream.getReader(); + const textContent = { + items: [], + styles: Object.create(null), + lang: null + }; + pump(); + }); + } + getStructTree() { + return this._transport.getStructTree(this._pageIndex); + } + _destroy() { + this.destroyed = true; + const waitOn = []; + for (const intentState of this._intentStates.values()) { + this._abortOperatorList({ + intentState, + reason: new Error("Page was destroyed."), + force: true + }); + if (intentState.opListReadCapability) { + continue; + } + for (const internalRenderTask of intentState.renderTasks) { + waitOn.push(internalRenderTask.completed); + internalRenderTask.cancel(); + } + } + this.objs.clear(); + this.#pendingCleanup = false; + this.#abortDelayedCleanup(); + return Promise.all(waitOn); + } + cleanup(resetStats = false) { + this.#pendingCleanup = true; + const success = this.#tryCleanup(false); + if (resetStats && success) { + this._stats &&= new StatTimer(); + } + return success; + } + #tryCleanup(delayed = false) { + this.#abortDelayedCleanup(); + if (!this.#pendingCleanup || this.destroyed) { + return false; + } + if (delayed) { + this.#delayedCleanupTimeout = setTimeout(() => { + this.#delayedCleanupTimeout = null; + this.#tryCleanup(false); + }, DELAYED_CLEANUP_TIMEOUT); + return false; + } + for (const { + renderTasks, + operatorList + } of this._intentStates.values()) { + if (renderTasks.size > 0 || !operatorList.lastChunk) { + return false; + } + } + this._intentStates.clear(); + this.objs.clear(); + this.#pendingCleanup = false; + return true; + } + #abortDelayedCleanup() { + if (this.#delayedCleanupTimeout) { + clearTimeout(this.#delayedCleanupTimeout); + this.#delayedCleanupTimeout = null; + } + } + _startRenderPage(transparency, cacheKey) { + const intentState = this._intentStates.get(cacheKey); + if (!intentState) { + return; + } + this._stats?.timeEnd("Page Request"); + intentState.displayReadyCapability?.resolve(transparency); + } + _renderPageChunk(operatorListChunk, intentState) { + for (let i = 0, ii = operatorListChunk.length; i < ii; i++) { + intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); + intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]); + } + intentState.operatorList.lastChunk = operatorListChunk.lastChunk; + intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots; + for (const internalRenderTask of intentState.renderTasks) { + internalRenderTask.operatorListChanged(); + } + if (operatorListChunk.lastChunk) { + this.#tryCleanup(true); + } + } + _pumpOperatorList({ + renderingIntent, + cacheKey, + annotationStorageSerializable, + modifiedIds + }) { + const { + map, + transfer + } = annotationStorageSerializable; + const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", { + pageIndex: this._pageIndex, + intent: renderingIntent, + cacheKey, + annotationStorage: map, + modifiedIds + }, transfer); + const reader = readableStream.getReader(); + const intentState = this._intentStates.get(cacheKey); + intentState.streamReader = reader; + const pump = () => { + reader.read().then(({ + value, + done + }) => { + if (done) { + intentState.streamReader = null; + return; + } + if (this._transport.destroyed) { + return; + } + this._renderPageChunk(value, intentState); + pump(); + }, reason => { + intentState.streamReader = null; + if (this._transport.destroyed) { + return; + } + if (intentState.operatorList) { + intentState.operatorList.lastChunk = true; + for (const internalRenderTask of intentState.renderTasks) { + internalRenderTask.operatorListChanged(); + } + this.#tryCleanup(true); + } + if (intentState.displayReadyCapability) { + intentState.displayReadyCapability.reject(reason); + } else if (intentState.opListReadCapability) { + intentState.opListReadCapability.reject(reason); + } else { + throw reason; + } + }); + }; + pump(); + } + _abortOperatorList({ + intentState, + reason, + force = false + }) { + if (!intentState.streamReader) { + return; + } + if (intentState.streamReaderCancelTimeout) { + clearTimeout(intentState.streamReaderCancelTimeout); + intentState.streamReaderCancelTimeout = null; + } + if (!force) { + if (intentState.renderTasks.size > 0) { + return; + } + if (reason instanceof RenderingCancelledException) { + let delay = RENDERING_CANCELLED_TIMEOUT; + if (reason.extraDelay > 0 && reason.extraDelay < 1000) { + delay += reason.extraDelay; + } + intentState.streamReaderCancelTimeout = setTimeout(() => { + intentState.streamReaderCancelTimeout = null; + this._abortOperatorList({ + intentState, + reason, + force: true + }); + }, delay); + return; + } + } + intentState.streamReader.cancel(new AbortException(reason.message)).catch(() => {}); + intentState.streamReader = null; + if (this._transport.destroyed) { + return; + } + for (const [curCacheKey, curIntentState] of this._intentStates) { + if (curIntentState === intentState) { + this._intentStates.delete(curCacheKey); + break; + } + } + this.cleanup(); + } + get stats() { + return this._stats; + } +} +class LoopbackPort { + #listeners = new Map(); + #deferred = Promise.resolve(); + postMessage(obj, transfer) { + const event = { + data: structuredClone(obj, transfer ? { + transfer + } : null) + }; + this.#deferred.then(() => { + for (const [listener] of this.#listeners) { + listener.call(this, event); + } + }); + } + addEventListener(name, listener, options = null) { + let rmAbort = null; + if (options?.signal instanceof AbortSignal) { + const { + signal + } = options; + if (signal.aborted) { + warn("LoopbackPort - cannot use an `aborted` signal."); + return; + } + const onAbort = () => this.removeEventListener(name, listener); + rmAbort = () => signal.removeEventListener("abort", onAbort); + signal.addEventListener("abort", onAbort); + } + this.#listeners.set(listener, rmAbort); + } + removeEventListener(name, listener) { + const rmAbort = this.#listeners.get(listener); + rmAbort?.(); + this.#listeners.delete(listener); + } + terminate() { + for (const [, rmAbort] of this.#listeners) { + rmAbort?.(); + } + this.#listeners.clear(); + } +} +class PDFWorker { + static #fakeWorkerId = 0; + static #isWorkerDisabled = false; + static #workerPorts; + static { + if (isNodeJS) { + this.#isWorkerDisabled = true; + GlobalWorkerOptions.workerSrc ||= "./pdf.worker.mjs"; + } + this._isSameOrigin = (baseUrl, otherUrl) => { + let base; + try { + base = new URL(baseUrl); + if (!base.origin || base.origin === "null") { + return false; + } + } catch { + return false; + } + const other = new URL(otherUrl, base); + return base.origin === other.origin; + }; + this._createCDNWrapper = url => { + const wrapper = `await import("${url}");`; + return URL.createObjectURL(new Blob([wrapper], { + type: "text/javascript" + })); + }; + } + constructor({ + name = null, + port = null, + verbosity = getVerbosityLevel() + } = {}) { + this.name = name; + this.destroyed = false; + this.verbosity = verbosity; + this._readyCapability = Promise.withResolvers(); + this._port = null; + this._webWorker = null; + this._messageHandler = null; + if (port) { + if (PDFWorker.#workerPorts?.has(port)) { + throw new Error("Cannot use more than one PDFWorker per port."); + } + (PDFWorker.#workerPorts ||= new WeakMap()).set(port, this); + this._initializeFromPort(port); + return; + } + this._initialize(); + } + get promise() { + return this._readyCapability.promise; + } + #resolve() { + this._readyCapability.resolve(); + this._messageHandler.send("configure", { + verbosity: this.verbosity + }); + } + get port() { + return this._port; + } + get messageHandler() { + return this._messageHandler; + } + _initializeFromPort(port) { + this._port = port; + this._messageHandler = new MessageHandler("main", "worker", port); + this._messageHandler.on("ready", function () {}); + this.#resolve(); + } + _initialize() { + if (PDFWorker.#isWorkerDisabled || PDFWorker.#mainThreadWorkerMessageHandler) { + this._setupFakeWorker(); + return; + } + let { + workerSrc + } = PDFWorker; + try { + if (!PDFWorker._isSameOrigin(window.location.href, workerSrc)) { + workerSrc = PDFWorker._createCDNWrapper(new URL(workerSrc, window.location).href); + } + const worker = new Worker(workerSrc, { + type: "module" + }); + const messageHandler = new MessageHandler("main", "worker", worker); + const terminateEarly = () => { + ac.abort(); + messageHandler.destroy(); + worker.terminate(); + if (this.destroyed) { + this._readyCapability.reject(new Error("Worker was destroyed")); + } else { + this._setupFakeWorker(); + } + }; + const ac = new AbortController(); + worker.addEventListener("error", () => { + if (!this._webWorker) { + terminateEarly(); + } + }, { + signal: ac.signal + }); + messageHandler.on("test", data => { + ac.abort(); + if (this.destroyed || !data) { + terminateEarly(); + return; + } + this._messageHandler = messageHandler; + this._port = worker; + this._webWorker = worker; + this.#resolve(); + }); + messageHandler.on("ready", data => { + ac.abort(); + if (this.destroyed) { + terminateEarly(); + return; + } + try { + sendTest(); + } catch { + this._setupFakeWorker(); + } + }); + const sendTest = () => { + const testObj = new Uint8Array(); + messageHandler.send("test", testObj, [testObj.buffer]); + }; + sendTest(); + return; + } catch { + info("The worker has been disabled."); + } + this._setupFakeWorker(); + } + _setupFakeWorker() { + if (!PDFWorker.#isWorkerDisabled) { + warn("Setting up fake worker."); + PDFWorker.#isWorkerDisabled = true; + } + PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => { + if (this.destroyed) { + this._readyCapability.reject(new Error("Worker was destroyed")); + return; + } + const port = new LoopbackPort(); + this._port = port; + const id = `fake${PDFWorker.#fakeWorkerId++}`; + const workerHandler = new MessageHandler(id + "_worker", id, port); + WorkerMessageHandler.setup(workerHandler, port); + this._messageHandler = new MessageHandler(id, id + "_worker", port); + this.#resolve(); + }).catch(reason => { + this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`)); + }); + } + destroy() { + this.destroyed = true; + this._webWorker?.terminate(); + this._webWorker = null; + PDFWorker.#workerPorts?.delete(this._port); + this._port = null; + this._messageHandler?.destroy(); + this._messageHandler = null; + } + static fromPort(params) { + if (!params?.port) { + throw new Error("PDFWorker.fromPort - invalid method signature."); + } + const cachedPort = this.#workerPorts?.get(params.port); + if (cachedPort) { + if (cachedPort._pendingDestroy) { + throw new Error("PDFWorker.fromPort - the worker is being destroyed.\n" + "Please remember to await `PDFDocumentLoadingTask.destroy()`-calls."); + } + return cachedPort; + } + return new PDFWorker(params); + } + static get workerSrc() { + if (GlobalWorkerOptions.workerSrc) { + return GlobalWorkerOptions.workerSrc; + } + throw new Error('No "GlobalWorkerOptions.workerSrc" specified.'); + } + static get #mainThreadWorkerMessageHandler() { + try { + return globalThis.pdfjsWorker?.WorkerMessageHandler || null; + } catch { + return null; + } + } + static get _setupFakeWorkerGlobal() { + const loader = async () => { + if (this.#mainThreadWorkerMessageHandler) { + return this.#mainThreadWorkerMessageHandler; + } + const worker = await import(/*webpackIgnore: true*/this.workerSrc); + return worker.WorkerMessageHandler; + }; + return shadow(this, "_setupFakeWorkerGlobal", loader()); + } +} +class WorkerTransport { + #methodPromises = new Map(); + #pageCache = new Map(); + #pagePromises = new Map(); + #pageRefCache = new Map(); + #passwordCapability = null; + constructor(messageHandler, loadingTask, networkStream, params, factory) { + this.messageHandler = messageHandler; + this.loadingTask = loadingTask; + this.commonObjs = new PDFObjects(); + this.fontLoader = new FontLoader({ + ownerDocument: params.ownerDocument, + styleElement: params.styleElement + }); + this.loadingParams = params.loadingParams; + this._params = params; + this.canvasFactory = factory.canvasFactory; + this.filterFactory = factory.filterFactory; + this.cMapReaderFactory = factory.cMapReaderFactory; + this.standardFontDataFactory = factory.standardFontDataFactory; + this.destroyed = false; + this.destroyCapability = null; + this._networkStream = networkStream; + this._fullReader = null; + this._lastProgress = null; + this.downloadInfoCapability = Promise.withResolvers(); + this.setupMessageHandler(); + } + #cacheSimpleMethod(name, data = null) { + const cachedPromise = this.#methodPromises.get(name); + if (cachedPromise) { + return cachedPromise; + } + const promise = this.messageHandler.sendWithPromise(name, data); + this.#methodPromises.set(name, promise); + return promise; + } + get annotationStorage() { + return shadow(this, "annotationStorage", new AnnotationStorage()); + } + getRenderingIntent(intent, annotationMode = AnnotationMode.ENABLE, printAnnotationStorage = null, isEditing = false, isOpList = false) { + let renderingIntent = RenderingIntentFlag.DISPLAY; + let annotationStorageSerializable = SerializableEmpty; + switch (intent) { + case "any": + renderingIntent = RenderingIntentFlag.ANY; + break; + case "display": + break; + case "print": + renderingIntent = RenderingIntentFlag.PRINT; + break; + default: + warn(`getRenderingIntent - invalid intent: ${intent}`); + } + const annotationStorage = renderingIntent & RenderingIntentFlag.PRINT && printAnnotationStorage instanceof PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage; + switch (annotationMode) { + case AnnotationMode.DISABLE: + renderingIntent += RenderingIntentFlag.ANNOTATIONS_DISABLE; + break; + case AnnotationMode.ENABLE: + break; + case AnnotationMode.ENABLE_FORMS: + renderingIntent += RenderingIntentFlag.ANNOTATIONS_FORMS; + break; + case AnnotationMode.ENABLE_STORAGE: + renderingIntent += RenderingIntentFlag.ANNOTATIONS_STORAGE; + annotationStorageSerializable = annotationStorage.serializable; + break; + default: + warn(`getRenderingIntent - invalid annotationMode: ${annotationMode}`); + } + if (isEditing) { + renderingIntent += RenderingIntentFlag.IS_EDITING; + } + if (isOpList) { + renderingIntent += RenderingIntentFlag.OPLIST; + } + const { + ids: modifiedIds, + hash: modifiedIdsHash + } = annotationStorage.modifiedIds; + const cacheKeyBuf = [renderingIntent, annotationStorageSerializable.hash, modifiedIdsHash]; + return { + renderingIntent, + cacheKey: cacheKeyBuf.join("_"), + annotationStorageSerializable, + modifiedIds + }; + } + destroy() { + if (this.destroyCapability) { + return this.destroyCapability.promise; + } + this.destroyed = true; + this.destroyCapability = Promise.withResolvers(); + this.#passwordCapability?.reject(new Error("Worker was destroyed during onPassword callback")); + const waitOn = []; + for (const page of this.#pageCache.values()) { + waitOn.push(page._destroy()); + } + this.#pageCache.clear(); + this.#pagePromises.clear(); + this.#pageRefCache.clear(); + if (this.hasOwnProperty("annotationStorage")) { + this.annotationStorage.resetModified(); + } + const terminated = this.messageHandler.sendWithPromise("Terminate", null); + waitOn.push(terminated); + Promise.all(waitOn).then(() => { + this.commonObjs.clear(); + this.fontLoader.clear(); + this.#methodPromises.clear(); + this.filterFactory.destroy(); + TextLayer.cleanup(); + this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated.")); + this.messageHandler?.destroy(); + this.messageHandler = null; + this.destroyCapability.resolve(); + }, this.destroyCapability.reject); + return this.destroyCapability.promise; + } + setupMessageHandler() { + const { + messageHandler, + loadingTask + } = this; + messageHandler.on("GetReader", (data, sink) => { + assert(this._networkStream, "GetReader - no `IPDFStream` instance available."); + this._fullReader = this._networkStream.getFullReader(); + this._fullReader.onProgress = evt => { + this._lastProgress = { + loaded: evt.loaded, + total: evt.total + }; + }; + sink.onPull = () => { + this._fullReader.read().then(function ({ + value, + done + }) { + if (done) { + sink.close(); + return; + } + assert(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer."); + sink.enqueue(new Uint8Array(value), 1, [value]); + }).catch(reason => { + sink.error(reason); + }); + }; + sink.onCancel = reason => { + this._fullReader.cancel(reason); + sink.ready.catch(readyReason => { + if (this.destroyed) { + return; + } + throw readyReason; + }); + }; + }); + messageHandler.on("ReaderHeadersReady", async data => { + await this._fullReader.headersReady; + const { + isStreamingSupported, + isRangeSupported, + contentLength + } = this._fullReader; + if (!isStreamingSupported || !isRangeSupported) { + if (this._lastProgress) { + loadingTask.onProgress?.(this._lastProgress); + } + this._fullReader.onProgress = evt => { + loadingTask.onProgress?.({ + loaded: evt.loaded, + total: evt.total + }); + }; + } + return { + isStreamingSupported, + isRangeSupported, + contentLength + }; + }); + messageHandler.on("GetRangeReader", (data, sink) => { + assert(this._networkStream, "GetRangeReader - no `IPDFStream` instance available."); + const rangeReader = this._networkStream.getRangeReader(data.begin, data.end); + if (!rangeReader) { + sink.close(); + return; + } + sink.onPull = () => { + rangeReader.read().then(function ({ + value, + done + }) { + if (done) { + sink.close(); + return; + } + assert(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer."); + sink.enqueue(new Uint8Array(value), 1, [value]); + }).catch(reason => { + sink.error(reason); + }); + }; + sink.onCancel = reason => { + rangeReader.cancel(reason); + sink.ready.catch(readyReason => { + if (this.destroyed) { + return; + } + throw readyReason; + }); + }; + }); + messageHandler.on("GetDoc", ({ + pdfInfo + }) => { + this._numPages = pdfInfo.numPages; + this._htmlForXfa = pdfInfo.htmlForXfa; + delete pdfInfo.htmlForXfa; + loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this)); + }); + messageHandler.on("DocException", function (ex) { + let reason; + switch (ex.name) { + case "PasswordException": + reason = new PasswordException(ex.message, ex.code); + break; + case "InvalidPDFException": + reason = new InvalidPDFException(ex.message); + break; + case "MissingPDFException": + reason = new MissingPDFException(ex.message); + break; + case "UnexpectedResponseException": + reason = new UnexpectedResponseException(ex.message, ex.status); + break; + case "UnknownErrorException": + reason = new UnknownErrorException(ex.message, ex.details); + break; + default: + unreachable("DocException - expected a valid Error."); + } + loadingTask._capability.reject(reason); + }); + messageHandler.on("PasswordRequest", exception => { + this.#passwordCapability = Promise.withResolvers(); + if (loadingTask.onPassword) { + const updatePassword = password => { + if (password instanceof Error) { + this.#passwordCapability.reject(password); + } else { + this.#passwordCapability.resolve({ + password + }); + } + }; + try { + loadingTask.onPassword(updatePassword, exception.code); + } catch (ex) { + this.#passwordCapability.reject(ex); + } + } else { + this.#passwordCapability.reject(new PasswordException(exception.message, exception.code)); + } + return this.#passwordCapability.promise; + }); + messageHandler.on("DataLoaded", data => { + loadingTask.onProgress?.({ + loaded: data.length, + total: data.length + }); + this.downloadInfoCapability.resolve(data); + }); + messageHandler.on("StartRenderPage", data => { + if (this.destroyed) { + return; + } + const page = this.#pageCache.get(data.pageIndex); + page._startRenderPage(data.transparency, data.cacheKey); + }); + messageHandler.on("commonobj", ([id, type, exportedData]) => { + if (this.destroyed) { + return null; + } + if (this.commonObjs.has(id)) { + return null; + } + switch (type) { + case "Font": + const { + disableFontFace, + fontExtraProperties, + pdfBug + } = this._params; + if ("error" in exportedData) { + const exportedError = exportedData.error; + warn(`Error during font loading: ${exportedError}`); + this.commonObjs.resolve(id, exportedError); + break; + } + const inspectFont = pdfBug && globalThis.FontInspector?.enabled ? (font, url) => globalThis.FontInspector.fontAdded(font, url) : null; + const font = new FontFaceObject(exportedData, { + disableFontFace, + inspectFont + }); + this.fontLoader.bind(font).catch(() => messageHandler.sendWithPromise("FontFallback", { + id + })).finally(() => { + if (!fontExtraProperties && font.data) { + font.data = null; + } + this.commonObjs.resolve(id, font); + }); + break; + case "CopyLocalImage": + const { + imageRef + } = exportedData; + assert(imageRef, "The imageRef must be defined."); + for (const pageProxy of this.#pageCache.values()) { + for (const [, data] of pageProxy.objs) { + if (data?.ref !== imageRef) { + continue; + } + if (!data.dataLen) { + return null; + } + this.commonObjs.resolve(id, structuredClone(data)); + return data.dataLen; + } + } + break; + case "FontPath": + case "Image": + case "Pattern": + this.commonObjs.resolve(id, exportedData); + break; + default: + throw new Error(`Got unknown common object type ${type}`); + } + return null; + }); + messageHandler.on("obj", ([id, pageIndex, type, imageData]) => { + if (this.destroyed) { + return; + } + const pageProxy = this.#pageCache.get(pageIndex); + if (pageProxy.objs.has(id)) { + return; + } + if (pageProxy._intentStates.size === 0) { + imageData?.bitmap?.close(); + return; + } + switch (type) { + case "Image": + pageProxy.objs.resolve(id, imageData); + if (imageData?.dataLen > MAX_IMAGE_SIZE_TO_CACHE) { + pageProxy._maybeCleanupAfterRender = true; + } + break; + case "Pattern": + pageProxy.objs.resolve(id, imageData); + break; + default: + throw new Error(`Got unknown object type ${type}`); + } + }); + messageHandler.on("DocProgress", data => { + if (this.destroyed) { + return; + } + loadingTask.onProgress?.({ + loaded: data.loaded, + total: data.total + }); + }); + messageHandler.on("FetchBuiltInCMap", async data => { + if (this.destroyed) { + throw new Error("Worker was destroyed."); + } + if (!this.cMapReaderFactory) { + throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."); + } + return this.cMapReaderFactory.fetch(data); + }); + messageHandler.on("FetchStandardFontData", async data => { + if (this.destroyed) { + throw new Error("Worker was destroyed."); + } + if (!this.standardFontDataFactory) { + throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."); + } + return this.standardFontDataFactory.fetch(data); + }); + } + getData() { + return this.messageHandler.sendWithPromise("GetData", null); + } + saveDocument() { + if (this.annotationStorage.size <= 0) { + warn("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead."); + } + const { + map, + transfer + } = this.annotationStorage.serializable; + return this.messageHandler.sendWithPromise("SaveDocument", { + isPureXfa: !!this._htmlForXfa, + numPages: this._numPages, + annotationStorage: map, + filename: this._fullReader?.filename ?? null + }, transfer).finally(() => { + this.annotationStorage.resetModified(); + }); + } + getPage(pageNumber) { + if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) { + return Promise.reject(new Error("Invalid page request.")); + } + const pageIndex = pageNumber - 1, + cachedPromise = this.#pagePromises.get(pageIndex); + if (cachedPromise) { + return cachedPromise; + } + const promise = this.messageHandler.sendWithPromise("GetPage", { + pageIndex + }).then(pageInfo => { + if (this.destroyed) { + throw new Error("Transport destroyed"); + } + if (pageInfo.refStr) { + this.#pageRefCache.set(pageInfo.refStr, pageNumber); + } + const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.pdfBug); + this.#pageCache.set(pageIndex, page); + return page; + }); + this.#pagePromises.set(pageIndex, promise); + return promise; + } + getPageIndex(ref) { + if (!isRefProxy(ref)) { + return Promise.reject(new Error("Invalid pageIndex request.")); + } + return this.messageHandler.sendWithPromise("GetPageIndex", { + num: ref.num, + gen: ref.gen + }); + } + getAnnotations(pageIndex, intent) { + return this.messageHandler.sendWithPromise("GetAnnotations", { + pageIndex, + intent + }); + } + getFieldObjects() { + return this.#cacheSimpleMethod("GetFieldObjects"); + } + hasJSActions() { + return this.#cacheSimpleMethod("HasJSActions"); + } + getCalculationOrderIds() { + return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null); + } + getDestinations() { + return this.messageHandler.sendWithPromise("GetDestinations", null); + } + getDestination(id) { + if (typeof id !== "string") { + return Promise.reject(new Error("Invalid destination request.")); + } + return this.messageHandler.sendWithPromise("GetDestination", { + id + }); + } + getPageLabels() { + return this.messageHandler.sendWithPromise("GetPageLabels", null); + } + getPageLayout() { + return this.messageHandler.sendWithPromise("GetPageLayout", null); + } + getPageMode() { + return this.messageHandler.sendWithPromise("GetPageMode", null); + } + getViewerPreferences() { + return this.messageHandler.sendWithPromise("GetViewerPreferences", null); + } + getOpenAction() { + return this.messageHandler.sendWithPromise("GetOpenAction", null); + } + getAttachments() { + return this.messageHandler.sendWithPromise("GetAttachments", null); + } + getDocJSActions() { + return this.#cacheSimpleMethod("GetDocJSActions"); + } + getPageJSActions(pageIndex) { + return this.messageHandler.sendWithPromise("GetPageJSActions", { + pageIndex + }); + } + getStructTree(pageIndex) { + return this.messageHandler.sendWithPromise("GetStructTree", { + pageIndex + }); + } + getOutline() { + return this.messageHandler.sendWithPromise("GetOutline", null); + } + getOptionalContentConfig(renderingIntent) { + return this.#cacheSimpleMethod("GetOptionalContentConfig").then(data => new OptionalContentConfig(data, renderingIntent)); + } + getPermissions() { + return this.messageHandler.sendWithPromise("GetPermissions", null); + } + getMetadata() { + const name = "GetMetadata", + cachedPromise = this.#methodPromises.get(name); + if (cachedPromise) { + return cachedPromise; + } + const promise = this.messageHandler.sendWithPromise(name, null).then(results => ({ + info: results[0], + metadata: results[1] ? new Metadata(results[1]) : null, + contentDispositionFilename: this._fullReader?.filename ?? null, + contentLength: this._fullReader?.contentLength ?? null + })); + this.#methodPromises.set(name, promise); + return promise; + } + getMarkInfo() { + return this.messageHandler.sendWithPromise("GetMarkInfo", null); + } + async startCleanup(keepLoadedFonts = false) { + if (this.destroyed) { + return; + } + await this.messageHandler.sendWithPromise("Cleanup", null); + for (const page of this.#pageCache.values()) { + const cleanupSuccessful = page.cleanup(); + if (!cleanupSuccessful) { + throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`); + } + } + this.commonObjs.clear(); + if (!keepLoadedFonts) { + this.fontLoader.clear(); + } + this.#methodPromises.clear(); + this.filterFactory.destroy(true); + TextLayer.cleanup(); + } + cachedPageNumber(ref) { + if (!isRefProxy(ref)) { + return null; + } + const refStr = ref.gen === 0 ? `${ref.num}R` : `${ref.num}R${ref.gen}`; + return this.#pageRefCache.get(refStr) ?? null; + } +} +const INITIAL_DATA = Symbol("INITIAL_DATA"); +class PDFObjects { + #objs = Object.create(null); + #ensureObj(objId) { + return this.#objs[objId] ||= { + ...Promise.withResolvers(), + data: INITIAL_DATA + }; + } + get(objId, callback = null) { + if (callback) { + const obj = this.#ensureObj(objId); + obj.promise.then(() => callback(obj.data)); + return null; + } + const obj = this.#objs[objId]; + if (!obj || obj.data === INITIAL_DATA) { + throw new Error(`Requesting object that isn't resolved yet ${objId}.`); + } + return obj.data; + } + has(objId) { + const obj = this.#objs[objId]; + return !!obj && obj.data !== INITIAL_DATA; + } + resolve(objId, data = null) { + const obj = this.#ensureObj(objId); + obj.data = data; + obj.resolve(); + } + clear() { + for (const objId in this.#objs) { + const { + data + } = this.#objs[objId]; + data?.bitmap?.close(); + } + this.#objs = Object.create(null); + } + *[Symbol.iterator]() { + for (const objId in this.#objs) { + const { + data + } = this.#objs[objId]; + if (data === INITIAL_DATA) { + continue; + } + yield [objId, data]; + } + } +} +class RenderTask { + #internalRenderTask = null; + constructor(internalRenderTask) { + this.#internalRenderTask = internalRenderTask; + this.onContinue = null; + } + get promise() { + return this.#internalRenderTask.capability.promise; + } + cancel(extraDelay = 0) { + this.#internalRenderTask.cancel(null, extraDelay); + } + get separateAnnots() { + const { + separateAnnots + } = this.#internalRenderTask.operatorList; + if (!separateAnnots) { + return false; + } + const { + annotationCanvasMap + } = this.#internalRenderTask; + return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0; + } +} +class InternalRenderTask { + #rAF = null; + static #canvasInUse = new WeakSet(); + constructor({ + callback, + params, + objs, + commonObjs, + annotationCanvasMap, + operatorList, + pageIndex, + canvasFactory, + filterFactory, + useRequestAnimationFrame = false, + pdfBug = false, + pageColors = null + }) { + this.callback = callback; + this.params = params; + this.objs = objs; + this.commonObjs = commonObjs; + this.annotationCanvasMap = annotationCanvasMap; + this.operatorListIdx = null; + this.operatorList = operatorList; + this._pageIndex = pageIndex; + this.canvasFactory = canvasFactory; + this.filterFactory = filterFactory; + this._pdfBug = pdfBug; + this.pageColors = pageColors; + this.running = false; + this.graphicsReadyCallback = null; + this.graphicsReady = false; + this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined"; + this.cancelled = false; + this.capability = Promise.withResolvers(); + this.task = new RenderTask(this); + this._cancelBound = this.cancel.bind(this); + this._continueBound = this._continue.bind(this); + this._scheduleNextBound = this._scheduleNext.bind(this); + this._nextBound = this._next.bind(this); + this._canvas = params.canvasContext.canvas; + } + get completed() { + return this.capability.promise.catch(function () {}); + } + initializeGraphics({ + transparency = false, + optionalContentConfig + }) { + if (this.cancelled) { + return; + } + if (this._canvas) { + if (InternalRenderTask.#canvasInUse.has(this._canvas)) { + throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed."); + } + InternalRenderTask.#canvasInUse.add(this._canvas); + } + if (this._pdfBug && globalThis.StepperManager?.enabled) { + this.stepper = globalThis.StepperManager.create(this._pageIndex); + this.stepper.init(this.operatorList); + this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint(); + } + const { + canvasContext, + viewport, + transform, + background + } = this.params; + this.gfx = new CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, { + optionalContentConfig + }, this.annotationCanvasMap, this.pageColors); + this.gfx.beginDrawing({ + transform, + viewport, + transparency, + background + }); + this.operatorListIdx = 0; + this.graphicsReady = true; + this.graphicsReadyCallback?.(); + } + cancel(error = null, extraDelay = 0) { + this.running = false; + this.cancelled = true; + this.gfx?.endDrawing(); + if (this.#rAF) { + window.cancelAnimationFrame(this.#rAF); + this.#rAF = null; + } + InternalRenderTask.#canvasInUse.delete(this._canvas); + this.callback(error || new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, extraDelay)); + } + operatorListChanged() { + if (!this.graphicsReady) { + this.graphicsReadyCallback ||= this._continueBound; + return; + } + this.stepper?.updateOperatorList(this.operatorList); + if (this.running) { + return; + } + this._continue(); + } + _continue() { + this.running = true; + if (this.cancelled) { + return; + } + if (this.task.onContinue) { + this.task.onContinue(this._scheduleNextBound); + } else { + this._scheduleNext(); + } + } + _scheduleNext() { + if (this._useRequestAnimationFrame) { + this.#rAF = window.requestAnimationFrame(() => { + this.#rAF = null; + this._nextBound().catch(this._cancelBound); + }); + } else { + Promise.resolve().then(this._nextBound).catch(this._cancelBound); + } + } + async _next() { + if (this.cancelled) { + return; + } + this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper); + if (this.operatorListIdx === this.operatorList.argsArray.length) { + this.running = false; + if (this.operatorList.lastChunk) { + this.gfx.endDrawing(); + InternalRenderTask.#canvasInUse.delete(this._canvas); + this.callback(); + } + } + } +} +const version = "4.9.155"; +const build = "a4eb8407c"; + +;// ./src/shared/scripting_utils.js +function makeColorComp(n) { + return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0"); +} +function scaleAndClamp(x) { + return Math.max(0, Math.min(255, 255 * x)); +} +class ColorConverters { + static CMYK_G([c, y, m, k]) { + return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)]; + } + static G_CMYK([g]) { + return ["CMYK", 0, 0, 0, 1 - g]; + } + static G_RGB([g]) { + return ["RGB", g, g, g]; + } + static G_rgb([g]) { + g = scaleAndClamp(g); + return [g, g, g]; + } + static G_HTML([g]) { + const G = makeColorComp(g); + return `#${G}${G}${G}`; + } + static RGB_G([r, g, b]) { + return ["G", 0.3 * r + 0.59 * g + 0.11 * b]; + } + static RGB_rgb(color) { + return color.map(scaleAndClamp); + } + static RGB_HTML(color) { + return `#${color.map(makeColorComp).join("")}`; + } + static T_HTML() { + return "#00000000"; + } + static T_rgb() { + return [null]; + } + static CMYK_RGB([c, y, m, k]) { + return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)]; + } + static CMYK_rgb([c, y, m, k]) { + return [scaleAndClamp(1 - Math.min(1, c + k)), scaleAndClamp(1 - Math.min(1, m + k)), scaleAndClamp(1 - Math.min(1, y + k))]; + } + static CMYK_HTML(components) { + const rgb = this.CMYK_RGB(components).slice(1); + return this.RGB_HTML(rgb); + } + static RGB_CMYK([r, g, b]) { + const c = 1 - r; + const m = 1 - g; + const y = 1 - b; + const k = Math.min(c, m, y); + return ["CMYK", c, m, y, k]; + } +} + +;// ./src/display/svg_factory.js + + +class BaseSVGFactory { + create(width, height, skipDimensions = false) { + if (width <= 0 || height <= 0) { + throw new Error("Invalid SVG dimensions"); + } + const svg = this._createSVG("svg:svg"); + svg.setAttribute("version", "1.1"); + if (!skipDimensions) { + svg.setAttribute("width", `${width}px`); + svg.setAttribute("height", `${height}px`); + } + svg.setAttribute("preserveAspectRatio", "none"); + svg.setAttribute("viewBox", `0 0 ${width} ${height}`); + return svg; + } + createElement(type) { + if (typeof type !== "string") { + throw new Error("Invalid SVG element type"); + } + return this._createSVG(type); + } + _createSVG(type) { + unreachable("Abstract method `_createSVG` called."); + } +} +class DOMSVGFactory extends BaseSVGFactory { + _createSVG(type) { + return document.createElementNS(SVG_NS, type); + } +} + +;// ./src/display/xfa_layer.js + +class XfaLayer { + static setupStorage(html, id, element, storage, intent) { + const storedData = storage.getValue(id, { + value: null + }); + switch (element.name) { + case "textarea": + if (storedData.value !== null) { + html.textContent = storedData.value; + } + if (intent === "print") { + break; + } + html.addEventListener("input", event => { + storage.setValue(id, { + value: event.target.value + }); + }); + break; + case "input": + if (element.attributes.type === "radio" || element.attributes.type === "checkbox") { + if (storedData.value === element.attributes.xfaOn) { + html.setAttribute("checked", true); + } else if (storedData.value === element.attributes.xfaOff) { + html.removeAttribute("checked"); + } + if (intent === "print") { + break; + } + html.addEventListener("change", event => { + storage.setValue(id, { + value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff") + }); + }); + } else { + if (storedData.value !== null) { + html.setAttribute("value", storedData.value); + } + if (intent === "print") { + break; + } + html.addEventListener("input", event => { + storage.setValue(id, { + value: event.target.value + }); + }); + } + break; + case "select": + if (storedData.value !== null) { + html.setAttribute("value", storedData.value); + for (const option of element.children) { + if (option.attributes.value === storedData.value) { + option.attributes.selected = true; + } else if (option.attributes.hasOwnProperty("selected")) { + delete option.attributes.selected; + } + } + } + html.addEventListener("input", event => { + const options = event.target.options; + const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value; + storage.setValue(id, { + value + }); + }); + break; + } + } + static setAttributes({ + html, + element, + storage = null, + intent, + linkService + }) { + const { + attributes + } = element; + const isHTMLAnchorElement = html instanceof HTMLAnchorElement; + if (attributes.type === "radio") { + attributes.name = `${attributes.name}-${intent}`; + } + for (const [key, value] of Object.entries(attributes)) { + if (value === null || value === undefined) { + continue; + } + switch (key) { + case "class": + if (value.length) { + html.setAttribute(key, value.join(" ")); + } + break; + case "dataId": + break; + case "id": + html.setAttribute("data-element-id", value); + break; + case "style": + Object.assign(html.style, value); + break; + case "textContent": + html.textContent = value; + break; + default: + if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") { + html.setAttribute(key, value); + } + } + } + if (isHTMLAnchorElement) { + linkService.addLinkAttributes(html, attributes.href, attributes.newWindow); + } + if (storage && attributes.dataId) { + this.setupStorage(html, attributes.dataId, element, storage); + } + } + static render(parameters) { + const storage = parameters.annotationStorage; + const linkService = parameters.linkService; + const root = parameters.xfaHtml; + const intent = parameters.intent || "display"; + const rootHtml = document.createElement(root.name); + if (root.attributes) { + this.setAttributes({ + html: rootHtml, + element: root, + intent, + linkService + }); + } + const isNotForRichText = intent !== "richText"; + const rootDiv = parameters.div; + rootDiv.append(rootHtml); + if (parameters.viewport) { + const transform = `matrix(${parameters.viewport.transform.join(",")})`; + rootDiv.style.transform = transform; + } + if (isNotForRichText) { + rootDiv.setAttribute("class", "xfaLayer xfaFont"); + } + const textDivs = []; + if (root.children.length === 0) { + if (root.value) { + const node = document.createTextNode(root.value); + rootHtml.append(node); + if (isNotForRichText && XfaText.shouldBuildText(root.name)) { + textDivs.push(node); + } + } + return { + textDivs + }; + } + const stack = [[root, -1, rootHtml]]; + while (stack.length > 0) { + const [parent, i, html] = stack.at(-1); + if (i + 1 === parent.children.length) { + stack.pop(); + continue; + } + const child = parent.children[++stack.at(-1)[1]]; + if (child === null) { + continue; + } + const { + name + } = child; + if (name === "#text") { + const node = document.createTextNode(child.value); + textDivs.push(node); + html.append(node); + continue; + } + const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name); + html.append(childHtml); + if (child.attributes) { + this.setAttributes({ + html: childHtml, + element: child, + storage, + intent, + linkService + }); + } + if (child.children?.length > 0) { + stack.push([child, -1, childHtml]); + } else if (child.value) { + const node = document.createTextNode(child.value); + if (isNotForRichText && XfaText.shouldBuildText(name)) { + textDivs.push(node); + } + childHtml.append(node); + } + } + for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) { + el.setAttribute("readOnly", true); + } + return { + textDivs + }; + } + static update(parameters) { + const transform = `matrix(${parameters.viewport.transform.join(",")})`; + parameters.div.style.transform = transform; + parameters.div.hidden = false; + } +} + +;// ./src/display/annotation_layer.js + + + + + + +const DEFAULT_TAB_INDEX = 1000; +const annotation_layer_DEFAULT_FONT_SIZE = 9; +const GetElementsByNameSet = new WeakSet(); +function getRectDims(rect) { + return { + width: rect[2] - rect[0], + height: rect[3] - rect[1] + }; +} +class AnnotationElementFactory { + static create(parameters) { + const subtype = parameters.data.annotationType; + switch (subtype) { + case AnnotationType.LINK: + return new LinkAnnotationElement(parameters); + case AnnotationType.TEXT: + return new TextAnnotationElement(parameters); + case AnnotationType.WIDGET: + const fieldType = parameters.data.fieldType; + switch (fieldType) { + case "Tx": + return new TextWidgetAnnotationElement(parameters); + case "Btn": + if (parameters.data.radioButton) { + return new RadioButtonWidgetAnnotationElement(parameters); + } else if (parameters.data.checkBox) { + return new CheckboxWidgetAnnotationElement(parameters); + } + return new PushButtonWidgetAnnotationElement(parameters); + case "Ch": + return new ChoiceWidgetAnnotationElement(parameters); + case "Sig": + return new SignatureWidgetAnnotationElement(parameters); + } + return new WidgetAnnotationElement(parameters); + case AnnotationType.POPUP: + return new PopupAnnotationElement(parameters); + case AnnotationType.FREETEXT: + return new FreeTextAnnotationElement(parameters); + case AnnotationType.LINE: + return new LineAnnotationElement(parameters); + case AnnotationType.SQUARE: + return new SquareAnnotationElement(parameters); + case AnnotationType.CIRCLE: + return new CircleAnnotationElement(parameters); + case AnnotationType.POLYLINE: + return new PolylineAnnotationElement(parameters); + case AnnotationType.CARET: + return new CaretAnnotationElement(parameters); + case AnnotationType.INK: + return new InkAnnotationElement(parameters); + case AnnotationType.POLYGON: + return new PolygonAnnotationElement(parameters); + case AnnotationType.HIGHLIGHT: + return new HighlightAnnotationElement(parameters); + case AnnotationType.UNDERLINE: + return new UnderlineAnnotationElement(parameters); + case AnnotationType.SQUIGGLY: + return new SquigglyAnnotationElement(parameters); + case AnnotationType.STRIKEOUT: + return new StrikeOutAnnotationElement(parameters); + case AnnotationType.STAMP: + return new StampAnnotationElement(parameters); + case AnnotationType.FILEATTACHMENT: + return new FileAttachmentAnnotationElement(parameters); + default: + return new AnnotationElement(parameters); + } + } +} +class AnnotationElement { + #updates = null; + #hasBorder = false; + #popupElement = null; + constructor(parameters, { + isRenderable = false, + ignoreBorder = false, + createQuadrilaterals = false + } = {}) { + this.isRenderable = isRenderable; + this.data = parameters.data; + this.layer = parameters.layer; + this.linkService = parameters.linkService; + this.downloadManager = parameters.downloadManager; + this.imageResourcesPath = parameters.imageResourcesPath; + this.renderForms = parameters.renderForms; + this.svgFactory = parameters.svgFactory; + this.annotationStorage = parameters.annotationStorage; + this.enableScripting = parameters.enableScripting; + this.hasJSActions = parameters.hasJSActions; + this._fieldObjects = parameters.fieldObjects; + this.parent = parameters.parent; + if (isRenderable) { + this.container = this._createContainer(ignoreBorder); + } + if (createQuadrilaterals) { + this._createQuadrilaterals(); + } + } + static _hasPopupData({ + titleObj, + contentsObj, + richText + }) { + return !!(titleObj?.str || contentsObj?.str || richText?.str); + } + get _isEditable() { + return this.data.isEditable; + } + get hasPopupData() { + return AnnotationElement._hasPopupData(this.data); + } + updateEdited(params) { + if (!this.container) { + return; + } + this.#updates ||= { + rect: this.data.rect.slice(0) + }; + const { + rect + } = params; + if (rect) { + this.#setRectEdited(rect); + } + this.#popupElement?.popup.updateEdited(params); + } + resetEdited() { + if (!this.#updates) { + return; + } + this.#setRectEdited(this.#updates.rect); + this.#popupElement?.popup.resetEdited(); + this.#updates = null; + } + #setRectEdited(rect) { + const { + container: { + style + }, + data: { + rect: currentRect, + rotation + }, + parent: { + viewport: { + rawDims: { + pageWidth, + pageHeight, + pageX, + pageY + } + } + } + } = this; + currentRect?.splice(0, 4, ...rect); + const { + width, + height + } = getRectDims(rect); + style.left = `${100 * (rect[0] - pageX) / pageWidth}%`; + style.top = `${100 * (pageHeight - rect[3] + pageY) / pageHeight}%`; + if (rotation === 0) { + style.width = `${100 * width / pageWidth}%`; + style.height = `${100 * height / pageHeight}%`; + } else { + this.setRotation(rotation); + } + } + _createContainer(ignoreBorder) { + const { + data, + parent: { + page, + viewport + } + } = this; + const container = document.createElement("section"); + container.setAttribute("data-annotation-id", data.id); + if (!(this instanceof WidgetAnnotationElement)) { + container.tabIndex = DEFAULT_TAB_INDEX; + } + const { + style + } = container; + style.zIndex = this.parent.zIndex++; + if (data.alternativeText) { + container.title = data.alternativeText; + } + if (data.noRotate) { + container.classList.add("norotate"); + } + if (!data.rect || this instanceof PopupAnnotationElement) { + const { + rotation + } = data; + if (!data.hasOwnCanvas && rotation !== 0) { + this.setRotation(rotation, container); + } + return container; + } + const { + width, + height + } = getRectDims(data.rect); + if (!ignoreBorder && data.borderStyle.width > 0) { + style.borderWidth = `${data.borderStyle.width}px`; + const horizontalRadius = data.borderStyle.horizontalCornerRadius; + const verticalRadius = data.borderStyle.verticalCornerRadius; + if (horizontalRadius > 0 || verticalRadius > 0) { + const radius = `calc(${horizontalRadius}px * var(--scale-factor)) / calc(${verticalRadius}px * var(--scale-factor))`; + style.borderRadius = radius; + } else if (this instanceof RadioButtonWidgetAnnotationElement) { + const radius = `calc(${width}px * var(--scale-factor)) / calc(${height}px * var(--scale-factor))`; + style.borderRadius = radius; + } + switch (data.borderStyle.style) { + case AnnotationBorderStyleType.SOLID: + style.borderStyle = "solid"; + break; + case AnnotationBorderStyleType.DASHED: + style.borderStyle = "dashed"; + break; + case AnnotationBorderStyleType.BEVELED: + warn("Unimplemented border style: beveled"); + break; + case AnnotationBorderStyleType.INSET: + warn("Unimplemented border style: inset"); + break; + case AnnotationBorderStyleType.UNDERLINE: + style.borderBottomStyle = "solid"; + break; + default: + break; + } + const borderColor = data.borderColor || null; + if (borderColor) { + this.#hasBorder = true; + style.borderColor = Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0); + } else { + style.borderWidth = 0; + } + } + const rect = Util.normalizeRect([data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1]]); + const { + pageWidth, + pageHeight, + pageX, + pageY + } = viewport.rawDims; + style.left = `${100 * (rect[0] - pageX) / pageWidth}%`; + style.top = `${100 * (rect[1] - pageY) / pageHeight}%`; + const { + rotation + } = data; + if (data.hasOwnCanvas || rotation === 0) { + style.width = `${100 * width / pageWidth}%`; + style.height = `${100 * height / pageHeight}%`; + } else { + this.setRotation(rotation, container); + } + return container; + } + setRotation(angle, container = this.container) { + if (!this.data.rect) { + return; + } + const { + pageWidth, + pageHeight + } = this.parent.viewport.rawDims; + const { + width, + height + } = getRectDims(this.data.rect); + let elementWidth, elementHeight; + if (angle % 180 === 0) { + elementWidth = 100 * width / pageWidth; + elementHeight = 100 * height / pageHeight; + } else { + elementWidth = 100 * height / pageWidth; + elementHeight = 100 * width / pageHeight; + } + container.style.width = `${elementWidth}%`; + container.style.height = `${elementHeight}%`; + container.setAttribute("data-main-rotation", (360 - angle) % 360); + } + get _commonActions() { + const setColor = (jsName, styleName, event) => { + const color = event.detail[jsName]; + const colorType = color[0]; + const colorArray = color.slice(1); + event.target.style[styleName] = ColorConverters[`${colorType}_HTML`](colorArray); + this.annotationStorage.setValue(this.data.id, { + [styleName]: ColorConverters[`${colorType}_rgb`](colorArray) + }); + }; + return shadow(this, "_commonActions", { + display: event => { + const { + display + } = event.detail; + const hidden = display % 2 === 1; + this.container.style.visibility = hidden ? "hidden" : "visible"; + this.annotationStorage.setValue(this.data.id, { + noView: hidden, + noPrint: display === 1 || display === 2 + }); + }, + print: event => { + this.annotationStorage.setValue(this.data.id, { + noPrint: !event.detail.print + }); + }, + hidden: event => { + const { + hidden + } = event.detail; + this.container.style.visibility = hidden ? "hidden" : "visible"; + this.annotationStorage.setValue(this.data.id, { + noPrint: hidden, + noView: hidden + }); + }, + focus: event => { + setTimeout(() => event.target.focus({ + preventScroll: false + }), 0); + }, + userName: event => { + event.target.title = event.detail.userName; + }, + readonly: event => { + event.target.disabled = event.detail.readonly; + }, + required: event => { + this._setRequired(event.target, event.detail.required); + }, + bgColor: event => { + setColor("bgColor", "backgroundColor", event); + }, + fillColor: event => { + setColor("fillColor", "backgroundColor", event); + }, + fgColor: event => { + setColor("fgColor", "color", event); + }, + textColor: event => { + setColor("textColor", "color", event); + }, + borderColor: event => { + setColor("borderColor", "borderColor", event); + }, + strokeColor: event => { + setColor("strokeColor", "borderColor", event); + }, + rotation: event => { + const angle = event.detail.rotation; + this.setRotation(angle); + this.annotationStorage.setValue(this.data.id, { + rotation: angle + }); + } + }); + } + _dispatchEventFromSandbox(actions, jsEvent) { + const commonActions = this._commonActions; + for (const name of Object.keys(jsEvent.detail)) { + const action = actions[name] || commonActions[name]; + action?.(jsEvent); + } + } + _setDefaultPropertiesFromJS(element) { + if (!this.enableScripting) { + return; + } + const storedData = this.annotationStorage.getRawValue(this.data.id); + if (!storedData) { + return; + } + const commonActions = this._commonActions; + for (const [actionName, detail] of Object.entries(storedData)) { + const action = commonActions[actionName]; + if (action) { + const eventProxy = { + detail: { + [actionName]: detail + }, + target: element + }; + action(eventProxy); + delete storedData[actionName]; + } + } + } + _createQuadrilaterals() { + if (!this.container) { + return; + } + const { + quadPoints + } = this.data; + if (!quadPoints) { + return; + } + const [rectBlX, rectBlY, rectTrX, rectTrY] = this.data.rect.map(x => Math.fround(x)); + if (quadPoints.length === 8) { + const [trX, trY, blX, blY] = quadPoints.subarray(2, 6); + if (rectTrX === trX && rectTrY === trY && rectBlX === blX && rectBlY === blY) { + return; + } + } + const { + style + } = this.container; + let svgBuffer; + if (this.#hasBorder) { + const { + borderColor, + borderWidth + } = style; + style.borderWidth = 0; + svgBuffer = ["url('data:image/svg+xml;utf8,", ``, ``]; + this.container.classList.add("hasBorder"); + } + const width = rectTrX - rectBlX; + const height = rectTrY - rectBlY; + const { + svgFactory + } = this; + const svg = svgFactory.createElement("svg"); + svg.classList.add("quadrilateralsContainer"); + svg.setAttribute("width", 0); + svg.setAttribute("height", 0); + const defs = svgFactory.createElement("defs"); + svg.append(defs); + const clipPath = svgFactory.createElement("clipPath"); + const id = `clippath_${this.data.id}`; + clipPath.setAttribute("id", id); + clipPath.setAttribute("clipPathUnits", "objectBoundingBox"); + defs.append(clipPath); + for (let i = 2, ii = quadPoints.length; i < ii; i += 8) { + const trX = quadPoints[i]; + const trY = quadPoints[i + 1]; + const blX = quadPoints[i + 2]; + const blY = quadPoints[i + 3]; + const rect = svgFactory.createElement("rect"); + const x = (blX - rectBlX) / width; + const y = (rectTrY - trY) / height; + const rectWidth = (trX - blX) / width; + const rectHeight = (trY - blY) / height; + rect.setAttribute("x", x); + rect.setAttribute("y", y); + rect.setAttribute("width", rectWidth); + rect.setAttribute("height", rectHeight); + clipPath.append(rect); + svgBuffer?.push(``); + } + if (this.#hasBorder) { + svgBuffer.push(`')`); + style.backgroundImage = svgBuffer.join(""); + } + this.container.append(svg); + this.container.style.clipPath = `url(#${id})`; + } + _createPopup() { + const { + data + } = this; + const popup = this.#popupElement = new PopupAnnotationElement({ + data: { + color: data.color, + titleObj: data.titleObj, + modificationDate: data.modificationDate, + contentsObj: data.contentsObj, + richText: data.richText, + parentRect: data.rect, + borderStyle: 0, + id: `popup_${data.id}`, + rotation: data.rotation + }, + parent: this.parent, + elements: [this] + }); + this.parent.div.append(popup.render()); + } + render() { + unreachable("Abstract method `AnnotationElement.render` called"); + } + _getElementsByName(name, skipId = null) { + const fields = []; + if (this._fieldObjects) { + const fieldObj = this._fieldObjects[name]; + if (fieldObj) { + for (const { + page, + id, + exportValues + } of fieldObj) { + if (page === -1) { + continue; + } + if (id === skipId) { + continue; + } + const exportValue = typeof exportValues === "string" ? exportValues : null; + const domElement = document.querySelector(`[data-element-id="${id}"]`); + if (domElement && !GetElementsByNameSet.has(domElement)) { + warn(`_getElementsByName - element not allowed: ${id}`); + continue; + } + fields.push({ + id, + exportValue, + domElement + }); + } + } + return fields; + } + for (const domElement of document.getElementsByName(name)) { + const { + exportValue + } = domElement; + const id = domElement.getAttribute("data-element-id"); + if (id === skipId) { + continue; + } + if (!GetElementsByNameSet.has(domElement)) { + continue; + } + fields.push({ + id, + exportValue, + domElement + }); + } + return fields; + } + show() { + if (this.container) { + this.container.hidden = false; + } + this.popup?.maybeShow(); + } + hide() { + if (this.container) { + this.container.hidden = true; + } + this.popup?.forceHide(); + } + getElementsToTriggerPopup() { + return this.container; + } + addHighlightArea() { + const triggers = this.getElementsToTriggerPopup(); + if (Array.isArray(triggers)) { + for (const element of triggers) { + element.classList.add("highlightArea"); + } + } else { + triggers.classList.add("highlightArea"); + } + } + _editOnDoubleClick() { + if (!this._isEditable) { + return; + } + const { + annotationEditorType: mode, + data: { + id: editId + } + } = this; + this.container.addEventListener("dblclick", () => { + this.linkService.eventBus?.dispatch("switchannotationeditormode", { + source: this, + mode, + editId + }); + }); + } +} +class LinkAnnotationElement extends AnnotationElement { + constructor(parameters, options = null) { + super(parameters, { + isRenderable: true, + ignoreBorder: !!options?.ignoreBorder, + createQuadrilaterals: true + }); + this.isTooltipOnly = parameters.data.isTooltipOnly; + } + render() { + const { + data, + linkService + } = this; + const link = document.createElement("a"); + link.setAttribute("data-element-id", data.id); + let isBound = false; + if (data.url) { + linkService.addLinkAttributes(link, data.url, data.newWindow); + isBound = true; + } else if (data.action) { + this._bindNamedAction(link, data.action); + isBound = true; + } else if (data.attachment) { + this.#bindAttachment(link, data.attachment, data.attachmentDest); + isBound = true; + } else if (data.setOCGState) { + this.#bindSetOCGState(link, data.setOCGState); + isBound = true; + } else if (data.dest) { + this._bindLink(link, data.dest); + isBound = true; + } else { + if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) { + this._bindJSAction(link, data); + isBound = true; + } + if (data.resetForm) { + this._bindResetFormAction(link, data.resetForm); + isBound = true; + } else if (this.isTooltipOnly && !isBound) { + this._bindLink(link, ""); + isBound = true; + } + } + this.container.classList.add("linkAnnotation"); + if (isBound) { + this.container.append(link); + } + return this.container; + } + #setInternalLink() { + this.container.setAttribute("data-internal-link", ""); + } + _bindLink(link, destination) { + link.href = this.linkService.getDestinationHash(destination); + link.onclick = () => { + if (destination) { + this.linkService.goToDestination(destination); + } + return false; + }; + if (destination || destination === "") { + this.#setInternalLink(); + } + } + _bindNamedAction(link, action) { + link.href = this.linkService.getAnchorUrl(""); + link.onclick = () => { + this.linkService.executeNamedAction(action); + return false; + }; + this.#setInternalLink(); + } + #bindAttachment(link, attachment, dest = null) { + link.href = this.linkService.getAnchorUrl(""); + if (attachment.description) { + link.title = attachment.description; + } + link.onclick = () => { + this.downloadManager?.openOrDownloadData(attachment.content, attachment.filename, dest); + return false; + }; + this.#setInternalLink(); + } + #bindSetOCGState(link, action) { + link.href = this.linkService.getAnchorUrl(""); + link.onclick = () => { + this.linkService.executeSetOCGState(action); + return false; + }; + this.#setInternalLink(); + } + _bindJSAction(link, data) { + link.href = this.linkService.getAnchorUrl(""); + const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]); + for (const name of Object.keys(data.actions)) { + const jsName = map.get(name); + if (!jsName) { + continue; + } + link[jsName] = () => { + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id: data.id, + name + } + }); + return false; + }; + } + if (!link.onclick) { + link.onclick = () => false; + } + this.#setInternalLink(); + } + _bindResetFormAction(link, resetForm) { + const otherClickAction = link.onclick; + if (!otherClickAction) { + link.href = this.linkService.getAnchorUrl(""); + } + this.#setInternalLink(); + if (!this._fieldObjects) { + warn(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided."); + if (!otherClickAction) { + link.onclick = () => false; + } + return; + } + link.onclick = () => { + otherClickAction?.(); + const { + fields: resetFormFields, + refs: resetFormRefs, + include + } = resetForm; + const allFields = []; + if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) { + const fieldIds = new Set(resetFormRefs); + for (const fieldName of resetFormFields) { + const fields = this._fieldObjects[fieldName] || []; + for (const { + id + } of fields) { + fieldIds.add(id); + } + } + for (const fields of Object.values(this._fieldObjects)) { + for (const field of fields) { + if (fieldIds.has(field.id) === include) { + allFields.push(field); + } + } + } + } else { + for (const fields of Object.values(this._fieldObjects)) { + allFields.push(...fields); + } + } + const storage = this.annotationStorage; + const allIds = []; + for (const field of allFields) { + const { + id + } = field; + allIds.push(id); + switch (field.type) { + case "text": + { + const value = field.defaultValue || ""; + storage.setValue(id, { + value + }); + break; + } + case "checkbox": + case "radiobutton": + { + const value = field.defaultValue === field.exportValues; + storage.setValue(id, { + value + }); + break; + } + case "combobox": + case "listbox": + { + const value = field.defaultValue || ""; + storage.setValue(id, { + value + }); + break; + } + default: + continue; + } + const domElement = document.querySelector(`[data-element-id="${id}"]`); + if (!domElement) { + continue; + } else if (!GetElementsByNameSet.has(domElement)) { + warn(`_bindResetFormAction - element not allowed: ${id}`); + continue; + } + domElement.dispatchEvent(new Event("resetform")); + } + if (this.enableScripting) { + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id: "app", + ids: allIds, + name: "ResetForm" + } + }); + } + return false; + }; + } +} +class TextAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true + }); + } + render() { + this.container.classList.add("textAnnotation"); + const image = document.createElement("img"); + image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg"; + image.setAttribute("data-l10n-id", "pdfjs-text-annotation-type"); + image.setAttribute("data-l10n-args", JSON.stringify({ + type: this.data.name + })); + if (!this.data.popupRef && this.hasPopupData) { + this._createPopup(); + } + this.container.append(image); + return this.container; + } +} +class WidgetAnnotationElement extends AnnotationElement { + render() { + return this.container; + } + showElementAndHideCanvas(element) { + if (this.data.hasOwnCanvas) { + if (element.previousSibling?.nodeName === "CANVAS") { + element.previousSibling.hidden = true; + } + element.hidden = false; + } + } + _getKeyModifier(event) { + return util_FeatureTest.platform.isMac ? event.metaKey : event.ctrlKey; + } + _setEventListener(element, elementData, baseName, eventName, valueGetter) { + if (baseName.includes("mouse")) { + element.addEventListener(baseName, event => { + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id: this.data.id, + name: eventName, + value: valueGetter(event), + shift: event.shiftKey, + modifier: this._getKeyModifier(event) + } + }); + }); + } else { + element.addEventListener(baseName, event => { + if (baseName === "blur") { + if (!elementData.focused || !event.relatedTarget) { + return; + } + elementData.focused = false; + } else if (baseName === "focus") { + if (elementData.focused) { + return; + } + elementData.focused = true; + } + if (!valueGetter) { + return; + } + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id: this.data.id, + name: eventName, + value: valueGetter(event) + } + }); + }); + } + } + _setEventListeners(element, elementData, names, getter) { + for (const [baseName, eventName] of names) { + if (eventName === "Action" || this.data.actions?.[eventName]) { + if (eventName === "Focus" || eventName === "Blur") { + elementData ||= { + focused: false + }; + } + this._setEventListener(element, elementData, baseName, eventName, getter); + if (eventName === "Focus" && !this.data.actions?.Blur) { + this._setEventListener(element, elementData, "blur", "Blur", null); + } else if (eventName === "Blur" && !this.data.actions?.Focus) { + this._setEventListener(element, elementData, "focus", "Focus", null); + } + } + } + } + _setBackgroundColor(element) { + const color = this.data.backgroundColor || null; + element.style.backgroundColor = color === null ? "transparent" : Util.makeHexColor(color[0], color[1], color[2]); + } + _setTextStyle(element) { + const TEXT_ALIGNMENT = ["left", "center", "right"]; + const { + fontColor + } = this.data.defaultAppearanceData; + const fontSize = this.data.defaultAppearanceData.fontSize || annotation_layer_DEFAULT_FONT_SIZE; + const style = element.style; + let computedFontSize; + const BORDER_SIZE = 2; + const roundToOneDecimal = x => Math.round(10 * x) / 10; + if (this.data.multiLine) { + const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE); + const numberOfLines = Math.round(height / (LINE_FACTOR * fontSize)) || 1; + const lineHeight = height / numberOfLines; + computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / LINE_FACTOR)); + } else { + const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE); + computedFontSize = Math.min(fontSize, roundToOneDecimal(height / LINE_FACTOR)); + } + style.fontSize = `calc(${computedFontSize}px * var(--scale-factor))`; + style.color = Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]); + if (this.data.textAlignment !== null) { + style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment]; + } + } + _setRequired(element, isRequired) { + if (isRequired) { + element.setAttribute("required", true); + } else { + element.removeAttribute("required"); + } + element.setAttribute("aria-required", isRequired); + } +} +class TextWidgetAnnotationElement extends WidgetAnnotationElement { + constructor(parameters) { + const isRenderable = parameters.renderForms || parameters.data.hasOwnCanvas || !parameters.data.hasAppearance && !!parameters.data.fieldValue; + super(parameters, { + isRenderable + }); + } + setPropertyOnSiblings(base, key, value, keyInStorage) { + const storage = this.annotationStorage; + for (const element of this._getElementsByName(base.name, base.id)) { + if (element.domElement) { + element.domElement[key] = value; + } + storage.setValue(element.id, { + [keyInStorage]: value + }); + } + } + render() { + const storage = this.annotationStorage; + const id = this.data.id; + this.container.classList.add("textWidgetAnnotation"); + let element = null; + if (this.renderForms) { + const storedData = storage.getValue(id, { + value: this.data.fieldValue + }); + let textContent = storedData.value || ""; + const maxLen = storage.getValue(id, { + charLimit: this.data.maxLen + }).charLimit; + if (maxLen && textContent.length > maxLen) { + textContent = textContent.slice(0, maxLen); + } + let fieldFormattedValues = storedData.formattedValue || this.data.textContent?.join("\n") || null; + if (fieldFormattedValues && this.data.comb) { + fieldFormattedValues = fieldFormattedValues.replaceAll(/\s+/g, ""); + } + const elementData = { + userValue: textContent, + formattedValue: fieldFormattedValues, + lastCommittedValue: null, + commitKey: 1, + focused: false + }; + if (this.data.multiLine) { + element = document.createElement("textarea"); + element.textContent = fieldFormattedValues ?? textContent; + if (this.data.doNotScroll) { + element.style.overflowY = "hidden"; + } + } else { + element = document.createElement("input"); + element.type = "text"; + element.setAttribute("value", fieldFormattedValues ?? textContent); + if (this.data.doNotScroll) { + element.style.overflowX = "hidden"; + } + } + if (this.data.hasOwnCanvas) { + element.hidden = true; + } + GetElementsByNameSet.add(element); + element.setAttribute("data-element-id", id); + element.disabled = this.data.readOnly; + element.name = this.data.fieldName; + element.tabIndex = DEFAULT_TAB_INDEX; + this._setRequired(element, this.data.required); + if (maxLen) { + element.maxLength = maxLen; + } + element.addEventListener("input", event => { + storage.setValue(id, { + value: event.target.value + }); + this.setPropertyOnSiblings(element, "value", event.target.value, "value"); + elementData.formattedValue = null; + }); + element.addEventListener("resetform", event => { + const defaultValue = this.data.defaultFieldValue ?? ""; + element.value = elementData.userValue = defaultValue; + elementData.formattedValue = null; + }); + let blurListener = event => { + const { + formattedValue + } = elementData; + if (formattedValue !== null && formattedValue !== undefined) { + event.target.value = formattedValue; + } + event.target.scrollLeft = 0; + }; + if (this.enableScripting && this.hasJSActions) { + element.addEventListener("focus", event => { + if (elementData.focused) { + return; + } + const { + target + } = event; + if (elementData.userValue) { + target.value = elementData.userValue; + } + elementData.lastCommittedValue = target.value; + elementData.commitKey = 1; + if (!this.data.actions?.Focus) { + elementData.focused = true; + } + }); + element.addEventListener("updatefromsandbox", jsEvent => { + this.showElementAndHideCanvas(jsEvent.target); + const actions = { + value(event) { + elementData.userValue = event.detail.value ?? ""; + storage.setValue(id, { + value: elementData.userValue.toString() + }); + event.target.value = elementData.userValue; + }, + formattedValue(event) { + const { + formattedValue + } = event.detail; + elementData.formattedValue = formattedValue; + if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) { + event.target.value = formattedValue; + } + storage.setValue(id, { + formattedValue + }); + }, + selRange(event) { + event.target.setSelectionRange(...event.detail.selRange); + }, + charLimit: event => { + const { + charLimit + } = event.detail; + const { + target + } = event; + if (charLimit === 0) { + target.removeAttribute("maxLength"); + return; + } + target.setAttribute("maxLength", charLimit); + let value = elementData.userValue; + if (!value || value.length <= charLimit) { + return; + } + value = value.slice(0, charLimit); + target.value = elementData.userValue = value; + storage.setValue(id, { + value + }); + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value, + willCommit: true, + commitKey: 1, + selStart: target.selectionStart, + selEnd: target.selectionEnd + } + }); + } + }; + this._dispatchEventFromSandbox(actions, jsEvent); + }); + element.addEventListener("keydown", event => { + elementData.commitKey = 1; + let commitKey = -1; + if (event.key === "Escape") { + commitKey = 0; + } else if (event.key === "Enter" && !this.data.multiLine) { + commitKey = 2; + } else if (event.key === "Tab") { + elementData.commitKey = 3; + } + if (commitKey === -1) { + return; + } + const { + value + } = event.target; + if (elementData.lastCommittedValue === value) { + return; + } + elementData.lastCommittedValue = value; + elementData.userValue = value; + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value, + willCommit: true, + commitKey, + selStart: event.target.selectionStart, + selEnd: event.target.selectionEnd + } + }); + }); + const _blurListener = blurListener; + blurListener = null; + element.addEventListener("blur", event => { + if (!elementData.focused || !event.relatedTarget) { + return; + } + if (!this.data.actions?.Blur) { + elementData.focused = false; + } + const { + value + } = event.target; + elementData.userValue = value; + if (elementData.lastCommittedValue !== value) { + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value, + willCommit: true, + commitKey: elementData.commitKey, + selStart: event.target.selectionStart, + selEnd: event.target.selectionEnd + } + }); + } + _blurListener(event); + }); + if (this.data.actions?.Keystroke) { + element.addEventListener("beforeinput", event => { + elementData.lastCommittedValue = null; + const { + data, + target + } = event; + const { + value, + selectionStart, + selectionEnd + } = target; + let selStart = selectionStart, + selEnd = selectionEnd; + switch (event.inputType) { + case "deleteWordBackward": + { + const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/); + if (match) { + selStart -= match[0].length; + } + break; + } + case "deleteWordForward": + { + const match = value.substring(selectionStart).match(/^[^\w]*\w*/); + if (match) { + selEnd += match[0].length; + } + break; + } + case "deleteContentBackward": + if (selectionStart === selectionEnd) { + selStart -= 1; + } + break; + case "deleteContentForward": + if (selectionStart === selectionEnd) { + selEnd += 1; + } + break; + } + event.preventDefault(); + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value, + change: data || "", + willCommit: false, + selStart, + selEnd + } + }); + }); + } + this._setEventListeners(element, elementData, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value); + } + if (blurListener) { + element.addEventListener("blur", blurListener); + } + if (this.data.comb) { + const fieldWidth = this.data.rect[2] - this.data.rect[0]; + const combWidth = fieldWidth / maxLen; + element.classList.add("comb"); + element.style.letterSpacing = `calc(${combWidth}px * var(--scale-factor) - 1ch)`; + } + } else { + element = document.createElement("div"); + element.textContent = this.data.fieldValue; + element.style.verticalAlign = "middle"; + element.style.display = "table-cell"; + if (this.data.hasOwnCanvas) { + element.hidden = true; + } + } + this._setTextStyle(element); + this._setBackgroundColor(element); + this._setDefaultPropertiesFromJS(element); + this.container.append(element); + return this.container; + } +} +class SignatureWidgetAnnotationElement extends WidgetAnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: !!parameters.data.hasOwnCanvas + }); + } +} +class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: parameters.renderForms + }); + } + render() { + const storage = this.annotationStorage; + const data = this.data; + const id = data.id; + let value = storage.getValue(id, { + value: data.exportValue === data.fieldValue + }).value; + if (typeof value === "string") { + value = value !== "Off"; + storage.setValue(id, { + value + }); + } + this.container.classList.add("buttonWidgetAnnotation", "checkBox"); + const element = document.createElement("input"); + GetElementsByNameSet.add(element); + element.setAttribute("data-element-id", id); + element.disabled = data.readOnly; + this._setRequired(element, this.data.required); + element.type = "checkbox"; + element.name = data.fieldName; + if (value) { + element.setAttribute("checked", true); + } + element.setAttribute("exportValue", data.exportValue); + element.tabIndex = DEFAULT_TAB_INDEX; + element.addEventListener("change", event => { + const { + name, + checked + } = event.target; + for (const checkbox of this._getElementsByName(name, id)) { + const curChecked = checked && checkbox.exportValue === data.exportValue; + if (checkbox.domElement) { + checkbox.domElement.checked = curChecked; + } + storage.setValue(checkbox.id, { + value: curChecked + }); + } + storage.setValue(id, { + value: checked + }); + }); + element.addEventListener("resetform", event => { + const defaultValue = data.defaultFieldValue || "Off"; + event.target.checked = defaultValue === data.exportValue; + }); + if (this.enableScripting && this.hasJSActions) { + element.addEventListener("updatefromsandbox", jsEvent => { + const actions = { + value(event) { + event.target.checked = event.detail.value !== "Off"; + storage.setValue(id, { + value: event.target.checked + }); + } + }; + this._dispatchEventFromSandbox(actions, jsEvent); + }); + this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked); + } + this._setBackgroundColor(element); + this._setDefaultPropertiesFromJS(element); + this.container.append(element); + return this.container; + } +} +class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: parameters.renderForms + }); + } + render() { + this.container.classList.add("buttonWidgetAnnotation", "radioButton"); + const storage = this.annotationStorage; + const data = this.data; + const id = data.id; + let value = storage.getValue(id, { + value: data.fieldValue === data.buttonValue + }).value; + if (typeof value === "string") { + value = value !== data.buttonValue; + storage.setValue(id, { + value + }); + } + if (value) { + for (const radio of this._getElementsByName(data.fieldName, id)) { + storage.setValue(radio.id, { + value: false + }); + } + } + const element = document.createElement("input"); + GetElementsByNameSet.add(element); + element.setAttribute("data-element-id", id); + element.disabled = data.readOnly; + this._setRequired(element, this.data.required); + element.type = "radio"; + element.name = data.fieldName; + if (value) { + element.setAttribute("checked", true); + } + element.tabIndex = DEFAULT_TAB_INDEX; + element.addEventListener("change", event => { + const { + name, + checked + } = event.target; + for (const radio of this._getElementsByName(name, id)) { + storage.setValue(radio.id, { + value: false + }); + } + storage.setValue(id, { + value: checked + }); + }); + element.addEventListener("resetform", event => { + const defaultValue = data.defaultFieldValue; + event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue; + }); + if (this.enableScripting && this.hasJSActions) { + const pdfButtonValue = data.buttonValue; + element.addEventListener("updatefromsandbox", jsEvent => { + const actions = { + value: event => { + const checked = pdfButtonValue === event.detail.value; + for (const radio of this._getElementsByName(event.target.name)) { + const curChecked = checked && radio.id === id; + if (radio.domElement) { + radio.domElement.checked = curChecked; + } + storage.setValue(radio.id, { + value: curChecked + }); + } + } + }; + this._dispatchEventFromSandbox(actions, jsEvent); + }); + this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked); + } + this._setBackgroundColor(element); + this._setDefaultPropertiesFromJS(element); + this.container.append(element); + return this.container; + } +} +class PushButtonWidgetAnnotationElement extends LinkAnnotationElement { + constructor(parameters) { + super(parameters, { + ignoreBorder: parameters.data.hasAppearance + }); + } + render() { + const container = super.render(); + container.classList.add("buttonWidgetAnnotation", "pushButton"); + const linkElement = container.lastChild; + if (this.enableScripting && this.hasJSActions && linkElement) { + this._setDefaultPropertiesFromJS(linkElement); + linkElement.addEventListener("updatefromsandbox", jsEvent => { + this._dispatchEventFromSandbox({}, jsEvent); + }); + } + return container; + } +} +class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: parameters.renderForms + }); + } + render() { + this.container.classList.add("choiceWidgetAnnotation"); + const storage = this.annotationStorage; + const id = this.data.id; + const storedData = storage.getValue(id, { + value: this.data.fieldValue + }); + const selectElement = document.createElement("select"); + GetElementsByNameSet.add(selectElement); + selectElement.setAttribute("data-element-id", id); + selectElement.disabled = this.data.readOnly; + this._setRequired(selectElement, this.data.required); + selectElement.name = this.data.fieldName; + selectElement.tabIndex = DEFAULT_TAB_INDEX; + let addAnEmptyEntry = this.data.combo && this.data.options.length > 0; + if (!this.data.combo) { + selectElement.size = this.data.options.length; + if (this.data.multiSelect) { + selectElement.multiple = true; + } + } + selectElement.addEventListener("resetform", event => { + const defaultValue = this.data.defaultFieldValue; + for (const option of selectElement.options) { + option.selected = option.value === defaultValue; + } + }); + for (const option of this.data.options) { + const optionElement = document.createElement("option"); + optionElement.textContent = option.displayValue; + optionElement.value = option.exportValue; + if (storedData.value.includes(option.exportValue)) { + optionElement.setAttribute("selected", true); + addAnEmptyEntry = false; + } + selectElement.append(optionElement); + } + let removeEmptyEntry = null; + if (addAnEmptyEntry) { + const noneOptionElement = document.createElement("option"); + noneOptionElement.value = " "; + noneOptionElement.setAttribute("hidden", true); + noneOptionElement.setAttribute("selected", true); + selectElement.prepend(noneOptionElement); + removeEmptyEntry = () => { + noneOptionElement.remove(); + selectElement.removeEventListener("input", removeEmptyEntry); + removeEmptyEntry = null; + }; + selectElement.addEventListener("input", removeEmptyEntry); + } + const getValue = isExport => { + const name = isExport ? "value" : "textContent"; + const { + options, + multiple + } = selectElement; + if (!multiple) { + return options.selectedIndex === -1 ? null : options[options.selectedIndex][name]; + } + return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]); + }; + let selectedValues = getValue(false); + const getItems = event => { + const options = event.target.options; + return Array.prototype.map.call(options, option => ({ + displayValue: option.textContent, + exportValue: option.value + })); + }; + if (this.enableScripting && this.hasJSActions) { + selectElement.addEventListener("updatefromsandbox", jsEvent => { + const actions = { + value(event) { + removeEmptyEntry?.(); + const value = event.detail.value; + const values = new Set(Array.isArray(value) ? value : [value]); + for (const option of selectElement.options) { + option.selected = values.has(option.value); + } + storage.setValue(id, { + value: getValue(true) + }); + selectedValues = getValue(false); + }, + multipleSelection(event) { + selectElement.multiple = true; + }, + remove(event) { + const options = selectElement.options; + const index = event.detail.remove; + options[index].selected = false; + selectElement.remove(index); + if (options.length > 0) { + const i = Array.prototype.findIndex.call(options, option => option.selected); + if (i === -1) { + options[0].selected = true; + } + } + storage.setValue(id, { + value: getValue(true), + items: getItems(event) + }); + selectedValues = getValue(false); + }, + clear(event) { + while (selectElement.length !== 0) { + selectElement.remove(0); + } + storage.setValue(id, { + value: null, + items: [] + }); + selectedValues = getValue(false); + }, + insert(event) { + const { + index, + displayValue, + exportValue + } = event.detail.insert; + const selectChild = selectElement.children[index]; + const optionElement = document.createElement("option"); + optionElement.textContent = displayValue; + optionElement.value = exportValue; + if (selectChild) { + selectChild.before(optionElement); + } else { + selectElement.append(optionElement); + } + storage.setValue(id, { + value: getValue(true), + items: getItems(event) + }); + selectedValues = getValue(false); + }, + items(event) { + const { + items + } = event.detail; + while (selectElement.length !== 0) { + selectElement.remove(0); + } + for (const item of items) { + const { + displayValue, + exportValue + } = item; + const optionElement = document.createElement("option"); + optionElement.textContent = displayValue; + optionElement.value = exportValue; + selectElement.append(optionElement); + } + if (selectElement.options.length > 0) { + selectElement.options[0].selected = true; + } + storage.setValue(id, { + value: getValue(true), + items: getItems(event) + }); + selectedValues = getValue(false); + }, + indices(event) { + const indices = new Set(event.detail.indices); + for (const option of event.target.options) { + option.selected = indices.has(option.index); + } + storage.setValue(id, { + value: getValue(true) + }); + selectedValues = getValue(false); + }, + editable(event) { + event.target.disabled = !event.detail.editable; + } + }; + this._dispatchEventFromSandbox(actions, jsEvent); + }); + selectElement.addEventListener("input", event => { + const exportValue = getValue(true); + const change = getValue(false); + storage.setValue(id, { + value: exportValue + }); + event.preventDefault(); + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value: selectedValues, + change, + changeEx: exportValue, + willCommit: false, + commitKey: 1, + keyDown: false + } + }); + }); + this._setEventListeners(selectElement, null, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"], ["input", "Validate"]], event => event.target.value); + } else { + selectElement.addEventListener("input", function (event) { + storage.setValue(id, { + value: getValue(true) + }); + }); + } + if (this.data.combo) { + this._setTextStyle(selectElement); + } else {} + this._setBackgroundColor(selectElement); + this._setDefaultPropertiesFromJS(selectElement); + this.container.append(selectElement); + return this.container; + } +} +class PopupAnnotationElement extends AnnotationElement { + constructor(parameters) { + const { + data, + elements + } = parameters; + super(parameters, { + isRenderable: AnnotationElement._hasPopupData(data) + }); + this.elements = elements; + this.popup = null; + } + render() { + this.container.classList.add("popupAnnotation"); + const popup = this.popup = new PopupElement({ + container: this.container, + color: this.data.color, + titleObj: this.data.titleObj, + modificationDate: this.data.modificationDate, + contentsObj: this.data.contentsObj, + richText: this.data.richText, + rect: this.data.rect, + parentRect: this.data.parentRect || null, + parent: this.parent, + elements: this.elements, + open: this.data.open + }); + const elementIds = []; + for (const element of this.elements) { + element.popup = popup; + element.container.ariaHasPopup = "dialog"; + elementIds.push(element.data.id); + element.addHighlightArea(); + } + this.container.setAttribute("aria-controls", elementIds.map(id => `${AnnotationPrefix}${id}`).join(",")); + return this.container; + } +} +class PopupElement { + #boundKeyDown = this.#keyDown.bind(this); + #boundHide = this.#hide.bind(this); + #boundShow = this.#show.bind(this); + #boundToggle = this.#toggle.bind(this); + #color = null; + #container = null; + #contentsObj = null; + #dateObj = null; + #elements = null; + #parent = null; + #parentRect = null; + #pinned = false; + #popup = null; + #position = null; + #rect = null; + #richText = null; + #titleObj = null; + #updates = null; + #wasVisible = false; + constructor({ + container, + color, + elements, + titleObj, + modificationDate, + contentsObj, + richText, + parent, + rect, + parentRect, + open + }) { + this.#container = container; + this.#titleObj = titleObj; + this.#contentsObj = contentsObj; + this.#richText = richText; + this.#parent = parent; + this.#color = color; + this.#rect = rect; + this.#parentRect = parentRect; + this.#elements = elements; + this.#dateObj = PDFDateString.toDateObject(modificationDate); + this.trigger = elements.flatMap(e => e.getElementsToTriggerPopup()); + for (const element of this.trigger) { + element.addEventListener("click", this.#boundToggle); + element.addEventListener("mouseenter", this.#boundShow); + element.addEventListener("mouseleave", this.#boundHide); + element.classList.add("popupTriggerArea"); + } + for (const element of elements) { + element.container?.addEventListener("keydown", this.#boundKeyDown); + } + this.#container.hidden = true; + if (open) { + this.#toggle(); + } + } + render() { + if (this.#popup) { + return; + } + const popup = this.#popup = document.createElement("div"); + popup.className = "popup"; + if (this.#color) { + const baseColor = popup.style.outlineColor = Util.makeHexColor(...this.#color); + if (CSS.supports("background-color", "color-mix(in srgb, red 30%, white)")) { + popup.style.backgroundColor = `color-mix(in srgb, ${baseColor} 30%, white)`; + } else { + const BACKGROUND_ENLIGHT = 0.7; + popup.style.backgroundColor = Util.makeHexColor(...this.#color.map(c => Math.floor(BACKGROUND_ENLIGHT * (255 - c) + c))); + } + } + const header = document.createElement("span"); + header.className = "header"; + const title = document.createElement("h1"); + header.append(title); + ({ + dir: title.dir, + str: title.textContent + } = this.#titleObj); + popup.append(header); + if (this.#dateObj) { + const modificationDate = document.createElement("span"); + modificationDate.classList.add("popupDate"); + modificationDate.setAttribute("data-l10n-id", "pdfjs-annotation-date-time-string"); + modificationDate.setAttribute("data-l10n-args", JSON.stringify({ + dateObj: this.#dateObj.valueOf() + })); + header.append(modificationDate); + } + const html = this.#html; + if (html) { + XfaLayer.render({ + xfaHtml: html, + intent: "richText", + div: popup + }); + popup.lastChild.classList.add("richText", "popupContent"); + } else { + const contents = this._formatContents(this.#contentsObj); + popup.append(contents); + } + this.#container.append(popup); + } + get #html() { + const richText = this.#richText; + const contentsObj = this.#contentsObj; + if (richText?.str && (!contentsObj?.str || contentsObj.str === richText.str)) { + return this.#richText.html || null; + } + return null; + } + get #fontSize() { + return this.#html?.attributes?.style?.fontSize || 0; + } + get #fontColor() { + return this.#html?.attributes?.style?.color || null; + } + #makePopupContent(text) { + const popupLines = []; + const popupContent = { + str: text, + html: { + name: "div", + attributes: { + dir: "auto" + }, + children: [{ + name: "p", + children: popupLines + }] + } + }; + const lineAttributes = { + style: { + color: this.#fontColor, + fontSize: this.#fontSize ? `calc(${this.#fontSize}px * var(--scale-factor))` : "" + } + }; + for (const line of text.split("\n")) { + popupLines.push({ + name: "span", + value: line, + attributes: lineAttributes + }); + } + return popupContent; + } + _formatContents({ + str, + dir + }) { + const p = document.createElement("p"); + p.classList.add("popupContent"); + p.dir = dir; + const lines = str.split(/(?:\r\n?|\n)/); + for (let i = 0, ii = lines.length; i < ii; ++i) { + const line = lines[i]; + p.append(document.createTextNode(line)); + if (i < ii - 1) { + p.append(document.createElement("br")); + } + } + return p; + } + #keyDown(event) { + if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) { + return; + } + if (event.key === "Enter" || event.key === "Escape" && this.#pinned) { + this.#toggle(); + } + } + updateEdited({ + rect, + popupContent + }) { + this.#updates ||= { + contentsObj: this.#contentsObj, + richText: this.#richText + }; + if (rect) { + this.#position = null; + } + if (popupContent) { + this.#richText = this.#makePopupContent(popupContent); + this.#contentsObj = null; + } + this.#popup?.remove(); + this.#popup = null; + } + resetEdited() { + if (!this.#updates) { + return; + } + ({ + contentsObj: this.#contentsObj, + richText: this.#richText + } = this.#updates); + this.#updates = null; + this.#popup?.remove(); + this.#popup = null; + this.#position = null; + } + #setPosition() { + if (this.#position !== null) { + return; + } + const { + page: { + view + }, + viewport: { + rawDims: { + pageWidth, + pageHeight, + pageX, + pageY + } + } + } = this.#parent; + let useParentRect = !!this.#parentRect; + let rect = useParentRect ? this.#parentRect : this.#rect; + for (const element of this.#elements) { + if (!rect || Util.intersect(element.data.rect, rect) !== null) { + rect = element.data.rect; + useParentRect = true; + break; + } + } + const normalizedRect = Util.normalizeRect([rect[0], view[3] - rect[1] + view[1], rect[2], view[3] - rect[3] + view[1]]); + const HORIZONTAL_SPACE_AFTER_ANNOTATION = 5; + const parentWidth = useParentRect ? rect[2] - rect[0] + HORIZONTAL_SPACE_AFTER_ANNOTATION : 0; + const popupLeft = normalizedRect[0] + parentWidth; + const popupTop = normalizedRect[1]; + this.#position = [100 * (popupLeft - pageX) / pageWidth, 100 * (popupTop - pageY) / pageHeight]; + const { + style + } = this.#container; + style.left = `${this.#position[0]}%`; + style.top = `${this.#position[1]}%`; + } + #toggle() { + this.#pinned = !this.#pinned; + if (this.#pinned) { + this.#show(); + this.#container.addEventListener("click", this.#boundToggle); + this.#container.addEventListener("keydown", this.#boundKeyDown); + } else { + this.#hide(); + this.#container.removeEventListener("click", this.#boundToggle); + this.#container.removeEventListener("keydown", this.#boundKeyDown); + } + } + #show() { + if (!this.#popup) { + this.render(); + } + if (!this.isVisible) { + this.#setPosition(); + this.#container.hidden = false; + this.#container.style.zIndex = parseInt(this.#container.style.zIndex) + 1000; + } else if (this.#pinned) { + this.#container.classList.add("focused"); + } + } + #hide() { + this.#container.classList.remove("focused"); + if (this.#pinned || !this.isVisible) { + return; + } + this.#container.hidden = true; + this.#container.style.zIndex = parseInt(this.#container.style.zIndex) - 1000; + } + forceHide() { + this.#wasVisible = this.isVisible; + if (!this.#wasVisible) { + return; + } + this.#container.hidden = true; + } + maybeShow() { + if (!this.#wasVisible) { + return; + } + if (!this.#popup) { + this.#show(); + } + this.#wasVisible = false; + this.#container.hidden = false; + } + get isVisible() { + return this.#container.hidden === false; + } +} +class FreeTextAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + this.textContent = parameters.data.textContent; + this.textPosition = parameters.data.textPosition; + this.annotationEditorType = AnnotationEditorType.FREETEXT; + } + render() { + this.container.classList.add("freeTextAnnotation"); + if (this.textContent) { + const content = document.createElement("div"); + content.classList.add("annotationTextContent"); + content.setAttribute("role", "comment"); + for (const line of this.textContent) { + const lineSpan = document.createElement("span"); + lineSpan.textContent = line; + content.append(lineSpan); + } + this.container.append(content); + } + if (!this.data.popupRef && this.hasPopupData) { + this._createPopup(); + } + this._editOnDoubleClick(); + return this.container; + } +} +class LineAnnotationElement extends AnnotationElement { + #line = null; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + } + render() { + this.container.classList.add("lineAnnotation"); + const data = this.data; + const { + width, + height + } = getRectDims(data.rect); + const svg = this.svgFactory.create(width, height, true); + const line = this.#line = this.svgFactory.createElement("svg:line"); + line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]); + line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]); + line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]); + line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]); + line.setAttribute("stroke-width", data.borderStyle.width || 1); + line.setAttribute("stroke", "transparent"); + line.setAttribute("fill", "transparent"); + svg.append(line); + this.container.append(svg); + if (!data.popupRef && this.hasPopupData) { + this._createPopup(); + } + return this.container; + } + getElementsToTriggerPopup() { + return this.#line; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } +} +class SquareAnnotationElement extends AnnotationElement { + #square = null; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + } + render() { + this.container.classList.add("squareAnnotation"); + const data = this.data; + const { + width, + height + } = getRectDims(data.rect); + const svg = this.svgFactory.create(width, height, true); + const borderWidth = data.borderStyle.width; + const square = this.#square = this.svgFactory.createElement("svg:rect"); + square.setAttribute("x", borderWidth / 2); + square.setAttribute("y", borderWidth / 2); + square.setAttribute("width", width - borderWidth); + square.setAttribute("height", height - borderWidth); + square.setAttribute("stroke-width", borderWidth || 1); + square.setAttribute("stroke", "transparent"); + square.setAttribute("fill", "transparent"); + svg.append(square); + this.container.append(svg); + if (!data.popupRef && this.hasPopupData) { + this._createPopup(); + } + return this.container; + } + getElementsToTriggerPopup() { + return this.#square; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } +} +class CircleAnnotationElement extends AnnotationElement { + #circle = null; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + } + render() { + this.container.classList.add("circleAnnotation"); + const data = this.data; + const { + width, + height + } = getRectDims(data.rect); + const svg = this.svgFactory.create(width, height, true); + const borderWidth = data.borderStyle.width; + const circle = this.#circle = this.svgFactory.createElement("svg:ellipse"); + circle.setAttribute("cx", width / 2); + circle.setAttribute("cy", height / 2); + circle.setAttribute("rx", width / 2 - borderWidth / 2); + circle.setAttribute("ry", height / 2 - borderWidth / 2); + circle.setAttribute("stroke-width", borderWidth || 1); + circle.setAttribute("stroke", "transparent"); + circle.setAttribute("fill", "transparent"); + svg.append(circle); + this.container.append(svg); + if (!data.popupRef && this.hasPopupData) { + this._createPopup(); + } + return this.container; + } + getElementsToTriggerPopup() { + return this.#circle; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } +} +class PolylineAnnotationElement extends AnnotationElement { + #polyline = null; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + this.containerClassName = "polylineAnnotation"; + this.svgElementName = "svg:polyline"; + } + render() { + this.container.classList.add(this.containerClassName); + const { + data: { + rect, + vertices, + borderStyle, + popupRef + } + } = this; + if (!vertices) { + return this.container; + } + const { + width, + height + } = getRectDims(rect); + const svg = this.svgFactory.create(width, height, true); + let points = []; + for (let i = 0, ii = vertices.length; i < ii; i += 2) { + const x = vertices[i] - rect[0]; + const y = rect[3] - vertices[i + 1]; + points.push(`${x},${y}`); + } + points = points.join(" "); + const polyline = this.#polyline = this.svgFactory.createElement(this.svgElementName); + polyline.setAttribute("points", points); + polyline.setAttribute("stroke-width", borderStyle.width || 1); + polyline.setAttribute("stroke", "transparent"); + polyline.setAttribute("fill", "transparent"); + svg.append(polyline); + this.container.append(svg); + if (!popupRef && this.hasPopupData) { + this._createPopup(); + } + return this.container; + } + getElementsToTriggerPopup() { + return this.#polyline; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } +} +class PolygonAnnotationElement extends PolylineAnnotationElement { + constructor(parameters) { + super(parameters); + this.containerClassName = "polygonAnnotation"; + this.svgElementName = "svg:polygon"; + } +} +class CaretAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + } + render() { + this.container.classList.add("caretAnnotation"); + if (!this.data.popupRef && this.hasPopupData) { + this._createPopup(); + } + return this.container; + } +} +class InkAnnotationElement extends AnnotationElement { + #polylinesGroupElement = null; + #polylines = []; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + this.containerClassName = "inkAnnotation"; + this.svgElementName = "svg:polyline"; + this.annotationEditorType = this.data.it === "InkHighlight" ? AnnotationEditorType.HIGHLIGHT : AnnotationEditorType.INK; + } + #getTransform(rotation, rect) { + switch (rotation) { + case 90: + return { + transform: `rotate(90) translate(${-rect[0]},${rect[1]}) scale(1,-1)`, + width: rect[3] - rect[1], + height: rect[2] - rect[0] + }; + case 180: + return { + transform: `rotate(180) translate(${-rect[2]},${rect[1]}) scale(1,-1)`, + width: rect[2] - rect[0], + height: rect[3] - rect[1] + }; + case 270: + return { + transform: `rotate(270) translate(${-rect[2]},${rect[3]}) scale(1,-1)`, + width: rect[3] - rect[1], + height: rect[2] - rect[0] + }; + default: + return { + transform: `translate(${-rect[0]},${rect[3]}) scale(1,-1)`, + width: rect[2] - rect[0], + height: rect[3] - rect[1] + }; + } + } + render() { + this.container.classList.add(this.containerClassName); + const { + data: { + rect, + rotation, + inkLists, + borderStyle, + popupRef + } + } = this; + const { + transform, + width, + height + } = this.#getTransform(rotation, rect); + const svg = this.svgFactory.create(width, height, true); + const g = this.#polylinesGroupElement = this.svgFactory.createElement("svg:g"); + svg.append(g); + g.setAttribute("stroke-width", borderStyle.width || 1); + g.setAttribute("stroke-linecap", "round"); + g.setAttribute("stroke-linejoin", "round"); + g.setAttribute("stroke-miterlimit", 10); + g.setAttribute("stroke", "transparent"); + g.setAttribute("fill", "transparent"); + g.setAttribute("transform", transform); + for (let i = 0, ii = inkLists.length; i < ii; i++) { + const polyline = this.svgFactory.createElement(this.svgElementName); + this.#polylines.push(polyline); + polyline.setAttribute("points", inkLists[i].join(",")); + g.append(polyline); + } + if (!popupRef && this.hasPopupData) { + this._createPopup(); + } + this.container.append(svg); + this._editOnDoubleClick(); + return this.container; + } + updateEdited(params) { + super.updateEdited(params); + const { + thickness, + points, + rect + } = params; + const g = this.#polylinesGroupElement; + if (thickness >= 0) { + g.setAttribute("stroke-width", thickness || 1); + } + if (points) { + for (let i = 0, ii = this.#polylines.length; i < ii; i++) { + this.#polylines[i].setAttribute("points", points[i].join(",")); + } + } + if (rect) { + const { + transform, + width, + height + } = this.#getTransform(this.data.rotation, rect); + const root = g.parentElement; + root.setAttribute("viewBox", `0 0 ${width} ${height}`); + g.setAttribute("transform", transform); + } + } + getElementsToTriggerPopup() { + return this.#polylines; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } +} +class HighlightAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true, + createQuadrilaterals: true + }); + this.annotationEditorType = AnnotationEditorType.HIGHLIGHT; + } + render() { + if (!this.data.popupRef && this.hasPopupData) { + this._createPopup(); + } + this.container.classList.add("highlightAnnotation"); + this._editOnDoubleClick(); + return this.container; + } +} +class UnderlineAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true, + createQuadrilaterals: true + }); + } + render() { + if (!this.data.popupRef && this.hasPopupData) { + this._createPopup(); + } + this.container.classList.add("underlineAnnotation"); + return this.container; + } +} +class SquigglyAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true, + createQuadrilaterals: true + }); + } + render() { + if (!this.data.popupRef && this.hasPopupData) { + this._createPopup(); + } + this.container.classList.add("squigglyAnnotation"); + return this.container; + } +} +class StrikeOutAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true, + createQuadrilaterals: true + }); + } + render() { + if (!this.data.popupRef && this.hasPopupData) { + this._createPopup(); + } + this.container.classList.add("strikeoutAnnotation"); + return this.container; + } +} +class StampAnnotationElement extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + this.annotationEditorType = AnnotationEditorType.STAMP; + } + render() { + this.container.classList.add("stampAnnotation"); + this.container.setAttribute("role", "img"); + if (!this.data.popupRef && this.hasPopupData) { + this._createPopup(); + } + this._editOnDoubleClick(); + return this.container; + } +} +class FileAttachmentAnnotationElement extends AnnotationElement { + #trigger = null; + constructor(parameters) { + super(parameters, { + isRenderable: true + }); + const { + file + } = this.data; + this.filename = file.filename; + this.content = file.content; + this.linkService.eventBus?.dispatch("fileattachmentannotation", { + source: this, + ...file + }); + } + render() { + this.container.classList.add("fileAttachmentAnnotation"); + const { + container, + data + } = this; + let trigger; + if (data.hasAppearance || data.fillAlpha === 0) { + trigger = document.createElement("div"); + } else { + trigger = document.createElement("img"); + trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(data.name) ? "paperclip" : "pushpin"}.svg`; + if (data.fillAlpha && data.fillAlpha < 1) { + trigger.style = `filter: opacity(${Math.round(data.fillAlpha * 100)}%);`; + } + } + trigger.addEventListener("dblclick", this.#download.bind(this)); + this.#trigger = trigger; + const { + isMac + } = util_FeatureTest.platform; + container.addEventListener("keydown", evt => { + if (evt.key === "Enter" && (isMac ? evt.metaKey : evt.ctrlKey)) { + this.#download(); + } + }); + if (!data.popupRef && this.hasPopupData) { + this._createPopup(); + } else { + trigger.classList.add("popupTriggerArea"); + } + container.append(trigger); + return container; + } + getElementsToTriggerPopup() { + return this.#trigger; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } + #download() { + this.downloadManager?.openOrDownloadData(this.content, this.filename); + } +} +class AnnotationLayer { + #accessibilityManager = null; + #annotationCanvasMap = null; + #editableAnnotations = new Map(); + #structTreeLayer = null; + constructor({ + div, + accessibilityManager, + annotationCanvasMap, + annotationEditorUIManager, + page, + viewport, + structTreeLayer + }) { + this.div = div; + this.#accessibilityManager = accessibilityManager; + this.#annotationCanvasMap = annotationCanvasMap; + this.#structTreeLayer = structTreeLayer || null; + this.page = page; + this.viewport = viewport; + this.zIndex = 0; + this._annotationEditorUIManager = annotationEditorUIManager; + } + hasEditableAnnotations() { + return this.#editableAnnotations.size > 0; + } + async #appendElement(element, id) { + const contentElement = element.firstChild || element; + const annotationId = contentElement.id = `${AnnotationPrefix}${id}`; + const ariaAttributes = await this.#structTreeLayer?.getAriaAttributes(annotationId); + if (ariaAttributes) { + for (const [key, value] of ariaAttributes) { + contentElement.setAttribute(key, value); + } + } + this.div.append(element); + this.#accessibilityManager?.moveElementInDOM(this.div, element, contentElement, false); + } + async render(params) { + const { + annotations + } = params; + const layer = this.div; + setLayerDimensions(layer, this.viewport); + const popupToElements = new Map(); + const elementParams = { + data: null, + layer, + linkService: params.linkService, + downloadManager: params.downloadManager, + imageResourcesPath: params.imageResourcesPath || "", + renderForms: params.renderForms !== false, + svgFactory: new DOMSVGFactory(), + annotationStorage: params.annotationStorage || new AnnotationStorage(), + enableScripting: params.enableScripting === true, + hasJSActions: params.hasJSActions, + fieldObjects: params.fieldObjects, + parent: this, + elements: null + }; + for (const data of annotations) { + if (data.noHTML) { + continue; + } + const isPopupAnnotation = data.annotationType === AnnotationType.POPUP; + if (!isPopupAnnotation) { + const { + width, + height + } = getRectDims(data.rect); + if (width <= 0 || height <= 0) { + continue; + } + } else { + const elements = popupToElements.get(data.id); + if (!elements) { + continue; + } + elementParams.elements = elements; + } + elementParams.data = data; + const element = AnnotationElementFactory.create(elementParams); + if (!element.isRenderable) { + continue; + } + if (!isPopupAnnotation && data.popupRef) { + const elements = popupToElements.get(data.popupRef); + if (!elements) { + popupToElements.set(data.popupRef, [element]); + } else { + elements.push(element); + } + } + const rendered = element.render(); + if (data.hidden) { + rendered.style.visibility = "hidden"; + } + await this.#appendElement(rendered, data.id); + if (element._isEditable) { + this.#editableAnnotations.set(element.data.id, element); + this._annotationEditorUIManager?.renderAnnotationElement(element); + } + } + this.#setAnnotationCanvasMap(); + } + update({ + viewport + }) { + const layer = this.div; + this.viewport = viewport; + setLayerDimensions(layer, { + rotation: viewport.rotation + }); + this.#setAnnotationCanvasMap(); + layer.hidden = false; + } + #setAnnotationCanvasMap() { + if (!this.#annotationCanvasMap) { + return; + } + const layer = this.div; + for (const [id, canvas] of this.#annotationCanvasMap) { + const element = layer.querySelector(`[data-annotation-id="${id}"]`); + if (!element) { + continue; + } + canvas.className = "annotationContent"; + const { + firstChild + } = element; + if (!firstChild) { + element.append(canvas); + } else if (firstChild.nodeName === "CANVAS") { + firstChild.replaceWith(canvas); + } else if (!firstChild.classList.contains("annotationContent")) { + firstChild.before(canvas); + } else { + firstChild.after(canvas); + } + } + this.#annotationCanvasMap.clear(); + } + getEditableAnnotations() { + return Array.from(this.#editableAnnotations.values()); + } + getEditableAnnotation(id) { + return this.#editableAnnotations.get(id); + } +} + +;// ./src/display/editor/freetext.js + + + + +const EOL_PATTERN = /\r\n?|\n/g; +class FreeTextEditor extends AnnotationEditor { + #color; + #content = ""; + #editorDivId = `${this.id}-editor`; + #editModeAC = null; + #fontSize; + static _freeTextDefaultContent = ""; + static _internalPadding = 0; + static _defaultColor = null; + static _defaultFontSize = 10; + static get _keyboardManager() { + const proto = FreeTextEditor.prototype; + const arrowChecker = self => self.isEmpty(); + const small = AnnotationEditorUIManager.TRANSLATE_SMALL; + const big = AnnotationEditorUIManager.TRANSLATE_BIG; + return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+s", "mac+meta+s", "ctrl+p", "mac+meta+p"], proto.commitOrRemove, { + bubbles: true + }], [["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], proto.commitOrRemove], [["ArrowLeft", "mac+ArrowLeft"], proto._translateEmpty, { + args: [-small, 0], + checker: arrowChecker + }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto._translateEmpty, { + args: [-big, 0], + checker: arrowChecker + }], [["ArrowRight", "mac+ArrowRight"], proto._translateEmpty, { + args: [small, 0], + checker: arrowChecker + }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto._translateEmpty, { + args: [big, 0], + checker: arrowChecker + }], [["ArrowUp", "mac+ArrowUp"], proto._translateEmpty, { + args: [0, -small], + checker: arrowChecker + }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto._translateEmpty, { + args: [0, -big], + checker: arrowChecker + }], [["ArrowDown", "mac+ArrowDown"], proto._translateEmpty, { + args: [0, small], + checker: arrowChecker + }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto._translateEmpty, { + args: [0, big], + checker: arrowChecker + }]])); + } + static _type = "freetext"; + static _editorType = AnnotationEditorType.FREETEXT; + constructor(params) { + super({ + ...params, + name: "freeTextEditor" + }); + this.#color = params.color || FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor; + this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize; + } + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager); + const style = getComputedStyle(document.documentElement); + this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding")); + } + static updateDefaultParams(type, value) { + switch (type) { + case AnnotationEditorParamsType.FREETEXT_SIZE: + FreeTextEditor._defaultFontSize = value; + break; + case AnnotationEditorParamsType.FREETEXT_COLOR: + FreeTextEditor._defaultColor = value; + break; + } + } + updateParams(type, value) { + switch (type) { + case AnnotationEditorParamsType.FREETEXT_SIZE: + this.#updateFontSize(value); + break; + case AnnotationEditorParamsType.FREETEXT_COLOR: + this.#updateColor(value); + break; + } + } + static get defaultPropertiesToUpdate() { + return [[AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor]]; + } + get propertiesToUpdate() { + return [[AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, this.#color]]; + } + #updateFontSize(fontSize) { + const setFontsize = size => { + this.editorDiv.style.fontSize = `calc(${size}px * var(--scale-factor))`; + this.translate(0, -(size - this.#fontSize) * this.parentScale); + this.#fontSize = size; + this.#setEditorDimensions(); + }; + const savedFontsize = this.#fontSize; + this.addCommands({ + cmd: setFontsize.bind(this, fontSize), + undo: setFontsize.bind(this, savedFontsize), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type: AnnotationEditorParamsType.FREETEXT_SIZE, + overwriteIfSameType: true, + keepUndo: true + }); + } + #updateColor(color) { + const setColor = col => { + this.#color = this.editorDiv.style.color = col; + }; + const savedColor = this.#color; + this.addCommands({ + cmd: setColor.bind(this, color), + undo: setColor.bind(this, savedColor), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type: AnnotationEditorParamsType.FREETEXT_COLOR, + overwriteIfSameType: true, + keepUndo: true + }); + } + _translateEmpty(x, y) { + this._uiManager.translateSelectedEditors(x, y, true); + } + getInitialTranslation() { + const scale = this.parentScale; + return [-FreeTextEditor._internalPadding * scale, -(FreeTextEditor._internalPadding + this.#fontSize) * scale]; + } + rebuild() { + if (!this.parent) { + return; + } + super.rebuild(); + if (this.div === null) { + return; + } + if (!this.isAttachedToDOM) { + this.parent.add(this); + } + } + enableEditMode() { + if (this.isInEditMode()) { + return; + } + this.parent.setEditingState(false); + this.parent.updateToolbar(AnnotationEditorType.FREETEXT); + super.enableEditMode(); + this.overlayDiv.classList.remove("enabled"); + this.editorDiv.contentEditable = true; + this._isDraggable = false; + this.div.removeAttribute("aria-activedescendant"); + this.#editModeAC = new AbortController(); + const signal = this._uiManager.combinedSignal(this.#editModeAC); + this.editorDiv.addEventListener("keydown", this.editorDivKeydown.bind(this), { + signal + }); + this.editorDiv.addEventListener("focus", this.editorDivFocus.bind(this), { + signal + }); + this.editorDiv.addEventListener("blur", this.editorDivBlur.bind(this), { + signal + }); + this.editorDiv.addEventListener("input", this.editorDivInput.bind(this), { + signal + }); + this.editorDiv.addEventListener("paste", this.editorDivPaste.bind(this), { + signal + }); + } + disableEditMode() { + if (!this.isInEditMode()) { + return; + } + this.parent.setEditingState(true); + super.disableEditMode(); + this.overlayDiv.classList.add("enabled"); + this.editorDiv.contentEditable = false; + this.div.setAttribute("aria-activedescendant", this.#editorDivId); + this._isDraggable = true; + this.#editModeAC?.abort(); + this.#editModeAC = null; + this.div.focus({ + preventScroll: true + }); + this.isEditing = false; + this.parent.div.classList.add("freetextEditing"); + } + focusin(event) { + if (!this._focusEventsAllowed) { + return; + } + super.focusin(event); + if (event.target !== this.editorDiv) { + this.editorDiv.focus(); + } + } + onceAdded() { + if (this.width) { + return; + } + this.enableEditMode(); + this.editorDiv.focus(); + if (this._initialOptions?.isCentered) { + this.center(); + } + this._initialOptions = null; + } + isEmpty() { + return !this.editorDiv || this.editorDiv.innerText.trim() === ""; + } + remove() { + this.isEditing = false; + if (this.parent) { + this.parent.setEditingState(true); + this.parent.div.classList.add("freetextEditing"); + } + super.remove(); + } + #extractText() { + const buffer = []; + this.editorDiv.normalize(); + let prevChild = null; + for (const child of this.editorDiv.childNodes) { + if (prevChild?.nodeType === Node.TEXT_NODE && child.nodeName === "BR") { + continue; + } + buffer.push(FreeTextEditor.#getNodeContent(child)); + prevChild = child; + } + return buffer.join("\n"); + } + #setEditorDimensions() { + const [parentWidth, parentHeight] = this.parentDimensions; + let rect; + if (this.isAttachedToDOM) { + rect = this.div.getBoundingClientRect(); + } else { + const { + currentLayer, + div + } = this; + const savedDisplay = div.style.display; + const savedVisibility = div.classList.contains("hidden"); + div.classList.remove("hidden"); + div.style.display = "hidden"; + currentLayer.div.append(this.div); + rect = div.getBoundingClientRect(); + div.remove(); + div.style.display = savedDisplay; + div.classList.toggle("hidden", savedVisibility); + } + if (this.rotation % 180 === this.parentRotation % 180) { + this.width = rect.width / parentWidth; + this.height = rect.height / parentHeight; + } else { + this.width = rect.height / parentWidth; + this.height = rect.width / parentHeight; + } + this.fixAndSetPosition(); + } + commit() { + if (!this.isInEditMode()) { + return; + } + super.commit(); + this.disableEditMode(); + const savedText = this.#content; + const newText = this.#content = this.#extractText().trimEnd(); + if (savedText === newText) { + return; + } + const setText = text => { + this.#content = text; + if (!text) { + this.remove(); + return; + } + this.#setContent(); + this._uiManager.rebuild(this); + this.#setEditorDimensions(); + }; + this.addCommands({ + cmd: () => { + setText(newText); + }, + undo: () => { + setText(savedText); + }, + mustExec: false + }); + this.#setEditorDimensions(); + } + shouldGetKeyboardEvents() { + return this.isInEditMode(); + } + enterInEditMode() { + this.enableEditMode(); + this.editorDiv.focus(); + } + dblclick(event) { + this.enterInEditMode(); + } + keydown(event) { + if (event.target === this.div && event.key === "Enter") { + this.enterInEditMode(); + event.preventDefault(); + } + } + editorDivKeydown(event) { + FreeTextEditor._keyboardManager.exec(this, event); + } + editorDivFocus(event) { + this.isEditing = true; + } + editorDivBlur(event) { + this.isEditing = false; + } + editorDivInput(event) { + this.parent.div.classList.toggle("freetextEditing", this.isEmpty()); + } + disableEditing() { + this.editorDiv.setAttribute("role", "comment"); + this.editorDiv.removeAttribute("aria-multiline"); + } + enableEditing() { + this.editorDiv.setAttribute("role", "textbox"); + this.editorDiv.setAttribute("aria-multiline", true); + } + render() { + if (this.div) { + return this.div; + } + let baseX, baseY; + if (this.width) { + baseX = this.x; + baseY = this.y; + } + super.render(); + this.editorDiv = document.createElement("div"); + this.editorDiv.className = "internal"; + this.editorDiv.setAttribute("id", this.#editorDivId); + this.editorDiv.setAttribute("data-l10n-id", "pdfjs-free-text2"); + this.editorDiv.setAttribute("data-l10n-attrs", "default-content"); + this.enableEditing(); + this.editorDiv.contentEditable = true; + const { + style + } = this.editorDiv; + style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`; + style.color = this.#color; + this.div.append(this.editorDiv); + this.overlayDiv = document.createElement("div"); + this.overlayDiv.classList.add("overlay", "enabled"); + this.div.append(this.overlayDiv); + bindEvents(this, this.div, ["dblclick", "keydown"]); + if (this.width) { + const [parentWidth, parentHeight] = this.parentDimensions; + if (this.annotationElementId) { + const { + position + } = this._initialData; + let [tx, ty] = this.getInitialTranslation(); + [tx, ty] = this.pageTranslationToScreen(tx, ty); + const [pageWidth, pageHeight] = this.pageDimensions; + const [pageX, pageY] = this.pageTranslation; + let posX, posY; + switch (this.rotation) { + case 0: + posX = baseX + (position[0] - pageX) / pageWidth; + posY = baseY + this.height - (position[1] - pageY) / pageHeight; + break; + case 90: + posX = baseX + (position[0] - pageX) / pageWidth; + posY = baseY - (position[1] - pageY) / pageHeight; + [tx, ty] = [ty, -tx]; + break; + case 180: + posX = baseX - this.width + (position[0] - pageX) / pageWidth; + posY = baseY - (position[1] - pageY) / pageHeight; + [tx, ty] = [-tx, -ty]; + break; + case 270: + posX = baseX + (position[0] - pageX - this.height * pageHeight) / pageWidth; + posY = baseY + (position[1] - pageY - this.width * pageWidth) / pageHeight; + [tx, ty] = [-ty, tx]; + break; + } + this.setAt(posX * parentWidth, posY * parentHeight, tx, ty); + } else { + this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight); + } + this.#setContent(); + this._isDraggable = true; + this.editorDiv.contentEditable = false; + } else { + this._isDraggable = false; + this.editorDiv.contentEditable = true; + } + return this.div; + } + static #getNodeContent(node) { + return (node.nodeType === Node.TEXT_NODE ? node.nodeValue : node.innerText).replaceAll(EOL_PATTERN, ""); + } + editorDivPaste(event) { + const clipboardData = event.clipboardData || window.clipboardData; + const { + types + } = clipboardData; + if (types.length === 1 && types[0] === "text/plain") { + return; + } + event.preventDefault(); + const paste = FreeTextEditor.#deserializeContent(clipboardData.getData("text") || "").replaceAll(EOL_PATTERN, "\n"); + if (!paste) { + return; + } + const selection = window.getSelection(); + if (!selection.rangeCount) { + return; + } + this.editorDiv.normalize(); + selection.deleteFromDocument(); + const range = selection.getRangeAt(0); + if (!paste.includes("\n")) { + range.insertNode(document.createTextNode(paste)); + this.editorDiv.normalize(); + selection.collapseToStart(); + return; + } + const { + startContainer, + startOffset + } = range; + const bufferBefore = []; + const bufferAfter = []; + if (startContainer.nodeType === Node.TEXT_NODE) { + const parent = startContainer.parentElement; + bufferAfter.push(startContainer.nodeValue.slice(startOffset).replaceAll(EOL_PATTERN, "")); + if (parent !== this.editorDiv) { + let buffer = bufferBefore; + for (const child of this.editorDiv.childNodes) { + if (child === parent) { + buffer = bufferAfter; + continue; + } + buffer.push(FreeTextEditor.#getNodeContent(child)); + } + } + bufferBefore.push(startContainer.nodeValue.slice(0, startOffset).replaceAll(EOL_PATTERN, "")); + } else if (startContainer === this.editorDiv) { + let buffer = bufferBefore; + let i = 0; + for (const child of this.editorDiv.childNodes) { + if (i++ === startOffset) { + buffer = bufferAfter; + } + buffer.push(FreeTextEditor.#getNodeContent(child)); + } + } + this.#content = `${bufferBefore.join("\n")}${paste}${bufferAfter.join("\n")}`; + this.#setContent(); + const newRange = new Range(); + let beforeLength = bufferBefore.reduce((acc, line) => acc + line.length, 0); + for (const { + firstChild + } of this.editorDiv.childNodes) { + if (firstChild.nodeType === Node.TEXT_NODE) { + const length = firstChild.nodeValue.length; + if (beforeLength <= length) { + newRange.setStart(firstChild, beforeLength); + newRange.setEnd(firstChild, beforeLength); + break; + } + beforeLength -= length; + } + } + selection.removeAllRanges(); + selection.addRange(newRange); + } + #setContent() { + this.editorDiv.replaceChildren(); + if (!this.#content) { + return; + } + for (const line of this.#content.split("\n")) { + const div = document.createElement("div"); + div.append(line ? document.createTextNode(line) : document.createElement("br")); + this.editorDiv.append(div); + } + } + #serializeContent() { + return this.#content.replaceAll("\xa0", " "); + } + static #deserializeContent(content) { + return content.replaceAll(" ", "\xa0"); + } + get contentDiv() { + return this.editorDiv; + } + static async deserialize(data, parent, uiManager) { + let initialData = null; + if (data instanceof FreeTextAnnotationElement) { + const { + data: { + defaultAppearanceData: { + fontSize, + fontColor + }, + rect, + rotation, + id, + popupRef + }, + textContent, + textPosition, + parent: { + page: { + pageNumber + } + } + } = data; + if (!textContent || textContent.length === 0) { + return null; + } + initialData = data = { + annotationType: AnnotationEditorType.FREETEXT, + color: Array.from(fontColor), + fontSize, + value: textContent.join("\n"), + position: textPosition, + pageIndex: pageNumber - 1, + rect: rect.slice(0), + rotation, + id, + deleted: false, + popupRef + }; + } + const editor = await super.deserialize(data, parent, uiManager); + editor.#fontSize = data.fontSize; + editor.#color = Util.makeHexColor(...data.color); + editor.#content = FreeTextEditor.#deserializeContent(data.value); + editor.annotationElementId = data.id || null; + editor._initialData = initialData; + return editor; + } + serialize(isForCopying = false) { + if (this.isEmpty()) { + return null; + } + if (this.deleted) { + return this.serializeDeleted(); + } + const padding = FreeTextEditor._internalPadding * this.parentScale; + const rect = this.getRect(padding, padding); + const color = AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.#color); + const serialized = { + annotationType: AnnotationEditorType.FREETEXT, + color, + fontSize: this.#fontSize, + value: this.#serializeContent(), + pageIndex: this.pageIndex, + rect, + rotation: this.rotation, + structTreeParentId: this._structTreeParentId + }; + if (isForCopying) { + return serialized; + } + if (this.annotationElementId && !this.#hasElementChanged(serialized)) { + return null; + } + serialized.id = this.annotationElementId; + return serialized; + } + #hasElementChanged(serialized) { + const { + value, + fontSize, + color, + pageIndex + } = this._initialData; + return this._hasBeenMoved || serialized.value !== value || serialized.fontSize !== fontSize || serialized.color.some((c, i) => c !== color[i]) || serialized.pageIndex !== pageIndex; + } + renderAnnotationElement(annotation) { + const content = super.renderAnnotationElement(annotation); + if (this.deleted) { + return content; + } + const { + style + } = content; + style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`; + style.color = this.#color; + content.replaceChildren(); + for (const line of this.#content.split("\n")) { + const div = document.createElement("div"); + div.append(line ? document.createTextNode(line) : document.createElement("br")); + content.append(div); + } + const padding = FreeTextEditor._internalPadding * this.parentScale; + annotation.updateEdited({ + rect: this.getRect(padding, padding), + popupContent: this.#content + }); + return content; + } + resetAnnotationElement(annotation) { + super.resetAnnotationElement(annotation); + annotation.resetEdited(); + } +} + +;// ./src/display/editor/drawers/outline.js + +class Outline { + static PRECISION = 1e-4; + toSVGPath() { + unreachable("Abstract method `toSVGPath` must be implemented."); + } + get box() { + unreachable("Abstract getter `box` must be implemented."); + } + serialize(_bbox, _rotation) { + unreachable("Abstract method `serialize` must be implemented."); + } + static _rescale(src, tx, ty, sx, sy, dest) { + dest ||= new Float32Array(src.length); + for (let i = 0, ii = src.length; i < ii; i += 2) { + dest[i] = tx + src[i] * sx; + dest[i + 1] = ty + src[i + 1] * sy; + } + return dest; + } + static _rescaleAndSwap(src, tx, ty, sx, sy, dest) { + dest ||= new Float32Array(src.length); + for (let i = 0, ii = src.length; i < ii; i += 2) { + dest[i] = tx + src[i + 1] * sx; + dest[i + 1] = ty + src[i] * sy; + } + return dest; + } + static _translate(src, tx, ty, dest) { + dest ||= new Float32Array(src.length); + for (let i = 0, ii = src.length; i < ii; i += 2) { + dest[i] = tx + src[i]; + dest[i + 1] = ty + src[i + 1]; + } + return dest; + } + static svgRound(x) { + return Math.round(x * 10000); + } + static _normalizePoint(x, y, parentWidth, parentHeight, rotation) { + switch (rotation) { + case 90: + return [1 - y / parentWidth, x / parentHeight]; + case 180: + return [1 - x / parentWidth, 1 - y / parentHeight]; + case 270: + return [y / parentWidth, 1 - x / parentHeight]; + default: + return [x / parentWidth, y / parentHeight]; + } + } + static _normalizePagePoint(x, y, rotation) { + switch (rotation) { + case 90: + return [1 - y, x]; + case 180: + return [1 - x, 1 - y]; + case 270: + return [y, 1 - x]; + default: + return [x, y]; + } + } + static createBezierPoints(x1, y1, x2, y2, x3, y3) { + return [(x1 + 5 * x2) / 6, (y1 + 5 * y2) / 6, (5 * x2 + x3) / 6, (5 * y2 + y3) / 6, (x2 + x3) / 2, (y2 + y3) / 2]; + } +} + +;// ./src/display/editor/drawers/freedraw.js + + +class FreeDrawOutliner { + #box; + #bottom = []; + #innerMargin; + #isLTR; + #top = []; + #last = new Float32Array(18); + #lastX; + #lastY; + #min; + #min_dist; + #scaleFactor; + #thickness; + #points = []; + static #MIN_DIST = 8; + static #MIN_DIFF = 2; + static #MIN = FreeDrawOutliner.#MIN_DIST + FreeDrawOutliner.#MIN_DIFF; + constructor({ + x, + y + }, box, scaleFactor, thickness, isLTR, innerMargin = 0) { + this.#box = box; + this.#thickness = thickness * scaleFactor; + this.#isLTR = isLTR; + this.#last.set([NaN, NaN, NaN, NaN, x, y], 6); + this.#innerMargin = innerMargin; + this.#min_dist = FreeDrawOutliner.#MIN_DIST * scaleFactor; + this.#min = FreeDrawOutliner.#MIN * scaleFactor; + this.#scaleFactor = scaleFactor; + this.#points.push(x, y); + } + isEmpty() { + return isNaN(this.#last[8]); + } + #getLastCoords() { + const lastTop = this.#last.subarray(4, 6); + const lastBottom = this.#last.subarray(16, 18); + const [x, y, width, height] = this.#box; + return [(this.#lastX + (lastTop[0] - lastBottom[0]) / 2 - x) / width, (this.#lastY + (lastTop[1] - lastBottom[1]) / 2 - y) / height, (this.#lastX + (lastBottom[0] - lastTop[0]) / 2 - x) / width, (this.#lastY + (lastBottom[1] - lastTop[1]) / 2 - y) / height]; + } + add({ + x, + y + }) { + this.#lastX = x; + this.#lastY = y; + const [layerX, layerY, layerWidth, layerHeight] = this.#box; + let [x1, y1, x2, y2] = this.#last.subarray(8, 12); + const diffX = x - x2; + const diffY = y - y2; + const d = Math.hypot(diffX, diffY); + if (d < this.#min) { + return false; + } + const diffD = d - this.#min_dist; + const K = diffD / d; + const shiftX = K * diffX; + const shiftY = K * diffY; + let x0 = x1; + let y0 = y1; + x1 = x2; + y1 = y2; + x2 += shiftX; + y2 += shiftY; + this.#points?.push(x, y); + const nX = -shiftY / diffD; + const nY = shiftX / diffD; + const thX = nX * this.#thickness; + const thY = nY * this.#thickness; + this.#last.set(this.#last.subarray(2, 8), 0); + this.#last.set([x2 + thX, y2 + thY], 4); + this.#last.set(this.#last.subarray(14, 18), 12); + this.#last.set([x2 - thX, y2 - thY], 16); + if (isNaN(this.#last[6])) { + if (this.#top.length === 0) { + this.#last.set([x1 + thX, y1 + thY], 2); + this.#top.push(NaN, NaN, NaN, NaN, (x1 + thX - layerX) / layerWidth, (y1 + thY - layerY) / layerHeight); + this.#last.set([x1 - thX, y1 - thY], 14); + this.#bottom.push(NaN, NaN, NaN, NaN, (x1 - thX - layerX) / layerWidth, (y1 - thY - layerY) / layerHeight); + } + this.#last.set([x0, y0, x1, y1, x2, y2], 6); + return !this.isEmpty(); + } + this.#last.set([x0, y0, x1, y1, x2, y2], 6); + const angle = Math.abs(Math.atan2(y0 - y1, x0 - x1) - Math.atan2(shiftY, shiftX)); + if (angle < Math.PI / 2) { + [x1, y1, x2, y2] = this.#last.subarray(2, 6); + this.#top.push(NaN, NaN, NaN, NaN, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight); + [x1, y1, x0, y0] = this.#last.subarray(14, 18); + this.#bottom.push(NaN, NaN, NaN, NaN, ((x0 + x1) / 2 - layerX) / layerWidth, ((y0 + y1) / 2 - layerY) / layerHeight); + return true; + } + [x0, y0, x1, y1, x2, y2] = this.#last.subarray(0, 6); + this.#top.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x2) / 6 - layerX) / layerWidth, ((5 * y1 + y2) / 6 - layerY) / layerHeight, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight); + [x2, y2, x1, y1, x0, y0] = this.#last.subarray(12, 18); + this.#bottom.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x2) / 6 - layerX) / layerWidth, ((5 * y1 + y2) / 6 - layerY) / layerHeight, ((x1 + x2) / 2 - layerX) / layerWidth, ((y1 + y2) / 2 - layerY) / layerHeight); + return true; + } + toSVGPath() { + if (this.isEmpty()) { + return ""; + } + const top = this.#top; + const bottom = this.#bottom; + if (isNaN(this.#last[6]) && !this.isEmpty()) { + return this.#toSVGPathTwoPoints(); + } + const buffer = []; + buffer.push(`M${top[4]} ${top[5]}`); + for (let i = 6; i < top.length; i += 6) { + if (isNaN(top[i])) { + buffer.push(`L${top[i + 4]} ${top[i + 5]}`); + } else { + buffer.push(`C${top[i]} ${top[i + 1]} ${top[i + 2]} ${top[i + 3]} ${top[i + 4]} ${top[i + 5]}`); + } + } + this.#toSVGPathEnd(buffer); + for (let i = bottom.length - 6; i >= 6; i -= 6) { + if (isNaN(bottom[i])) { + buffer.push(`L${bottom[i + 4]} ${bottom[i + 5]}`); + } else { + buffer.push(`C${bottom[i]} ${bottom[i + 1]} ${bottom[i + 2]} ${bottom[i + 3]} ${bottom[i + 4]} ${bottom[i + 5]}`); + } + } + this.#toSVGPathStart(buffer); + return buffer.join(" "); + } + #toSVGPathTwoPoints() { + const [x, y, width, height] = this.#box; + const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords(); + return `M${(this.#last[2] - x) / width} ${(this.#last[3] - y) / height} L${(this.#last[4] - x) / width} ${(this.#last[5] - y) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(this.#last[16] - x) / width} ${(this.#last[17] - y) / height} L${(this.#last[14] - x) / width} ${(this.#last[15] - y) / height} Z`; + } + #toSVGPathStart(buffer) { + const bottom = this.#bottom; + buffer.push(`L${bottom[4]} ${bottom[5]} Z`); + } + #toSVGPathEnd(buffer) { + const [x, y, width, height] = this.#box; + const lastTop = this.#last.subarray(4, 6); + const lastBottom = this.#last.subarray(16, 18); + const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords(); + buffer.push(`L${(lastTop[0] - x) / width} ${(lastTop[1] - y) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(lastBottom[0] - x) / width} ${(lastBottom[1] - y) / height}`); + } + newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) { + return new FreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR); + } + getOutlines() { + const top = this.#top; + const bottom = this.#bottom; + const last = this.#last; + const [layerX, layerY, layerWidth, layerHeight] = this.#box; + const points = new Float32Array((this.#points?.length ?? 0) + 2); + for (let i = 0, ii = points.length - 2; i < ii; i += 2) { + points[i] = (this.#points[i] - layerX) / layerWidth; + points[i + 1] = (this.#points[i + 1] - layerY) / layerHeight; + } + points[points.length - 2] = (this.#lastX - layerX) / layerWidth; + points[points.length - 1] = (this.#lastY - layerY) / layerHeight; + if (isNaN(last[6]) && !this.isEmpty()) { + return this.#getOutlineTwoPoints(points); + } + const outline = new Float32Array(this.#top.length + 24 + this.#bottom.length); + let N = top.length; + for (let i = 0; i < N; i += 2) { + if (isNaN(top[i])) { + outline[i] = outline[i + 1] = NaN; + continue; + } + outline[i] = top[i]; + outline[i + 1] = top[i + 1]; + } + N = this.#getOutlineEnd(outline, N); + for (let i = bottom.length - 6; i >= 6; i -= 6) { + for (let j = 0; j < 6; j += 2) { + if (isNaN(bottom[i + j])) { + outline[N] = outline[N + 1] = NaN; + N += 2; + continue; + } + outline[N] = bottom[i + j]; + outline[N + 1] = bottom[i + j + 1]; + N += 2; + } + } + this.#getOutlineStart(outline, N); + return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR); + } + #getOutlineTwoPoints(points) { + const last = this.#last; + const [layerX, layerY, layerWidth, layerHeight] = this.#box; + const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords(); + const outline = new Float32Array(36); + outline.set([NaN, NaN, NaN, NaN, (last[2] - layerX) / layerWidth, (last[3] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[4] - layerX) / layerWidth, (last[5] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (last[16] - layerX) / layerWidth, (last[17] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[14] - layerX) / layerWidth, (last[15] - layerY) / layerHeight], 0); + return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR); + } + #getOutlineStart(outline, pos) { + const bottom = this.#bottom; + outline.set([NaN, NaN, NaN, NaN, bottom[4], bottom[5]], pos); + return pos += 6; + } + #getOutlineEnd(outline, pos) { + const lastTop = this.#last.subarray(4, 6); + const lastBottom = this.#last.subarray(16, 18); + const [layerX, layerY, layerWidth, layerHeight] = this.#box; + const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords(); + outline.set([NaN, NaN, NaN, NaN, (lastTop[0] - layerX) / layerWidth, (lastTop[1] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (lastBottom[0] - layerX) / layerWidth, (lastBottom[1] - layerY) / layerHeight], pos); + return pos += 24; + } +} +class FreeDrawOutline extends Outline { + #box; + #bbox = new Float32Array(4); + #innerMargin; + #isLTR; + #points; + #scaleFactor; + #outline; + constructor(outline, points, box, scaleFactor, innerMargin, isLTR) { + super(); + this.#outline = outline; + this.#points = points; + this.#box = box; + this.#scaleFactor = scaleFactor; + this.#innerMargin = innerMargin; + this.#isLTR = isLTR; + this.lastPoint = [NaN, NaN]; + this.#computeMinMax(isLTR); + const [x, y, width, height] = this.#bbox; + for (let i = 0, ii = outline.length; i < ii; i += 2) { + outline[i] = (outline[i] - x) / width; + outline[i + 1] = (outline[i + 1] - y) / height; + } + for (let i = 0, ii = points.length; i < ii; i += 2) { + points[i] = (points[i] - x) / width; + points[i + 1] = (points[i + 1] - y) / height; + } + } + toSVGPath() { + const buffer = [`M${this.#outline[4]} ${this.#outline[5]}`]; + for (let i = 6, ii = this.#outline.length; i < ii; i += 6) { + if (isNaN(this.#outline[i])) { + buffer.push(`L${this.#outline[i + 4]} ${this.#outline[i + 5]}`); + continue; + } + buffer.push(`C${this.#outline[i]} ${this.#outline[i + 1]} ${this.#outline[i + 2]} ${this.#outline[i + 3]} ${this.#outline[i + 4]} ${this.#outline[i + 5]}`); + } + buffer.push("Z"); + return buffer.join(" "); + } + serialize([blX, blY, trX, trY], rotation) { + const width = trX - blX; + const height = trY - blY; + let outline; + let points; + switch (rotation) { + case 0: + outline = Outline._rescale(this.#outline, blX, trY, width, -height); + points = Outline._rescale(this.#points, blX, trY, width, -height); + break; + case 90: + outline = Outline._rescaleAndSwap(this.#outline, blX, blY, width, height); + points = Outline._rescaleAndSwap(this.#points, blX, blY, width, height); + break; + case 180: + outline = Outline._rescale(this.#outline, trX, blY, -width, height); + points = Outline._rescale(this.#points, trX, blY, -width, height); + break; + case 270: + outline = Outline._rescaleAndSwap(this.#outline, trX, trY, -width, -height); + points = Outline._rescaleAndSwap(this.#points, trX, trY, -width, -height); + break; + } + return { + outline: Array.from(outline), + points: [Array.from(points)] + }; + } + #computeMinMax(isLTR) { + const outline = this.#outline; + let lastX = outline[4]; + let lastY = outline[5]; + let minX = lastX; + let minY = lastY; + let maxX = lastX; + let maxY = lastY; + let lastPointX = lastX; + let lastPointY = lastY; + const ltrCallback = isLTR ? Math.max : Math.min; + for (let i = 6, ii = outline.length; i < ii; i += 6) { + if (isNaN(outline[i])) { + minX = Math.min(minX, outline[i + 4]); + minY = Math.min(minY, outline[i + 5]); + maxX = Math.max(maxX, outline[i + 4]); + maxY = Math.max(maxY, outline[i + 5]); + if (lastPointY < outline[i + 5]) { + lastPointX = outline[i + 4]; + lastPointY = outline[i + 5]; + } else if (lastPointY === outline[i + 5]) { + lastPointX = ltrCallback(lastPointX, outline[i + 4]); + } + } else { + const bbox = Util.bezierBoundingBox(lastX, lastY, ...outline.slice(i, i + 6)); + minX = Math.min(minX, bbox[0]); + minY = Math.min(minY, bbox[1]); + maxX = Math.max(maxX, bbox[2]); + maxY = Math.max(maxY, bbox[3]); + if (lastPointY < bbox[3]) { + lastPointX = bbox[2]; + lastPointY = bbox[3]; + } else if (lastPointY === bbox[3]) { + lastPointX = ltrCallback(lastPointX, bbox[2]); + } + } + lastX = outline[i + 4]; + lastY = outline[i + 5]; + } + const bbox = this.#bbox; + bbox[0] = minX - this.#innerMargin; + bbox[1] = minY - this.#innerMargin; + bbox[2] = maxX - minX + 2 * this.#innerMargin; + bbox[3] = maxY - minY + 2 * this.#innerMargin; + this.lastPoint = [lastPointX, lastPointY]; + } + get box() { + return this.#bbox; + } + newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) { + return new FreeDrawOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin); + } + getNewOutline(thickness, innerMargin) { + const [x, y, width, height] = this.#bbox; + const [layerX, layerY, layerWidth, layerHeight] = this.#box; + const sx = width * layerWidth; + const sy = height * layerHeight; + const tx = x * layerWidth + layerX; + const ty = y * layerHeight + layerY; + const outliner = this.newOutliner({ + x: this.#points[0] * sx + tx, + y: this.#points[1] * sy + ty + }, this.#box, this.#scaleFactor, thickness, this.#isLTR, innerMargin ?? this.#innerMargin); + for (let i = 2; i < this.#points.length; i += 2) { + outliner.add({ + x: this.#points[i] * sx + tx, + y: this.#points[i + 1] * sy + ty + }); + } + return outliner.getOutlines(); + } +} + +;// ./src/display/editor/drawers/highlight.js + + +class HighlightOutliner { + #box; + #lastPoint; + #verticalEdges = []; + #intervals = []; + constructor(boxes, borderWidth = 0, innerMargin = 0, isLTR = true) { + let minX = Infinity; + let maxX = -Infinity; + let minY = Infinity; + let maxY = -Infinity; + const NUMBER_OF_DIGITS = 4; + const EPSILON = 10 ** -NUMBER_OF_DIGITS; + for (const { + x, + y, + width, + height + } of boxes) { + const x1 = Math.floor((x - borderWidth) / EPSILON) * EPSILON; + const x2 = Math.ceil((x + width + borderWidth) / EPSILON) * EPSILON; + const y1 = Math.floor((y - borderWidth) / EPSILON) * EPSILON; + const y2 = Math.ceil((y + height + borderWidth) / EPSILON) * EPSILON; + const left = [x1, y1, y2, true]; + const right = [x2, y1, y2, false]; + this.#verticalEdges.push(left, right); + minX = Math.min(minX, x1); + maxX = Math.max(maxX, x2); + minY = Math.min(minY, y1); + maxY = Math.max(maxY, y2); + } + const bboxWidth = maxX - minX + 2 * innerMargin; + const bboxHeight = maxY - minY + 2 * innerMargin; + const shiftedMinX = minX - innerMargin; + const shiftedMinY = minY - innerMargin; + const lastEdge = this.#verticalEdges.at(isLTR ? -1 : -2); + const lastPoint = [lastEdge[0], lastEdge[2]]; + for (const edge of this.#verticalEdges) { + const [x, y1, y2] = edge; + edge[0] = (x - shiftedMinX) / bboxWidth; + edge[1] = (y1 - shiftedMinY) / bboxHeight; + edge[2] = (y2 - shiftedMinY) / bboxHeight; + } + this.#box = new Float32Array([shiftedMinX, shiftedMinY, bboxWidth, bboxHeight]); + this.#lastPoint = lastPoint; + } + getOutlines() { + this.#verticalEdges.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]); + const outlineVerticalEdges = []; + for (const edge of this.#verticalEdges) { + if (edge[3]) { + outlineVerticalEdges.push(...this.#breakEdge(edge)); + this.#insert(edge); + } else { + this.#remove(edge); + outlineVerticalEdges.push(...this.#breakEdge(edge)); + } + } + return this.#getOutlines(outlineVerticalEdges); + } + #getOutlines(outlineVerticalEdges) { + const edges = []; + const allEdges = new Set(); + for (const edge of outlineVerticalEdges) { + const [x, y1, y2] = edge; + edges.push([x, y1, edge], [x, y2, edge]); + } + edges.sort((a, b) => a[1] - b[1] || a[0] - b[0]); + for (let i = 0, ii = edges.length; i < ii; i += 2) { + const edge1 = edges[i][2]; + const edge2 = edges[i + 1][2]; + edge1.push(edge2); + edge2.push(edge1); + allEdges.add(edge1); + allEdges.add(edge2); + } + const outlines = []; + let outline; + while (allEdges.size > 0) { + const edge = allEdges.values().next().value; + let [x, y1, y2, edge1, edge2] = edge; + allEdges.delete(edge); + let lastPointX = x; + let lastPointY = y1; + outline = [x, y2]; + outlines.push(outline); + while (true) { + let e; + if (allEdges.has(edge1)) { + e = edge1; + } else if (allEdges.has(edge2)) { + e = edge2; + } else { + break; + } + allEdges.delete(e); + [x, y1, y2, edge1, edge2] = e; + if (lastPointX !== x) { + outline.push(lastPointX, lastPointY, x, lastPointY === y1 ? y1 : y2); + lastPointX = x; + } + lastPointY = lastPointY === y1 ? y2 : y1; + } + outline.push(lastPointX, lastPointY); + } + return new HighlightOutline(outlines, this.#box, this.#lastPoint); + } + #binarySearch(y) { + const array = this.#intervals; + let start = 0; + let end = array.length - 1; + while (start <= end) { + const middle = start + end >> 1; + const y1 = array[middle][0]; + if (y1 === y) { + return middle; + } + if (y1 < y) { + start = middle + 1; + } else { + end = middle - 1; + } + } + return end + 1; + } + #insert([, y1, y2]) { + const index = this.#binarySearch(y1); + this.#intervals.splice(index, 0, [y1, y2]); + } + #remove([, y1, y2]) { + const index = this.#binarySearch(y1); + for (let i = index; i < this.#intervals.length; i++) { + const [start, end] = this.#intervals[i]; + if (start !== y1) { + break; + } + if (start === y1 && end === y2) { + this.#intervals.splice(i, 1); + return; + } + } + for (let i = index - 1; i >= 0; i--) { + const [start, end] = this.#intervals[i]; + if (start !== y1) { + break; + } + if (start === y1 && end === y2) { + this.#intervals.splice(i, 1); + return; + } + } + } + #breakEdge(edge) { + const [x, y1, y2] = edge; + const results = [[x, y1, y2]]; + const index = this.#binarySearch(y2); + for (let i = 0; i < index; i++) { + const [start, end] = this.#intervals[i]; + for (let j = 0, jj = results.length; j < jj; j++) { + const [, y3, y4] = results[j]; + if (end <= y3 || y4 <= start) { + continue; + } + if (y3 >= start) { + if (y4 > end) { + results[j][1] = end; + } else { + if (jj === 1) { + return []; + } + results.splice(j, 1); + j--; + jj--; + } + continue; + } + results[j][2] = start; + if (y4 > end) { + results.push([x, end, y4]); + } + } + } + return results; + } +} +class HighlightOutline extends Outline { + #box; + #outlines; + constructor(outlines, box, lastPoint) { + super(); + this.#outlines = outlines; + this.#box = box; + this.lastPoint = lastPoint; + } + toSVGPath() { + const buffer = []; + for (const polygon of this.#outlines) { + let [prevX, prevY] = polygon; + buffer.push(`M${prevX} ${prevY}`); + for (let i = 2; i < polygon.length; i += 2) { + const x = polygon[i]; + const y = polygon[i + 1]; + if (x === prevX) { + buffer.push(`V${y}`); + prevY = y; + } else if (y === prevY) { + buffer.push(`H${x}`); + prevX = x; + } + } + buffer.push("Z"); + } + return buffer.join(" "); + } + serialize([blX, blY, trX, trY], _rotation) { + const outlines = []; + const width = trX - blX; + const height = trY - blY; + for (const outline of this.#outlines) { + const points = new Array(outline.length); + for (let i = 0; i < outline.length; i += 2) { + points[i] = blX + outline[i] * width; + points[i + 1] = trY - outline[i + 1] * height; + } + outlines.push(points); + } + return outlines; + } + get box() { + return this.#box; + } + get classNamesForOutlining() { + return ["highlightOutline"]; + } +} +class FreeHighlightOutliner extends FreeDrawOutliner { + newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) { + return new FreeHighlightOutline(outline, points, box, scaleFactor, innerMargin, isLTR); + } +} +class FreeHighlightOutline extends FreeDrawOutline { + newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) { + return new FreeHighlightOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin); + } +} + +;// ./src/display/editor/color_picker.js + + + +class ColorPicker { + #button = null; + #buttonSwatch = null; + #defaultColor; + #dropdown = null; + #dropdownWasFromKeyboard = false; + #isMainColorPicker = false; + #editor = null; + #eventBus; + #openDropdownAC = null; + #uiManager = null; + #type; + static #l10nColor = null; + static get _keyboardManager() { + return shadow(this, "_keyboardManager", new KeyboardManager([[["Escape", "mac+Escape"], ColorPicker.prototype._hideDropdownFromKeyboard], [[" ", "mac+ "], ColorPicker.prototype._colorSelectFromKeyboard], [["ArrowDown", "ArrowRight", "mac+ArrowDown", "mac+ArrowRight"], ColorPicker.prototype._moveToNext], [["ArrowUp", "ArrowLeft", "mac+ArrowUp", "mac+ArrowLeft"], ColorPicker.prototype._moveToPrevious], [["Home", "mac+Home"], ColorPicker.prototype._moveToBeginning], [["End", "mac+End"], ColorPicker.prototype._moveToEnd]])); + } + constructor({ + editor = null, + uiManager = null + }) { + if (editor) { + this.#isMainColorPicker = false; + this.#type = AnnotationEditorParamsType.HIGHLIGHT_COLOR; + this.#editor = editor; + } else { + this.#isMainColorPicker = true; + this.#type = AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR; + } + this.#uiManager = editor?._uiManager || uiManager; + this.#eventBus = this.#uiManager._eventBus; + this.#defaultColor = editor?.color || this.#uiManager?.highlightColors.values().next().value || "#FFFF98"; + ColorPicker.#l10nColor ||= Object.freeze({ + blue: "pdfjs-editor-colorpicker-blue", + green: "pdfjs-editor-colorpicker-green", + pink: "pdfjs-editor-colorpicker-pink", + red: "pdfjs-editor-colorpicker-red", + yellow: "pdfjs-editor-colorpicker-yellow" + }); + } + renderButton() { + const button = this.#button = document.createElement("button"); + button.className = "colorPicker"; + button.tabIndex = "0"; + button.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-button"); + button.setAttribute("aria-haspopup", true); + const signal = this.#uiManager._signal; + button.addEventListener("click", this.#openDropdown.bind(this), { + signal + }); + button.addEventListener("keydown", this.#keyDown.bind(this), { + signal + }); + const swatch = this.#buttonSwatch = document.createElement("span"); + swatch.className = "swatch"; + swatch.setAttribute("aria-hidden", true); + swatch.style.backgroundColor = this.#defaultColor; + button.append(swatch); + return button; + } + renderMainDropdown() { + const dropdown = this.#dropdown = this.#getDropdownRoot(); + dropdown.setAttribute("aria-orientation", "horizontal"); + dropdown.setAttribute("aria-labelledby", "highlightColorPickerLabel"); + return dropdown; + } + #getDropdownRoot() { + const div = document.createElement("div"); + const signal = this.#uiManager._signal; + div.addEventListener("contextmenu", noContextMenu, { + signal + }); + div.className = "dropdown"; + div.role = "listbox"; + div.setAttribute("aria-multiselectable", false); + div.setAttribute("aria-orientation", "vertical"); + div.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-dropdown"); + for (const [name, color] of this.#uiManager.highlightColors) { + const button = document.createElement("button"); + button.tabIndex = "0"; + button.role = "option"; + button.setAttribute("data-color", color); + button.title = name; + button.setAttribute("data-l10n-id", ColorPicker.#l10nColor[name]); + const swatch = document.createElement("span"); + button.append(swatch); + swatch.className = "swatch"; + swatch.style.backgroundColor = color; + button.setAttribute("aria-selected", color === this.#defaultColor); + button.addEventListener("click", this.#colorSelect.bind(this, color), { + signal + }); + div.append(button); + } + div.addEventListener("keydown", this.#keyDown.bind(this), { + signal + }); + return div; + } + #colorSelect(color, event) { + event.stopPropagation(); + this.#eventBus.dispatch("switchannotationeditorparams", { + source: this, + type: this.#type, + value: color + }); + } + _colorSelectFromKeyboard(event) { + if (event.target === this.#button) { + this.#openDropdown(event); + return; + } + const color = event.target.getAttribute("data-color"); + if (!color) { + return; + } + this.#colorSelect(color, event); + } + _moveToNext(event) { + if (!this.#isDropdownVisible) { + this.#openDropdown(event); + return; + } + if (event.target === this.#button) { + this.#dropdown.firstChild?.focus(); + return; + } + event.target.nextSibling?.focus(); + } + _moveToPrevious(event) { + if (event.target === this.#dropdown?.firstChild || event.target === this.#button) { + if (this.#isDropdownVisible) { + this._hideDropdownFromKeyboard(); + } + return; + } + if (!this.#isDropdownVisible) { + this.#openDropdown(event); + } + event.target.previousSibling?.focus(); + } + _moveToBeginning(event) { + if (!this.#isDropdownVisible) { + this.#openDropdown(event); + return; + } + this.#dropdown.firstChild?.focus(); + } + _moveToEnd(event) { + if (!this.#isDropdownVisible) { + this.#openDropdown(event); + return; + } + this.#dropdown.lastChild?.focus(); + } + #keyDown(event) { + ColorPicker._keyboardManager.exec(this, event); + } + #openDropdown(event) { + if (this.#isDropdownVisible) { + this.hideDropdown(); + return; + } + this.#dropdownWasFromKeyboard = event.detail === 0; + if (!this.#openDropdownAC) { + this.#openDropdownAC = new AbortController(); + window.addEventListener("pointerdown", this.#pointerDown.bind(this), { + signal: this.#uiManager.combinedSignal(this.#openDropdownAC) + }); + } + if (this.#dropdown) { + this.#dropdown.classList.remove("hidden"); + return; + } + const root = this.#dropdown = this.#getDropdownRoot(); + this.#button.append(root); + } + #pointerDown(event) { + if (this.#dropdown?.contains(event.target)) { + return; + } + this.hideDropdown(); + } + hideDropdown() { + this.#dropdown?.classList.add("hidden"); + this.#openDropdownAC?.abort(); + this.#openDropdownAC = null; + } + get #isDropdownVisible() { + return this.#dropdown && !this.#dropdown.classList.contains("hidden"); + } + _hideDropdownFromKeyboard() { + if (this.#isMainColorPicker) { + return; + } + if (!this.#isDropdownVisible) { + this.#editor?.unselect(); + return; + } + this.hideDropdown(); + this.#button.focus({ + preventScroll: true, + focusVisible: this.#dropdownWasFromKeyboard + }); + } + updateColor(color) { + if (this.#buttonSwatch) { + this.#buttonSwatch.style.backgroundColor = color; + } + if (!this.#dropdown) { + return; + } + const i = this.#uiManager.highlightColors.values(); + for (const child of this.#dropdown.children) { + child.setAttribute("aria-selected", i.next().value === color); + } + } + destroy() { + this.#button?.remove(); + this.#button = null; + this.#buttonSwatch = null; + this.#dropdown?.remove(); + this.#dropdown = null; + } +} + +;// ./src/display/editor/highlight.js + + + + + + + +class HighlightEditor extends AnnotationEditor { + #anchorNode = null; + #anchorOffset = 0; + #boxes; + #clipPathId = null; + #colorPicker = null; + #focusOutlines = null; + #focusNode = null; + #focusOffset = 0; + #highlightDiv = null; + #highlightOutlines = null; + #id = null; + #isFreeHighlight = false; + #lastPoint = null; + #opacity; + #outlineId = null; + #text = ""; + #thickness; + #methodOfCreation = ""; + static _defaultColor = null; + static _defaultOpacity = 1; + static _defaultThickness = 12; + static _type = "highlight"; + static _editorType = AnnotationEditorType.HIGHLIGHT; + static _freeHighlightId = -1; + static _freeHighlight = null; + static _freeHighlightClipId = ""; + static get _keyboardManager() { + const proto = HighlightEditor.prototype; + return shadow(this, "_keyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], proto._moveCaret, { + args: [0] + }], [["ArrowRight", "mac+ArrowRight"], proto._moveCaret, { + args: [1] + }], [["ArrowUp", "mac+ArrowUp"], proto._moveCaret, { + args: [2] + }], [["ArrowDown", "mac+ArrowDown"], proto._moveCaret, { + args: [3] + }]])); + } + constructor(params) { + super({ + ...params, + name: "highlightEditor" + }); + this.color = params.color || HighlightEditor._defaultColor; + this.#thickness = params.thickness || HighlightEditor._defaultThickness; + this.#opacity = params.opacity || HighlightEditor._defaultOpacity; + this.#boxes = params.boxes || null; + this.#methodOfCreation = params.methodOfCreation || ""; + this.#text = params.text || ""; + this._isDraggable = false; + if (params.highlightId > -1) { + this.#isFreeHighlight = true; + this.#createFreeOutlines(params); + this.#addToDrawLayer(); + } else if (this.#boxes) { + this.#anchorNode = params.anchorNode; + this.#anchorOffset = params.anchorOffset; + this.#focusNode = params.focusNode; + this.#focusOffset = params.focusOffset; + this.#createOutlines(); + this.#addToDrawLayer(); + this.rotate(this.rotation); + } + } + get telemetryInitialData() { + return { + action: "added", + type: this.#isFreeHighlight ? "free_highlight" : "highlight", + color: this._uiManager.highlightColorNames.get(this.color), + thickness: this.#thickness, + methodOfCreation: this.#methodOfCreation + }; + } + get telemetryFinalData() { + return { + type: "highlight", + color: this._uiManager.highlightColorNames.get(this.color) + }; + } + static computeTelemetryFinalData(data) { + return { + numberOfColors: data.get("color").size + }; + } + #createOutlines() { + const outliner = new HighlightOutliner(this.#boxes, 0.001); + this.#highlightOutlines = outliner.getOutlines(); + [this.x, this.y, this.width, this.height] = this.#highlightOutlines.box; + const outlinerForOutline = new HighlightOutliner(this.#boxes, 0.0025, 0.001, this._uiManager.direction === "ltr"); + this.#focusOutlines = outlinerForOutline.getOutlines(); + const { + lastPoint + } = this.#focusOutlines; + this.#lastPoint = [(lastPoint[0] - this.x) / this.width, (lastPoint[1] - this.y) / this.height]; + } + #createFreeOutlines({ + highlightOutlines, + highlightId, + clipPathId + }) { + this.#highlightOutlines = highlightOutlines; + const extraThickness = 1.5; + this.#focusOutlines = highlightOutlines.getNewOutline(this.#thickness / 2 + extraThickness, 0.0025); + if (highlightId >= 0) { + this.#id = highlightId; + this.#clipPathId = clipPathId; + this.parent.drawLayer.finalizeDraw(highlightId, { + bbox: highlightOutlines.box, + path: { + d: highlightOutlines.toSVGPath() + } + }); + this.#outlineId = this.parent.drawLayer.drawOutline({ + rootClass: { + highlightOutline: true, + free: true + }, + bbox: this.#focusOutlines.box, + path: { + d: this.#focusOutlines.toSVGPath() + } + }, true); + } else if (this.parent) { + const angle = this.parent.viewport.rotation; + this.parent.drawLayer.updateProperties(this.#id, { + bbox: HighlightEditor.#rotateBbox(this.#highlightOutlines.box, (angle - this.rotation + 360) % 360), + path: { + d: highlightOutlines.toSVGPath() + } + }); + this.parent.drawLayer.updateProperties(this.#outlineId, { + bbox: HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle), + path: { + d: this.#focusOutlines.toSVGPath() + } + }); + } + const [x, y, width, height] = highlightOutlines.box; + switch (this.rotation) { + case 0: + this.x = x; + this.y = y; + this.width = width; + this.height = height; + break; + case 90: + { + const [pageWidth, pageHeight] = this.parentDimensions; + this.x = y; + this.y = 1 - x; + this.width = width * pageHeight / pageWidth; + this.height = height * pageWidth / pageHeight; + break; + } + case 180: + this.x = 1 - x; + this.y = 1 - y; + this.width = width; + this.height = height; + break; + case 270: + { + const [pageWidth, pageHeight] = this.parentDimensions; + this.x = 1 - y; + this.y = x; + this.width = width * pageHeight / pageWidth; + this.height = height * pageWidth / pageHeight; + break; + } + } + const { + lastPoint + } = this.#focusOutlines; + this.#lastPoint = [(lastPoint[0] - x) / width, (lastPoint[1] - y) / height]; + } + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager); + HighlightEditor._defaultColor ||= uiManager.highlightColors?.values().next().value || "#fff066"; + } + static updateDefaultParams(type, value) { + switch (type) { + case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR: + HighlightEditor._defaultColor = value; + break; + case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS: + HighlightEditor._defaultThickness = value; + break; + } + } + translateInPage(x, y) {} + get toolbarPosition() { + return this.#lastPoint; + } + updateParams(type, value) { + switch (type) { + case AnnotationEditorParamsType.HIGHLIGHT_COLOR: + this.#updateColor(value); + break; + case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS: + this.#updateThickness(value); + break; + } + } + static get defaultPropertiesToUpdate() { + return [[AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR, HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, HighlightEditor._defaultThickness]]; + } + get propertiesToUpdate() { + return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, this.color || HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, this.#thickness || HighlightEditor._defaultThickness], [AnnotationEditorParamsType.HIGHLIGHT_FREE, this.#isFreeHighlight]]; + } + #updateColor(color) { + const setColorAndOpacity = (col, opa) => { + this.color = col; + this.#opacity = opa; + this.parent?.drawLayer.updateProperties(this.#id, { + root: { + fill: col, + "fill-opacity": opa + } + }); + this.#colorPicker?.updateColor(col); + }; + const savedColor = this.color; + const savedOpacity = this.#opacity; + this.addCommands({ + cmd: setColorAndOpacity.bind(this, color, HighlightEditor._defaultOpacity), + undo: setColorAndOpacity.bind(this, savedColor, savedOpacity), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type: AnnotationEditorParamsType.HIGHLIGHT_COLOR, + overwriteIfSameType: true, + keepUndo: true + }); + this._reportTelemetry({ + action: "color_changed", + color: this._uiManager.highlightColorNames.get(color) + }, true); + } + #updateThickness(thickness) { + const savedThickness = this.#thickness; + const setThickness = th => { + this.#thickness = th; + this.#changeThickness(th); + }; + this.addCommands({ + cmd: setThickness.bind(this, thickness), + undo: setThickness.bind(this, savedThickness), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type: AnnotationEditorParamsType.INK_THICKNESS, + overwriteIfSameType: true, + keepUndo: true + }); + this._reportTelemetry({ + action: "thickness_changed", + thickness + }, true); + } + async addEditToolbar() { + const toolbar = await super.addEditToolbar(); + if (!toolbar) { + return null; + } + if (this._uiManager.highlightColors) { + this.#colorPicker = new ColorPicker({ + editor: this + }); + toolbar.addColorPicker(this.#colorPicker); + } + return toolbar; + } + disableEditing() { + super.disableEditing(); + this.div.classList.toggle("disabled", true); + } + enableEditing() { + super.enableEditing(); + this.div.classList.toggle("disabled", false); + } + fixAndSetPosition() { + return super.fixAndSetPosition(this.#getRotation()); + } + getBaseTranslation() { + return [0, 0]; + } + getRect(tx, ty) { + return super.getRect(tx, ty, this.#getRotation()); + } + onceAdded() { + if (!this.annotationElementId) { + this.parent.addUndoableEditor(this); + } + this.div.focus(); + } + remove() { + this.#cleanDrawLayer(); + this._reportTelemetry({ + action: "deleted" + }); + super.remove(); + } + rebuild() { + if (!this.parent) { + return; + } + super.rebuild(); + if (this.div === null) { + return; + } + this.#addToDrawLayer(); + if (!this.isAttachedToDOM) { + this.parent.add(this); + } + } + setParent(parent) { + let mustBeSelected = false; + if (this.parent && !parent) { + this.#cleanDrawLayer(); + } else if (parent) { + this.#addToDrawLayer(parent); + mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor"); + } + super.setParent(parent); + this.show(this._isVisible); + if (mustBeSelected) { + this.select(); + } + } + #changeThickness(thickness) { + if (!this.#isFreeHighlight) { + return; + } + this.#createFreeOutlines({ + highlightOutlines: this.#highlightOutlines.getNewOutline(thickness / 2) + }); + this.fixAndSetPosition(); + const [parentWidth, parentHeight] = this.parentDimensions; + this.setDims(this.width * parentWidth, this.height * parentHeight); + } + #cleanDrawLayer() { + if (this.#id === null || !this.parent) { + return; + } + this.parent.drawLayer.remove(this.#id); + this.#id = null; + this.parent.drawLayer.remove(this.#outlineId); + this.#outlineId = null; + } + #addToDrawLayer(parent = this.parent) { + if (this.#id !== null) { + return; + } + ({ + id: this.#id, + clipPathId: this.#clipPathId + } = parent.drawLayer.draw({ + bbox: this.#highlightOutlines.box, + root: { + viewBox: "0 0 1 1", + fill: this.color, + "fill-opacity": this.#opacity + }, + rootClass: { + highlight: true, + free: this.#isFreeHighlight + }, + path: { + d: this.#highlightOutlines.toSVGPath() + } + }, false, true)); + this.#outlineId = parent.drawLayer.drawOutline({ + rootClass: { + highlightOutline: true, + free: this.#isFreeHighlight + }, + bbox: this.#focusOutlines.box, + path: { + d: this.#focusOutlines.toSVGPath() + } + }, this.#isFreeHighlight); + if (this.#highlightDiv) { + this.#highlightDiv.style.clipPath = this.#clipPathId; + } + } + static #rotateBbox([x, y, width, height], angle) { + switch (angle) { + case 90: + return [1 - y - height, x, height, width]; + case 180: + return [1 - x - width, 1 - y - height, width, height]; + case 270: + return [y, 1 - x - width, height, width]; + } + return [x, y, width, height]; + } + rotate(angle) { + const { + drawLayer + } = this.parent; + let box; + if (this.#isFreeHighlight) { + angle = (angle - this.rotation + 360) % 360; + box = HighlightEditor.#rotateBbox(this.#highlightOutlines.box, angle); + } else { + box = HighlightEditor.#rotateBbox([this.x, this.y, this.width, this.height], angle); + } + drawLayer.updateProperties(this.#id, { + bbox: box, + root: { + "data-main-rotation": angle + } + }); + drawLayer.updateProperties(this.#outlineId, { + bbox: HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle), + root: { + "data-main-rotation": angle + } + }); + } + render() { + if (this.div) { + return this.div; + } + const div = super.render(); + if (this.#text) { + div.setAttribute("aria-label", this.#text); + div.setAttribute("role", "mark"); + } + if (this.#isFreeHighlight) { + div.classList.add("free"); + } else { + this.div.addEventListener("keydown", this.#keydown.bind(this), { + signal: this._uiManager._signal + }); + } + const highlightDiv = this.#highlightDiv = document.createElement("div"); + div.append(highlightDiv); + highlightDiv.setAttribute("aria-hidden", "true"); + highlightDiv.className = "internal"; + highlightDiv.style.clipPath = this.#clipPathId; + const [parentWidth, parentHeight] = this.parentDimensions; + this.setDims(this.width * parentWidth, this.height * parentHeight); + bindEvents(this, this.#highlightDiv, ["pointerover", "pointerleave"]); + this.enableEditing(); + return div; + } + pointerover() { + if (!this.isSelected) { + this.parent?.drawLayer.updateProperties(this.#outlineId, { + rootClass: { + hovered: true + } + }); + } + } + pointerleave() { + if (!this.isSelected) { + this.parent?.drawLayer.updateProperties(this.#outlineId, { + rootClass: { + hovered: false + } + }); + } + } + #keydown(event) { + HighlightEditor._keyboardManager.exec(this, event); + } + _moveCaret(direction) { + this.parent.unselect(this); + switch (direction) { + case 0: + case 2: + this.#setCaret(true); + break; + case 1: + case 3: + this.#setCaret(false); + break; + } + } + #setCaret(start) { + if (!this.#anchorNode) { + return; + } + const selection = window.getSelection(); + if (start) { + selection.setPosition(this.#anchorNode, this.#anchorOffset); + } else { + selection.setPosition(this.#focusNode, this.#focusOffset); + } + } + select() { + super.select(); + if (!this.#outlineId) { + return; + } + this.parent?.drawLayer.updateProperties(this.#outlineId, { + rootClass: { + hovered: false, + selected: true + } + }); + } + unselect() { + super.unselect(); + if (!this.#outlineId) { + return; + } + this.parent?.drawLayer.updateProperties(this.#outlineId, { + rootClass: { + selected: false + } + }); + if (!this.#isFreeHighlight) { + this.#setCaret(false); + } + } + get _mustFixPosition() { + return !this.#isFreeHighlight; + } + show(visible = this._isVisible) { + super.show(visible); + if (this.parent) { + this.parent.drawLayer.updateProperties(this.#id, { + rootClass: { + hidden: !visible + } + }); + this.parent.drawLayer.updateProperties(this.#outlineId, { + rootClass: { + hidden: !visible + } + }); + } + } + #getRotation() { + return this.#isFreeHighlight ? this.rotation : 0; + } + #serializeBoxes() { + if (this.#isFreeHighlight) { + return null; + } + const [pageWidth, pageHeight] = this.pageDimensions; + const [pageX, pageY] = this.pageTranslation; + const boxes = this.#boxes; + const quadPoints = new Float32Array(boxes.length * 8); + let i = 0; + for (const { + x, + y, + width, + height + } of boxes) { + const sx = x * pageWidth + pageX; + const sy = (1 - y) * pageHeight + pageY; + quadPoints[i] = quadPoints[i + 4] = sx; + quadPoints[i + 1] = quadPoints[i + 3] = sy; + quadPoints[i + 2] = quadPoints[i + 6] = sx + width * pageWidth; + quadPoints[i + 5] = quadPoints[i + 7] = sy - height * pageHeight; + i += 8; + } + return quadPoints; + } + #serializeOutlines(rect) { + return this.#highlightOutlines.serialize(rect, this.#getRotation()); + } + static startHighlighting(parent, isLTR, { + target: textLayer, + x, + y + }) { + const { + x: layerX, + y: layerY, + width: parentWidth, + height: parentHeight + } = textLayer.getBoundingClientRect(); + const ac = new AbortController(); + const signal = parent.combinedSignal(ac); + const pointerUpCallback = e => { + ac.abort(); + this.#endHighlight(parent, e); + }; + window.addEventListener("blur", pointerUpCallback, { + signal + }); + window.addEventListener("pointerup", pointerUpCallback, { + signal + }); + window.addEventListener("pointerdown", stopEvent, { + capture: true, + passive: false, + signal + }); + window.addEventListener("contextmenu", noContextMenu, { + signal + }); + textLayer.addEventListener("pointermove", this.#highlightMove.bind(this, parent), { + signal + }); + this._freeHighlight = new FreeHighlightOutliner({ + x, + y + }, [layerX, layerY, parentWidth, parentHeight], parent.scale, this._defaultThickness / 2, isLTR, 0.001); + ({ + id: this._freeHighlightId, + clipPathId: this._freeHighlightClipId + } = parent.drawLayer.draw({ + bbox: [0, 0, 1, 1], + root: { + viewBox: "0 0 1 1", + fill: this._defaultColor, + "fill-opacity": this._defaultOpacity + }, + rootClass: { + highlight: true, + free: true + }, + path: { + d: this._freeHighlight.toSVGPath() + } + }, true, true)); + } + static #highlightMove(parent, event) { + if (this._freeHighlight.add(event)) { + parent.drawLayer.updateProperties(this._freeHighlightId, { + path: { + d: this._freeHighlight.toSVGPath() + } + }); + } + } + static #endHighlight(parent, event) { + if (!this._freeHighlight.isEmpty()) { + parent.createAndAddNewEditor(event, false, { + highlightId: this._freeHighlightId, + highlightOutlines: this._freeHighlight.getOutlines(), + clipPathId: this._freeHighlightClipId, + methodOfCreation: "main_toolbar" + }); + } else { + parent.drawLayer.remove(this._freeHighlightId); + } + this._freeHighlightId = -1; + this._freeHighlight = null; + this._freeHighlightClipId = ""; + } + static async deserialize(data, parent, uiManager) { + let initialData = null; + if (data instanceof HighlightAnnotationElement) { + const { + data: { + quadPoints, + rect, + rotation, + id, + color, + opacity, + popupRef + }, + parent: { + page: { + pageNumber + } + } + } = data; + initialData = data = { + annotationType: AnnotationEditorType.HIGHLIGHT, + color: Array.from(color), + opacity, + quadPoints, + boxes: null, + pageIndex: pageNumber - 1, + rect: rect.slice(0), + rotation, + id, + deleted: false, + popupRef + }; + } else if (data instanceof InkAnnotationElement) { + const { + data: { + inkLists, + rect, + rotation, + id, + color, + borderStyle: { + rawWidth: thickness + }, + popupRef + }, + parent: { + page: { + pageNumber + } + } + } = data; + initialData = data = { + annotationType: AnnotationEditorType.HIGHLIGHT, + color: Array.from(color), + thickness, + inkLists, + boxes: null, + pageIndex: pageNumber - 1, + rect: rect.slice(0), + rotation, + id, + deleted: false, + popupRef + }; + } + const { + color, + quadPoints, + inkLists, + opacity + } = data; + const editor = await super.deserialize(data, parent, uiManager); + editor.color = Util.makeHexColor(...color); + editor.#opacity = opacity || 1; + if (inkLists) { + editor.#thickness = data.thickness; + } + editor.annotationElementId = data.id || null; + editor._initialData = initialData; + const [pageWidth, pageHeight] = editor.pageDimensions; + const [pageX, pageY] = editor.pageTranslation; + if (quadPoints) { + const boxes = editor.#boxes = []; + for (let i = 0; i < quadPoints.length; i += 8) { + boxes.push({ + x: (quadPoints[i] - pageX) / pageWidth, + y: 1 - (quadPoints[i + 1] - pageY) / pageHeight, + width: (quadPoints[i + 2] - quadPoints[i]) / pageWidth, + height: (quadPoints[i + 1] - quadPoints[i + 5]) / pageHeight + }); + } + editor.#createOutlines(); + editor.#addToDrawLayer(); + editor.rotate(editor.rotation); + } else if (inkLists) { + editor.#isFreeHighlight = true; + const points = inkLists[0]; + const point = { + x: points[0] - pageX, + y: pageHeight - (points[1] - pageY) + }; + const outliner = new FreeHighlightOutliner(point, [0, 0, pageWidth, pageHeight], 1, editor.#thickness / 2, true, 0.001); + for (let i = 0, ii = points.length; i < ii; i += 2) { + point.x = points[i] - pageX; + point.y = pageHeight - (points[i + 1] - pageY); + outliner.add(point); + } + const { + id, + clipPathId + } = parent.drawLayer.draw({ + bbox: [0, 0, 1, 1], + root: { + viewBox: "0 0 1 1", + fill: editor.color, + "fill-opacity": editor._defaultOpacity + }, + rootClass: { + highlight: true, + free: true + }, + path: { + d: outliner.toSVGPath() + } + }, true, true); + editor.#createFreeOutlines({ + highlightOutlines: outliner.getOutlines(), + highlightId: id, + clipPathId + }); + editor.#addToDrawLayer(); + } + return editor; + } + serialize(isForCopying = false) { + if (this.isEmpty() || isForCopying) { + return null; + } + if (this.deleted) { + return this.serializeDeleted(); + } + const rect = this.getRect(0, 0); + const color = AnnotationEditor._colorManager.convert(this.color); + const serialized = { + annotationType: AnnotationEditorType.HIGHLIGHT, + color, + opacity: this.#opacity, + thickness: this.#thickness, + quadPoints: this.#serializeBoxes(), + outlines: this.#serializeOutlines(rect), + pageIndex: this.pageIndex, + rect, + rotation: this.#getRotation(), + structTreeParentId: this._structTreeParentId + }; + if (this.annotationElementId && !this.#hasElementChanged(serialized)) { + return null; + } + serialized.id = this.annotationElementId; + return serialized; + } + #hasElementChanged(serialized) { + const { + color + } = this._initialData; + return serialized.color.some((c, i) => c !== color[i]); + } + renderAnnotationElement(annotation) { + annotation.updateEdited({ + rect: this.getRect(0, 0) + }); + return null; + } + static canCreateNewEmptyEditor() { + return false; + } +} + +;// ./src/display/editor/draw.js + + + +class DrawingOptions { + #svgProperties = Object.create(null); + updateProperty(name, value) { + this[name] = value; + this.updateSVGProperty(name, value); + } + updateProperties(properties) { + if (!properties) { + return; + } + for (const [name, value] of Object.entries(properties)) { + this.updateProperty(name, value); + } + } + updateSVGProperty(name, value) { + this.#svgProperties[name] = value; + } + toSVGProperties() { + const root = this.#svgProperties; + this.#svgProperties = Object.create(null); + return { + root + }; + } + reset() { + this.#svgProperties = Object.create(null); + } + updateAll(options = this) { + this.updateProperties(options); + } + clone() { + unreachable("Not implemented"); + } +} +class DrawingEditor extends AnnotationEditor { + #drawOutlines = null; + #mustBeCommitted; + _drawId = null; + static _currentDrawId = -1; + static _currentDraw = null; + static _currentDrawingOptions = null; + static _currentParent = null; + static _INNER_MARGIN = 3; + constructor(params) { + super(params); + this.#mustBeCommitted = params.mustBeCommitted || false; + if (params.drawOutlines) { + this.#createDrawOutlines(params); + this.#addToDrawLayer(); + } + } + #createDrawOutlines({ + drawOutlines, + drawId, + drawingOptions + }) { + this.#drawOutlines = drawOutlines; + this._drawingOptions ||= drawingOptions; + if (drawId >= 0) { + this._drawId = drawId; + this.parent.drawLayer.finalizeDraw(drawId, drawOutlines.defaultProperties); + } else { + this._drawId = this.#createDrawing(drawOutlines, this.parent); + } + this.#updateBbox(drawOutlines.box); + } + #createDrawing(drawOutlines, parent) { + const { + id + } = parent.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(), drawOutlines.defaultSVGProperties), false, false); + return id; + } + static _mergeSVGProperties(p1, p2) { + const p1Keys = new Set(Object.keys(p1)); + for (const [key, value] of Object.entries(p2)) { + if (p1Keys.has(key)) { + Object.assign(p1[key], value); + } else { + p1[key] = value; + } + } + return p1; + } + static getDefaultDrawingOptions(_options) { + unreachable("Not implemented"); + } + static get typesMap() { + unreachable("Not implemented"); + } + static get isDrawer() { + return true; + } + static get supportMultipleDrawings() { + return false; + } + static updateDefaultParams(type, value) { + const propertyName = this.typesMap.get(type); + if (propertyName) { + this._defaultDrawingOptions.updateProperty(propertyName, value); + } + if (this._currentParent) { + this._currentDraw.updateProperty(propertyName, value); + this._currentParent.drawLayer.updateProperties(this._currentDrawId, this._defaultDrawingOptions.toSVGProperties()); + } + } + updateParams(type, value) { + const propertyName = this.constructor.typesMap.get(type); + if (propertyName) { + this._updateProperty(type, propertyName, value); + } + } + static get defaultPropertiesToUpdate() { + const properties = []; + const options = this._defaultDrawingOptions; + for (const [type, name] of this.typesMap) { + properties.push([type, options[name]]); + } + return properties; + } + get propertiesToUpdate() { + const properties = []; + const { + _drawingOptions + } = this; + for (const [type, name] of this.constructor.typesMap) { + properties.push([type, _drawingOptions[name]]); + } + return properties; + } + _updateProperty(type, name, value) { + const options = this._drawingOptions; + const savedValue = options[name]; + const setter = val => { + options.updateProperty(name, val); + const bbox = this.#drawOutlines.updateProperty(name, val); + if (bbox) { + this.#updateBbox(bbox); + } + this.parent?.drawLayer.updateProperties(this._drawId, options.toSVGProperties()); + }; + this.addCommands({ + cmd: setter.bind(this, value), + undo: setter.bind(this, savedValue), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type, + overwriteIfSameType: true, + keepUndo: true + }); + } + _onResizing() { + this.parent?.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathResizingSVGProperties(this.#convertToDrawSpace()), { + bbox: this.#rotateBox() + })); + } + _onResized() { + this.parent?.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathResizedSVGProperties(this.#convertToDrawSpace()), { + bbox: this.#rotateBox() + })); + } + _onTranslating(x, y) { + this.parent?.drawLayer.updateProperties(this._drawId, { + bbox: this.#rotateBox(x, y) + }); + } + _onTranslated() { + this.parent?.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathTranslatedSVGProperties(this.#convertToDrawSpace(), this.parentDimensions), { + bbox: this.#rotateBox() + })); + } + _onStartDragging() { + this.parent?.drawLayer.updateProperties(this._drawId, { + rootClass: { + moving: true + } + }); + } + _onStopDragging() { + this.parent?.drawLayer.updateProperties(this._drawId, { + rootClass: { + moving: false + } + }); + } + commit() { + super.commit(); + this.disableEditMode(); + this.disableEditing(); + } + disableEditing() { + super.disableEditing(); + this.div.classList.toggle("disabled", true); + } + enableEditing() { + super.enableEditing(); + this.div.classList.toggle("disabled", false); + } + getBaseTranslation() { + return [0, 0]; + } + get isResizable() { + return true; + } + onceAdded() { + if (!this.annotationElementId) { + this.parent.addUndoableEditor(this); + } + this._isDraggable = true; + if (this.#mustBeCommitted) { + this.#mustBeCommitted = false; + this.commit(); + this.parent.setSelected(this); + if (this.isOnScreen) { + this.div.focus(); + } + } + } + remove() { + this.#cleanDrawLayer(); + super.remove(); + } + rebuild() { + if (!this.parent) { + return; + } + super.rebuild(); + if (this.div === null) { + return; + } + this.#addToDrawLayer(); + this.#updateBbox(this.#drawOutlines.box); + if (!this.isAttachedToDOM) { + this.parent.add(this); + } + } + setParent(parent) { + let mustBeSelected = false; + if (this.parent && !parent) { + this._uiManager.removeShouldRescale(this); + this.#cleanDrawLayer(); + } else if (parent) { + this._uiManager.addShouldRescale(this); + this.#addToDrawLayer(parent); + mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor"); + } + super.setParent(parent); + if (mustBeSelected) { + this.select(); + } + } + #cleanDrawLayer() { + if (this._drawId === null || !this.parent) { + return; + } + this.parent.drawLayer.remove(this._drawId); + this._drawId = null; + this._drawingOptions.reset(); + } + #addToDrawLayer(parent = this.parent) { + if (this._drawId !== null && this.parent === parent) { + return; + } + if (this._drawId !== null) { + this.parent.drawLayer.updateParent(this._drawId, parent.drawLayer); + return; + } + this._drawingOptions.updateAll(); + this._drawId = this.#createDrawing(this.#drawOutlines, parent); + } + #convertToParentSpace([x, y, width, height]) { + const { + parentDimensions: [pW, pH], + rotation + } = this; + switch (rotation) { + case 90: + return [y, 1 - x, width * (pH / pW), height * (pW / pH)]; + case 180: + return [1 - x, 1 - y, width, height]; + case 270: + return [1 - y, x, width * (pH / pW), height * (pW / pH)]; + default: + return [x, y, width, height]; + } + } + #convertToDrawSpace() { + const { + x, + y, + width, + height, + parentDimensions: [pW, pH], + rotation + } = this; + switch (rotation) { + case 90: + return [1 - y, x, width * (pW / pH), height * (pH / pW)]; + case 180: + return [1 - x, 1 - y, width, height]; + case 270: + return [y, 1 - x, width * (pW / pH), height * (pH / pW)]; + default: + return [x, y, width, height]; + } + } + #updateBbox(bbox) { + [this.x, this.y, this.width, this.height] = this.#convertToParentSpace(bbox); + if (this.div) { + this.fixAndSetPosition(); + const [parentWidth, parentHeight] = this.parentDimensions; + this.setDims(this.width * parentWidth, this.height * parentHeight); + } + this._onResized(); + } + #rotateBox() { + const { + x, + y, + width, + height, + rotation, + parentRotation, + parentDimensions: [pW, pH] + } = this; + switch ((rotation * 4 + parentRotation) / 90) { + case 1: + return [1 - y - height, x, height, width]; + case 2: + return [1 - x - width, 1 - y - height, width, height]; + case 3: + return [y, 1 - x - width, height, width]; + case 4: + return [x, y - width * (pW / pH), height * (pH / pW), width * (pW / pH)]; + case 5: + return [1 - y, x, width * (pW / pH), height * (pH / pW)]; + case 6: + return [1 - x - height * (pH / pW), 1 - y, height * (pH / pW), width * (pW / pH)]; + case 7: + return [y - width * (pW / pH), 1 - x - height * (pH / pW), width * (pW / pH), height * (pH / pW)]; + case 8: + return [x - width, y - height, width, height]; + case 9: + return [1 - y, x - width, height, width]; + case 10: + return [1 - x, 1 - y, width, height]; + case 11: + return [y - height, 1 - x, height, width]; + case 12: + return [x - height * (pH / pW), y, height * (pH / pW), width * (pW / pH)]; + case 13: + return [1 - y - width * (pW / pH), x - height * (pH / pW), width * (pW / pH), height * (pH / pW)]; + case 14: + return [1 - x, 1 - y - width * (pW / pH), height * (pH / pW), width * (pW / pH)]; + case 15: + return [y, 1 - x, width * (pW / pH), height * (pH / pW)]; + default: + return [x, y, width, height]; + } + } + rotate() { + if (!this.parent) { + return; + } + this.parent.drawLayer.updateProperties(this._drawId, DrawingEditor._mergeSVGProperties({ + bbox: this.#rotateBox() + }, this.#drawOutlines.updateRotation((this.parentRotation - this.rotation + 360) % 360))); + } + onScaleChanging() { + if (!this.parent) { + return; + } + this.#updateBbox(this.#drawOutlines.updateParentDimensions(this.parentDimensions, this.parent.scale)); + } + static onScaleChangingWhenDrawing() {} + render() { + if (this.div) { + return this.div; + } + const div = super.render(); + div.classList.add("draw"); + const drawDiv = document.createElement("div"); + div.append(drawDiv); + drawDiv.setAttribute("aria-hidden", "true"); + drawDiv.className = "internal"; + const [parentWidth, parentHeight] = this.parentDimensions; + this.setDims(this.width * parentWidth, this.height * parentHeight); + this._uiManager.addShouldRescale(this); + this.disableEditing(); + return div; + } + static createDrawerInstance(_x, _y, _parentWidth, _parentHeight, _rotation) { + unreachable("Not implemented"); + } + static startDrawing(parent, uiManager, _isLTR, { + target, + offsetX: x, + offsetY: y + }) { + const { + viewport: { + rotation + } + } = parent; + const { + width: parentWidth, + height: parentHeight + } = target.getBoundingClientRect(); + const ac = new AbortController(); + const signal = parent.combinedSignal(ac); + window.addEventListener("pointerup", e => { + ac.abort(); + parent.toggleDrawing(true); + this._endDraw(e); + }, { + signal + }); + window.addEventListener("pointerdown", stopEvent, { + capture: true, + passive: false, + signal + }); + window.addEventListener("contextmenu", noContextMenu, { + signal + }); + target.addEventListener("pointermove", this._drawMove.bind(this), { + signal + }); + parent.toggleDrawing(); + uiManager._editorUndoBar?.hide(); + if (this._currentDraw) { + parent.drawLayer.updateProperties(this._currentDrawId, this._currentDraw.startNew(x, y, parentWidth, parentHeight, rotation)); + return; + } + uiManager.updateUIForDefaultProperties(this); + this._currentDraw = this.createDrawerInstance(x, y, parentWidth, parentHeight, rotation); + this._currentDrawingOptions = this.getDefaultDrawingOptions(); + this._currentParent = parent; + ({ + id: this._currentDrawId + } = parent.drawLayer.draw(this._mergeSVGProperties(this._currentDrawingOptions.toSVGProperties(), this._currentDraw.defaultSVGProperties), true, false)); + } + static _drawMove({ + offsetX, + offsetY + }) { + this._currentParent.drawLayer.updateProperties(this._currentDrawId, this._currentDraw.add(offsetX, offsetY)); + } + static _endDraw({ + offsetX, + offsetY + }) { + const parent = this._currentParent; + parent.drawLayer.updateProperties(this._currentDrawId, this._currentDraw.end(offsetX, offsetY)); + if (this.supportMultipleDrawings) { + const draw = this._currentDraw; + const drawId = this._currentDrawId; + const lastElement = draw.getLastElement(); + parent.addCommands({ + cmd: () => { + parent.drawLayer.updateProperties(drawId, draw.setLastElement(lastElement)); + }, + undo: () => { + parent.drawLayer.updateProperties(drawId, draw.removeLastElement()); + }, + mustExec: false, + type: AnnotationEditorParamsType.DRAW_STEP + }); + return; + } + this.endDrawing(false); + } + static endDrawing(isAborted) { + const parent = this._currentParent; + if (!parent) { + return null; + } + parent.toggleDrawing(true); + parent.cleanUndoStack(AnnotationEditorParamsType.DRAW_STEP); + if (!this._currentDraw.isEmpty()) { + const { + pageDimensions: [pageWidth, pageHeight], + scale + } = parent; + const editor = parent.createAndAddNewEditor({ + offsetX: 0, + offsetY: 0 + }, false, { + drawId: this._currentDrawId, + drawOutlines: this._currentDraw.getOutlines(pageWidth * scale, pageHeight * scale, scale, this._INNER_MARGIN), + drawingOptions: this._currentDrawingOptions, + mustBeCommitted: !isAborted + }); + this._cleanup(); + return editor; + } + parent.drawLayer.remove(this._currentDrawId); + this._cleanup(); + return null; + } + static _cleanup() { + this._currentDrawId = -1; + this._currentDraw = null; + this._currentDrawingOptions = null; + this._currentParent = null; + } + createDrawingOptions(_data) {} + static deserializeDraw(_pageX, _pageY, _pageWidth, _pageHeight, _innerWidth, _data) { + unreachable("Not implemented"); + } + static async deserialize(data, parent, uiManager) { + const { + rawDims: { + pageWidth, + pageHeight, + pageX, + pageY + } + } = parent.viewport; + const drawOutlines = this.deserializeDraw(pageX, pageY, pageWidth, pageHeight, this._INNER_MARGIN, data); + const editor = await super.deserialize(data, parent, uiManager); + editor.createDrawingOptions(data); + editor.#createDrawOutlines({ + drawOutlines + }); + editor.#addToDrawLayer(); + editor.onScaleChanging(); + editor.rotate(); + return editor; + } + serializeDraw(isForCopying) { + const [pageX, pageY] = this.pageTranslation; + const [pageWidth, pageHeight] = this.pageDimensions; + return this.#drawOutlines.serialize([pageX, pageY, pageWidth, pageHeight], isForCopying); + } + renderAnnotationElement(annotation) { + annotation.updateEdited({ + rect: this.getRect(0, 0) + }); + return null; + } + static canCreateNewEmptyEditor() { + return false; + } +} + +;// ./src/display/editor/drawers/inkdraw.js + + +class InkDrawOutliner { + #last = new Float64Array(6); + #line; + #lines; + #rotation; + #thickness; + #points; + #lastSVGPath = ""; + #lastIndex = 0; + #outlines = new InkDrawOutline(); + #parentWidth; + #parentHeight; + constructor(x, y, parentWidth, parentHeight, rotation, thickness) { + this.#parentWidth = parentWidth; + this.#parentHeight = parentHeight; + this.#rotation = rotation; + this.#thickness = thickness; + [x, y] = this.#normalizePoint(x, y); + const line = this.#line = [NaN, NaN, NaN, NaN, x, y]; + this.#points = [x, y]; + this.#lines = [{ + line, + points: this.#points + }]; + this.#last.set(line, 0); + } + updateProperty(name, value) { + if (name === "stroke-width") { + this.#thickness = value; + } + } + #normalizePoint(x, y) { + return Outline._normalizePoint(x, y, this.#parentWidth, this.#parentHeight, this.#rotation); + } + isEmpty() { + return !this.#lines || this.#lines.length === 0; + } + add(x, y) { + [x, y] = this.#normalizePoint(x, y); + const [x1, y1, x2, y2] = this.#last.subarray(2, 6); + const diffX = x - x2; + const diffY = y - y2; + const d = Math.hypot(this.#parentWidth * diffX, this.#parentHeight * diffY); + if (d <= 2) { + return null; + } + this.#points.push(x, y); + if (isNaN(x1)) { + this.#last.set([x2, y2, x, y], 2); + this.#line.push(NaN, NaN, NaN, NaN, x, y); + return { + path: { + d: this.toSVGPath() + } + }; + } + if (isNaN(this.#last[0])) { + this.#line.splice(6, 6); + } + this.#last.set([x1, y1, x2, y2, x, y], 0); + this.#line.push(...Outline.createBezierPoints(x1, y1, x2, y2, x, y)); + return { + path: { + d: this.toSVGPath() + } + }; + } + end(x, y) { + const change = this.add(x, y); + if (change) { + return change; + } + if (this.#points.length === 2) { + return { + path: { + d: this.toSVGPath() + } + }; + } + return null; + } + startNew(x, y, parentWidth, parentHeight, rotation) { + this.#parentWidth = parentWidth; + this.#parentHeight = parentHeight; + this.#rotation = rotation; + [x, y] = this.#normalizePoint(x, y); + const line = this.#line = [NaN, NaN, NaN, NaN, x, y]; + this.#points = [x, y]; + const last = this.#lines.at(-1); + if (last) { + last.line = new Float32Array(last.line); + last.points = new Float32Array(last.points); + } + this.#lines.push({ + line, + points: this.#points + }); + this.#last.set(line, 0); + this.#lastIndex = 0; + this.toSVGPath(); + return null; + } + getLastElement() { + return this.#lines.at(-1); + } + setLastElement(element) { + if (!this.#lines) { + return this.#outlines.setLastElement(element); + } + this.#lines.push(element); + this.#line = element.line; + this.#points = element.points; + this.#lastIndex = 0; + return { + path: { + d: this.toSVGPath() + } + }; + } + removeLastElement() { + if (!this.#lines) { + return this.#outlines.removeLastElement(); + } + this.#lines.pop(); + this.#lastSVGPath = ""; + for (let i = 0, ii = this.#lines.length; i < ii; i++) { + const { + line, + points + } = this.#lines[i]; + this.#line = line; + this.#points = points; + this.#lastIndex = 0; + this.toSVGPath(); + } + return { + path: { + d: this.#lastSVGPath + } + }; + } + toSVGPath() { + const firstX = Outline.svgRound(this.#line[4]); + const firstY = Outline.svgRound(this.#line[5]); + if (this.#points.length === 2) { + this.#lastSVGPath = `${this.#lastSVGPath} M ${firstX} ${firstY} Z`; + return this.#lastSVGPath; + } + if (this.#points.length <= 6) { + const i = this.#lastSVGPath.lastIndexOf("M"); + this.#lastSVGPath = `${this.#lastSVGPath.slice(0, i)} M ${firstX} ${firstY}`; + this.#lastIndex = 6; + } + if (this.#points.length === 4) { + const secondX = Outline.svgRound(this.#line[10]); + const secondY = Outline.svgRound(this.#line[11]); + this.#lastSVGPath = `${this.#lastSVGPath} L ${secondX} ${secondY}`; + this.#lastIndex = 12; + return this.#lastSVGPath; + } + const buffer = []; + if (this.#lastIndex === 0) { + buffer.push(`M ${firstX} ${firstY}`); + this.#lastIndex = 6; + } + for (let i = this.#lastIndex, ii = this.#line.length; i < ii; i += 6) { + const [c1x, c1y, c2x, c2y, x, y] = this.#line.slice(i, i + 6).map(Outline.svgRound); + buffer.push(`C${c1x} ${c1y} ${c2x} ${c2y} ${x} ${y}`); + } + this.#lastSVGPath += buffer.join(" "); + this.#lastIndex = this.#line.length; + return this.#lastSVGPath; + } + getOutlines(parentWidth, parentHeight, scale, innerMargin) { + const last = this.#lines.at(-1); + last.line = new Float32Array(last.line); + last.points = new Float32Array(last.points); + this.#outlines.build(this.#lines, parentWidth, parentHeight, scale, this.#rotation, this.#thickness, innerMargin); + this.#last = null; + this.#line = null; + this.#lines = null; + this.#lastSVGPath = null; + return this.#outlines; + } + get defaultSVGProperties() { + return { + root: { + viewBox: "0 0 10000 10000" + }, + rootClass: { + draw: true + }, + bbox: [0, 0, 1, 1] + }; + } +} +class InkDrawOutline extends Outline { + #bbox; + #currentRotation = 0; + #innerMargin; + #lines; + #parentWidth; + #parentHeight; + #parentScale; + #rotation; + #thickness; + build(lines, parentWidth, parentHeight, parentScale, rotation, thickness, innerMargin) { + this.#parentWidth = parentWidth; + this.#parentHeight = parentHeight; + this.#parentScale = parentScale; + this.#rotation = rotation; + this.#thickness = thickness; + this.#innerMargin = innerMargin ?? 0; + this.#lines = lines; + this.#computeBbox(); + } + setLastElement(element) { + this.#lines.push(element); + return { + path: { + d: this.toSVGPath() + } + }; + } + removeLastElement() { + this.#lines.pop(); + return { + path: { + d: this.toSVGPath() + } + }; + } + toSVGPath() { + const buffer = []; + for (const { + line + } of this.#lines) { + buffer.push(`M${Outline.svgRound(line[4])} ${Outline.svgRound(line[5])}`); + if (line.length === 6) { + buffer.push("Z"); + continue; + } + if (line.length === 12) { + buffer.push(`L${Outline.svgRound(line[10])} ${Outline.svgRound(line[11])}`); + continue; + } + for (let i = 6, ii = line.length; i < ii; i += 6) { + const [c1x, c1y, c2x, c2y, x, y] = line.subarray(i, i + 6).map(Outline.svgRound); + buffer.push(`C${c1x} ${c1y} ${c2x} ${c2y} ${x} ${y}`); + } + } + return buffer.join(""); + } + serialize([pageX, pageY, pageWidth, pageHeight], isForCopying) { + const serializedLines = []; + const serializedPoints = []; + const [x, y, width, height] = this.#getBBoxWithNoMargin(); + let tx, ty, sx, sy, x1, y1, x2, y2, rescaleFn; + switch (this.#rotation) { + case 0: + rescaleFn = Outline._rescale; + tx = pageX; + ty = pageY + pageHeight; + sx = pageWidth; + sy = -pageHeight; + x1 = pageX + x * pageWidth; + y1 = pageY + (1 - y - height) * pageHeight; + x2 = pageX + (x + width) * pageWidth; + y2 = pageY + (1 - y) * pageHeight; + break; + case 90: + rescaleFn = Outline._rescaleAndSwap; + tx = pageX; + ty = pageY; + sx = pageWidth; + sy = pageHeight; + x1 = pageX + y * pageWidth; + y1 = pageY + x * pageHeight; + x2 = pageX + (y + height) * pageWidth; + y2 = pageY + (x + width) * pageHeight; + break; + case 180: + rescaleFn = Outline._rescale; + tx = pageX + pageWidth; + ty = pageY; + sx = -pageWidth; + sy = pageHeight; + x1 = pageX + (1 - x - width) * pageWidth; + y1 = pageY + y * pageHeight; + x2 = pageX + (1 - x) * pageWidth; + y2 = pageY + (y + height) * pageHeight; + break; + case 270: + rescaleFn = Outline._rescaleAndSwap; + tx = pageX + pageWidth; + ty = pageY + pageHeight; + sx = -pageWidth; + sy = -pageHeight; + x1 = pageX + (1 - y - height) * pageWidth; + y1 = pageY + (1 - x - width) * pageHeight; + x2 = pageX + (1 - y) * pageWidth; + y2 = pageY + (1 - x) * pageHeight; + break; + } + for (const { + line, + points + } of this.#lines) { + serializedLines.push(rescaleFn(line, tx, ty, sx, sy, isForCopying ? new Array(line.length) : null)); + serializedPoints.push(rescaleFn(points, tx, ty, sx, sy, isForCopying ? new Array(points.length) : null)); + } + return { + lines: serializedLines, + points: serializedPoints, + rect: [x1, y1, x2, y2] + }; + } + static deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, { + paths: { + lines, + points + }, + rotation, + thickness + }) { + const newLines = []; + let tx, ty, sx, sy, rescaleFn; + switch (rotation) { + case 0: + rescaleFn = Outline._rescale; + tx = -pageX / pageWidth; + ty = pageY / pageHeight + 1; + sx = 1 / pageWidth; + sy = -1 / pageHeight; + break; + case 90: + rescaleFn = Outline._rescaleAndSwap; + tx = -pageY / pageHeight; + ty = -pageX / pageWidth; + sx = 1 / pageHeight; + sy = 1 / pageWidth; + break; + case 180: + rescaleFn = Outline._rescale; + tx = pageX / pageWidth + 1; + ty = -pageY / pageHeight; + sx = -1 / pageWidth; + sy = 1 / pageHeight; + break; + case 270: + rescaleFn = Outline._rescaleAndSwap; + tx = pageY / pageHeight + 1; + ty = pageX / pageWidth + 1; + sx = -1 / pageHeight; + sy = -1 / pageWidth; + break; + } + if (!lines) { + lines = []; + for (const point of points) { + const len = point.length; + if (len === 2) { + lines.push(new Float32Array([NaN, NaN, NaN, NaN, point[0], point[1]])); + continue; + } + if (len === 4) { + lines.push(new Float32Array([NaN, NaN, NaN, NaN, point[0], point[1], NaN, NaN, NaN, NaN, point[2], point[3]])); + continue; + } + const line = new Float32Array(3 * (len - 2)); + lines.push(line); + let [x1, y1, x2, y2] = point.subarray(0, 4); + line.set([NaN, NaN, NaN, NaN, x1, y1], 0); + for (let i = 4; i < len; i += 2) { + const x = point[i]; + const y = point[i + 1]; + line.set(Outline.createBezierPoints(x1, y1, x2, y2, x, y), (i - 2) * 3); + [x1, y1, x2, y2] = [x2, y2, x, y]; + } + } + } + for (let i = 0, ii = lines.length; i < ii; i++) { + newLines.push({ + line: rescaleFn(lines[i].map(x => x ?? NaN), tx, ty, sx, sy), + points: rescaleFn(points[i].map(x => x ?? NaN), tx, ty, sx, sy) + }); + } + const outlines = new InkDrawOutline(); + outlines.build(newLines, pageWidth, pageHeight, 1, rotation, thickness, innerMargin); + return outlines; + } + #getMarginComponents(thickness = this.#thickness) { + const margin = this.#innerMargin + thickness / 2 * this.#parentScale; + return this.#rotation % 180 === 0 ? [margin / this.#parentWidth, margin / this.#parentHeight] : [margin / this.#parentHeight, margin / this.#parentWidth]; + } + #getBBoxWithNoMargin() { + const [x, y, width, height] = this.#bbox; + const [marginX, marginY] = this.#getMarginComponents(0); + return [x + marginX, y + marginY, width - 2 * marginX, height - 2 * marginY]; + } + #computeBbox() { + const bbox = this.#bbox = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]); + for (const { + line + } of this.#lines) { + if (line.length <= 12) { + for (let i = 4, ii = line.length; i < ii; i += 6) { + const [x, y] = line.subarray(i, i + 2); + bbox[0] = Math.min(bbox[0], x); + bbox[1] = Math.min(bbox[1], y); + bbox[2] = Math.max(bbox[2], x); + bbox[3] = Math.max(bbox[3], y); + } + continue; + } + let lastX = line[4], + lastY = line[5]; + for (let i = 6, ii = line.length; i < ii; i += 6) { + const [c1x, c1y, c2x, c2y, x, y] = line.subarray(i, i + 6); + Util.bezierBoundingBox(lastX, lastY, c1x, c1y, c2x, c2y, x, y, bbox); + lastX = x; + lastY = y; + } + } + const [marginX, marginY] = this.#getMarginComponents(); + bbox[0] = Math.min(1, Math.max(0, bbox[0] - marginX)); + bbox[1] = Math.min(1, Math.max(0, bbox[1] - marginY)); + bbox[2] = Math.min(1, Math.max(0, bbox[2] + marginX)); + bbox[3] = Math.min(1, Math.max(0, bbox[3] + marginY)); + bbox[2] -= bbox[0]; + bbox[3] -= bbox[1]; + } + get box() { + return this.#bbox; + } + updateProperty(name, value) { + if (name === "stroke-width") { + return this.#updateThickness(value); + } + return null; + } + #updateThickness(thickness) { + const [oldMarginX, oldMarginY] = this.#getMarginComponents(); + this.#thickness = thickness; + const [newMarginX, newMarginY] = this.#getMarginComponents(); + const [diffMarginX, diffMarginY] = [newMarginX - oldMarginX, newMarginY - oldMarginY]; + const bbox = this.#bbox; + bbox[0] -= diffMarginX; + bbox[1] -= diffMarginY; + bbox[2] += 2 * diffMarginX; + bbox[3] += 2 * diffMarginY; + return bbox; + } + updateParentDimensions([width, height], scale) { + const [oldMarginX, oldMarginY] = this.#getMarginComponents(); + this.#parentWidth = width; + this.#parentHeight = height; + this.#parentScale = scale; + const [newMarginX, newMarginY] = this.#getMarginComponents(); + const diffMarginX = newMarginX - oldMarginX; + const diffMarginY = newMarginY - oldMarginY; + const bbox = this.#bbox; + bbox[0] -= diffMarginX; + bbox[1] -= diffMarginY; + bbox[2] += 2 * diffMarginX; + bbox[3] += 2 * diffMarginY; + return bbox; + } + updateRotation(rotation) { + this.#currentRotation = rotation; + return { + path: { + transform: this.rotationTransform + } + }; + } + get viewBox() { + return this.#bbox.map(Outline.svgRound).join(" "); + } + get defaultProperties() { + const [x, y] = this.#bbox; + return { + root: { + viewBox: this.viewBox + }, + path: { + "transform-origin": `${Outline.svgRound(x)} ${Outline.svgRound(y)}` + } + }; + } + get rotationTransform() { + const [,, width, height] = this.#bbox; + let a = 0, + b = 0, + c = 0, + d = 0, + e = 0, + f = 0; + switch (this.#currentRotation) { + case 90: + b = height / width; + c = -width / height; + e = width; + break; + case 180: + a = -1; + d = -1; + e = width; + f = height; + break; + case 270: + b = -height / width; + c = width / height; + f = height; + break; + default: + return ""; + } + return `matrix(${a} ${b} ${c} ${d} ${Outline.svgRound(e)} ${Outline.svgRound(f)})`; + } + getPathResizingSVGProperties([newX, newY, newWidth, newHeight]) { + const [marginX, marginY] = this.#getMarginComponents(); + const [x, y, width, height] = this.#bbox; + if (Math.abs(width - marginX) <= Outline.PRECISION || Math.abs(height - marginY) <= Outline.PRECISION) { + const tx = newX + newWidth / 2 - (x + width / 2); + const ty = newY + newHeight / 2 - (y + height / 2); + return { + path: { + "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`, + transform: `${this.rotationTransform} translate(${tx} ${ty})` + } + }; + } + const s1x = (newWidth - 2 * marginX) / (width - 2 * marginX); + const s1y = (newHeight - 2 * marginY) / (height - 2 * marginY); + const s2x = width / newWidth; + const s2y = height / newHeight; + return { + path: { + "transform-origin": `${Outline.svgRound(x)} ${Outline.svgRound(y)}`, + transform: `${this.rotationTransform} scale(${s2x} ${s2y}) ` + `translate(${Outline.svgRound(marginX)} ${Outline.svgRound(marginY)}) scale(${s1x} ${s1y}) ` + `translate(${Outline.svgRound(-marginX)} ${Outline.svgRound(-marginY)})` + } + }; + } + getPathResizedSVGProperties([newX, newY, newWidth, newHeight]) { + const [marginX, marginY] = this.#getMarginComponents(); + const bbox = this.#bbox; + const [x, y, width, height] = bbox; + bbox[0] = newX; + bbox[1] = newY; + bbox[2] = newWidth; + bbox[3] = newHeight; + if (Math.abs(width - marginX) <= Outline.PRECISION || Math.abs(height - marginY) <= Outline.PRECISION) { + const tx = newX + newWidth / 2 - (x + width / 2); + const ty = newY + newHeight / 2 - (y + height / 2); + for (const { + line, + points + } of this.#lines) { + Outline._translate(line, tx, ty, line); + Outline._translate(points, tx, ty, points); + } + return { + root: { + viewBox: this.viewBox + }, + path: { + "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`, + transform: this.rotationTransform || null, + d: this.toSVGPath() + } + }; + } + const s1x = (newWidth - 2 * marginX) / (width - 2 * marginX); + const s1y = (newHeight - 2 * marginY) / (height - 2 * marginY); + const tx = -s1x * (x + marginX) + newX + marginX; + const ty = -s1y * (y + marginY) + newY + marginY; + if (s1x !== 1 || s1y !== 1 || tx !== 0 || ty !== 0) { + for (const { + line, + points + } of this.#lines) { + Outline._rescale(line, tx, ty, s1x, s1y, line); + Outline._rescale(points, tx, ty, s1x, s1y, points); + } + } + return { + root: { + viewBox: this.viewBox + }, + path: { + "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`, + transform: this.rotationTransform || null, + d: this.toSVGPath() + } + }; + } + getPathTranslatedSVGProperties([newX, newY], parentDimensions) { + const [newParentWidth, newParentHeight] = parentDimensions; + const bbox = this.#bbox; + const tx = newX - bbox[0]; + const ty = newY - bbox[1]; + if (this.#parentWidth === newParentWidth && this.#parentHeight === newParentHeight) { + for (const { + line, + points + } of this.#lines) { + Outline._translate(line, tx, ty, line); + Outline._translate(points, tx, ty, points); + } + } else { + const sx = this.#parentWidth / newParentWidth; + const sy = this.#parentHeight / newParentHeight; + this.#parentWidth = newParentWidth; + this.#parentHeight = newParentHeight; + for (const { + line, + points + } of this.#lines) { + Outline._rescale(line, tx, ty, sx, sy, line); + Outline._rescale(points, tx, ty, sx, sy, points); + } + bbox[2] *= sx; + bbox[3] *= sy; + } + bbox[0] = newX; + bbox[1] = newY; + return { + root: { + viewBox: this.viewBox + }, + path: { + d: this.toSVGPath(), + "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}` + } + }; + } + get defaultSVGProperties() { + const bbox = this.#bbox; + return { + root: { + viewBox: this.viewBox + }, + rootClass: { + draw: true + }, + path: { + d: this.toSVGPath(), + "transform-origin": `${Outline.svgRound(bbox[0])} ${Outline.svgRound(bbox[1])}`, + transform: this.rotationTransform || null + }, + bbox + }; + } +} + +;// ./src/display/editor/ink.js + + + + + +class InkDrawingOptions extends DrawingOptions { + #viewParameters; + constructor(viewerParameters) { + super(); + this.#viewParameters = viewerParameters; + super.updateProperties({ + fill: "none", + stroke: AnnotationEditor._defaultLineColor, + "stroke-opacity": 1, + "stroke-width": 1, + "stroke-linecap": "round", + "stroke-linejoin": "round", + "stroke-miterlimit": 10 + }); + } + updateSVGProperty(name, value) { + if (name === "stroke-width") { + value ??= this["stroke-width"]; + value *= this.#viewParameters.realScale; + } + super.updateSVGProperty(name, value); + } + clone() { + const clone = new InkDrawingOptions(this.#viewParameters); + clone.updateAll(this); + return clone; + } +} +class InkEditor extends DrawingEditor { + static _type = "ink"; + static _editorType = AnnotationEditorType.INK; + static _defaultDrawingOptions = null; + constructor(params) { + super({ + ...params, + name: "inkEditor" + }); + this._willKeepAspectRatio = true; + } + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager); + this._defaultDrawingOptions = new InkDrawingOptions(uiManager.viewParameters); + } + static getDefaultDrawingOptions(options) { + const clone = this._defaultDrawingOptions.clone(); + clone.updateProperties(options); + return clone; + } + static get supportMultipleDrawings() { + return true; + } + static get typesMap() { + return shadow(this, "typesMap", new Map([[AnnotationEditorParamsType.INK_THICKNESS, "stroke-width"], [AnnotationEditorParamsType.INK_COLOR, "stroke"], [AnnotationEditorParamsType.INK_OPACITY, "stroke-opacity"]])); + } + static createDrawerInstance(x, y, parentWidth, parentHeight, rotation) { + return new InkDrawOutliner(x, y, parentWidth, parentHeight, rotation, this._defaultDrawingOptions["stroke-width"]); + } + static deserializeDraw(pageX, pageY, pageWidth, pageHeight, innerMargin, data) { + return InkDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data); + } + static async deserialize(data, parent, uiManager) { + let initialData = null; + if (data instanceof InkAnnotationElement) { + const { + data: { + inkLists, + rect, + rotation, + id, + color, + opacity, + borderStyle: { + rawWidth: thickness + }, + popupRef + }, + parent: { + page: { + pageNumber + } + } + } = data; + initialData = data = { + annotationType: AnnotationEditorType.INK, + color: Array.from(color), + thickness, + opacity, + paths: { + points: inkLists + }, + boxes: null, + pageIndex: pageNumber - 1, + rect: rect.slice(0), + rotation, + id, + deleted: false, + popupRef + }; + } + const editor = await super.deserialize(data, parent, uiManager); + editor.annotationElementId = data.id || null; + editor._initialData = initialData; + return editor; + } + onScaleChanging() { + if (!this.parent) { + return; + } + super.onScaleChanging(); + const { + _drawId, + _drawingOptions, + parent + } = this; + _drawingOptions.updateSVGProperty("stroke-width"); + parent.drawLayer.updateProperties(_drawId, _drawingOptions.toSVGProperties()); + } + static onScaleChangingWhenDrawing() { + const parent = this._currentParent; + if (!parent) { + return; + } + super.onScaleChangingWhenDrawing(); + this._defaultDrawingOptions.updateSVGProperty("stroke-width"); + parent.drawLayer.updateProperties(this._currentDrawId, this._defaultDrawingOptions.toSVGProperties()); + } + createDrawingOptions({ + color, + thickness, + opacity + }) { + this._drawingOptions = InkEditor.getDefaultDrawingOptions({ + stroke: Util.makeHexColor(...color), + "stroke-width": thickness, + "stroke-opacity": opacity + }); + } + serialize(isForCopying = false) { + if (this.isEmpty()) { + return null; + } + if (this.deleted) { + return this.serializeDeleted(); + } + const { + lines, + points, + rect + } = this.serializeDraw(isForCopying); + const { + _drawingOptions: { + stroke, + "stroke-opacity": opacity, + "stroke-width": thickness + } + } = this; + const serialized = { + annotationType: AnnotationEditorType.INK, + color: AnnotationEditor._colorManager.convert(stroke), + opacity, + thickness, + paths: { + lines, + points + }, + pageIndex: this.pageIndex, + rect, + rotation: this.rotation, + structTreeParentId: this._structTreeParentId + }; + if (isForCopying) { + return serialized; + } + if (this.annotationElementId && !this.#hasElementChanged(serialized)) { + return null; + } + serialized.id = this.annotationElementId; + return serialized; + } + #hasElementChanged(serialized) { + const { + color, + thickness, + opacity, + pageIndex + } = this._initialData; + return this._hasBeenMoved || this._hasBeenResized || serialized.color.some((c, i) => c !== color[i]) || serialized.thickness !== thickness || serialized.opacity !== opacity || serialized.pageIndex !== pageIndex; + } + renderAnnotationElement(annotation) { + const { + points, + rect + } = this.serializeDraw(false); + annotation.updateEdited({ + rect, + thickness: this._drawingOptions["stroke-width"], + points + }); + return null; + } +} + +;// ./src/display/editor/stamp.js + + + + +class StampEditor extends AnnotationEditor { + #bitmap = null; + #bitmapId = null; + #bitmapPromise = null; + #bitmapUrl = null; + #bitmapFile = null; + #bitmapFileName = ""; + #canvas = null; + #observer = null; + #resizeTimeoutId = null; + #isSvg = false; + #hasBeenAddedInUndoStack = false; + static _type = "stamp"; + static _editorType = AnnotationEditorType.STAMP; + constructor(params) { + super({ + ...params, + name: "stampEditor" + }); + this.#bitmapUrl = params.bitmapUrl; + this.#bitmapFile = params.bitmapFile; + } + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager); + } + static get supportedTypes() { + const types = ["apng", "avif", "bmp", "gif", "jpeg", "png", "svg+xml", "webp", "x-icon"]; + return shadow(this, "supportedTypes", types.map(type => `image/${type}`)); + } + static get supportedTypesStr() { + return shadow(this, "supportedTypesStr", this.supportedTypes.join(",")); + } + static isHandlingMimeForPasting(mime) { + return this.supportedTypes.includes(mime); + } + static paste(item, parent) { + parent.pasteEditor(AnnotationEditorType.STAMP, { + bitmapFile: item.getAsFile() + }); + } + altTextFinish() { + if (this._uiManager.useNewAltTextFlow) { + this.div.hidden = false; + } + super.altTextFinish(); + } + get telemetryFinalData() { + return { + type: "stamp", + hasAltText: !!this.altTextData?.altText + }; + } + static computeTelemetryFinalData(data) { + const hasAltTextStats = data.get("hasAltText"); + return { + hasAltText: hasAltTextStats.get(true) ?? 0, + hasNoAltText: hasAltTextStats.get(false) ?? 0 + }; + } + #getBitmapFetched(data, fromId = false) { + if (!data) { + this.remove(); + return; + } + this.#bitmap = data.bitmap; + if (!fromId) { + this.#bitmapId = data.id; + this.#isSvg = data.isSvg; + } + if (data.file) { + this.#bitmapFileName = data.file.name; + } + this.#createCanvas(); + } + #getBitmapDone() { + this.#bitmapPromise = null; + this._uiManager.enableWaiting(false); + if (!this.#canvas) { + return; + } + if (this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) { + this._editToolbar.hide(); + this._uiManager.editAltText(this, true); + return; + } + if (!this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) { + this._reportTelemetry({ + action: "pdfjs.image.image_added", + data: { + alt_text_modal: false, + alt_text_type: "empty" + } + }); + try { + this.mlGuessAltText(); + } catch {} + } + this.div.focus(); + } + async mlGuessAltText(imageData = null, updateAltTextData = true) { + if (this.hasAltTextData()) { + return null; + } + const { + mlManager + } = this._uiManager; + if (!mlManager) { + throw new Error("No ML."); + } + if (!(await mlManager.isEnabledFor("altText"))) { + throw new Error("ML isn't enabled for alt text."); + } + const { + data, + width, + height + } = imageData || this.copyCanvas(null, null, true).imageData; + const response = await mlManager.guess({ + name: "altText", + request: { + data, + width, + height, + channels: data.length / (width * height) + } + }); + if (!response) { + throw new Error("No response from the AI service."); + } + if (response.error) { + throw new Error("Error from the AI service."); + } + if (response.cancel) { + return null; + } + if (!response.output) { + throw new Error("No valid response from the AI service."); + } + const altText = response.output; + await this.setGuessedAltText(altText); + if (updateAltTextData && !this.hasAltTextData()) { + this.altTextData = { + alt: altText, + decorative: false + }; + } + return altText; + } + #getBitmap() { + if (this.#bitmapId) { + this._uiManager.enableWaiting(true); + this._uiManager.imageManager.getFromId(this.#bitmapId).then(data => this.#getBitmapFetched(data, true)).finally(() => this.#getBitmapDone()); + return; + } + if (this.#bitmapUrl) { + const url = this.#bitmapUrl; + this.#bitmapUrl = null; + this._uiManager.enableWaiting(true); + this.#bitmapPromise = this._uiManager.imageManager.getFromUrl(url).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone()); + return; + } + if (this.#bitmapFile) { + const file = this.#bitmapFile; + this.#bitmapFile = null; + this._uiManager.enableWaiting(true); + this.#bitmapPromise = this._uiManager.imageManager.getFromFile(file).then(data => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone()); + return; + } + const input = document.createElement("input"); + input.type = "file"; + input.accept = StampEditor.supportedTypesStr; + const signal = this._uiManager._signal; + this.#bitmapPromise = new Promise(resolve => { + input.addEventListener("change", async () => { + if (!input.files || input.files.length === 0) { + this.remove(); + } else { + this._uiManager.enableWaiting(true); + const data = await this._uiManager.imageManager.getFromFile(input.files[0]); + this._reportTelemetry({ + action: "pdfjs.image.image_selected", + data: { + alt_text_modal: this._uiManager.useNewAltTextFlow + } + }); + this.#getBitmapFetched(data); + } + resolve(); + }, { + signal + }); + input.addEventListener("cancel", () => { + this.remove(); + resolve(); + }, { + signal + }); + }).finally(() => this.#getBitmapDone()); + input.click(); + } + remove() { + if (this.#bitmapId) { + this.#bitmap = null; + this._uiManager.imageManager.deleteId(this.#bitmapId); + this.#canvas?.remove(); + this.#canvas = null; + this.#observer?.disconnect(); + this.#observer = null; + if (this.#resizeTimeoutId) { + clearTimeout(this.#resizeTimeoutId); + this.#resizeTimeoutId = null; + } + } + super.remove(); + } + rebuild() { + if (!this.parent) { + if (this.#bitmapId) { + this.#getBitmap(); + } + return; + } + super.rebuild(); + if (this.div === null) { + return; + } + if (this.#bitmapId && this.#canvas === null) { + this.#getBitmap(); + } + if (!this.isAttachedToDOM) { + this.parent.add(this); + } + } + onceAdded() { + this._isDraggable = true; + this.div.focus(); + } + isEmpty() { + return !(this.#bitmapPromise || this.#bitmap || this.#bitmapUrl || this.#bitmapFile || this.#bitmapId); + } + get isResizable() { + return true; + } + render() { + if (this.div) { + return this.div; + } + let baseX, baseY; + if (this.width) { + baseX = this.x; + baseY = this.y; + } + super.render(); + this.div.hidden = true; + this.div.setAttribute("role", "figure"); + this.addAltTextButton(); + if (this.#bitmap) { + this.#createCanvas(); + } else { + this.#getBitmap(); + } + if (this.width && !this.annotationElementId) { + const [parentWidth, parentHeight] = this.parentDimensions; + this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight); + } + return this.div; + } + #createCanvas() { + const { + div + } = this; + let { + width, + height + } = this.#bitmap; + const [pageWidth, pageHeight] = this.pageDimensions; + const MAX_RATIO = 0.75; + if (this.width) { + width = this.width * pageWidth; + height = this.height * pageHeight; + } else if (width > MAX_RATIO * pageWidth || height > MAX_RATIO * pageHeight) { + const factor = Math.min(MAX_RATIO * pageWidth / width, MAX_RATIO * pageHeight / height); + width *= factor; + height *= factor; + } + const [parentWidth, parentHeight] = this.parentDimensions; + this.setDims(width * parentWidth / pageWidth, height * parentHeight / pageHeight); + this._uiManager.enableWaiting(false); + const canvas = this.#canvas = document.createElement("canvas"); + canvas.setAttribute("role", "img"); + this.addContainer(canvas); + if (!this._uiManager.useNewAltTextWhenAddingImage || !this._uiManager.useNewAltTextFlow || this.annotationElementId) { + div.hidden = false; + } + this.#drawBitmap(width, height); + this.#createObserver(); + if (!this.#hasBeenAddedInUndoStack) { + this.parent.addUndoableEditor(this); + this.#hasBeenAddedInUndoStack = true; + } + this._reportTelemetry({ + action: "inserted_image" + }); + if (this.#bitmapFileName) { + canvas.setAttribute("aria-label", this.#bitmapFileName); + } + } + copyCanvas(maxDataDimension, maxPreviewDimension, createImageData = false) { + if (!maxDataDimension) { + maxDataDimension = 224; + } + const { + width: bitmapWidth, + height: bitmapHeight + } = this.#bitmap; + const outputScale = new OutputScale(); + let bitmap = this.#bitmap; + let width = bitmapWidth, + height = bitmapHeight; + let canvas = null; + if (maxPreviewDimension) { + if (bitmapWidth > maxPreviewDimension || bitmapHeight > maxPreviewDimension) { + const ratio = Math.min(maxPreviewDimension / bitmapWidth, maxPreviewDimension / bitmapHeight); + width = Math.floor(bitmapWidth * ratio); + height = Math.floor(bitmapHeight * ratio); + } + canvas = document.createElement("canvas"); + const scaledWidth = canvas.width = Math.ceil(width * outputScale.sx); + const scaledHeight = canvas.height = Math.ceil(height * outputScale.sy); + if (!this.#isSvg) { + bitmap = this.#scaleBitmap(scaledWidth, scaledHeight); + } + const ctx = canvas.getContext("2d"); + ctx.filter = this._uiManager.hcmFilter; + let white = "white", + black = "#cfcfd8"; + if (this._uiManager.hcmFilter !== "none") { + black = "black"; + } else if (window.matchMedia?.("(prefers-color-scheme: dark)").matches) { + white = "#8f8f9d"; + black = "#42414d"; + } + const boxDim = 15; + const boxDimWidth = boxDim * outputScale.sx; + const boxDimHeight = boxDim * outputScale.sy; + const pattern = new OffscreenCanvas(boxDimWidth * 2, boxDimHeight * 2); + const patternCtx = pattern.getContext("2d"); + patternCtx.fillStyle = white; + patternCtx.fillRect(0, 0, boxDimWidth * 2, boxDimHeight * 2); + patternCtx.fillStyle = black; + patternCtx.fillRect(0, 0, boxDimWidth, boxDimHeight); + patternCtx.fillRect(boxDimWidth, boxDimHeight, boxDimWidth, boxDimHeight); + ctx.fillStyle = ctx.createPattern(pattern, "repeat"); + ctx.fillRect(0, 0, scaledWidth, scaledHeight); + ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight); + } + let imageData = null; + if (createImageData) { + let dataWidth, dataHeight; + if (outputScale.symmetric && bitmap.width < maxDataDimension && bitmap.height < maxDataDimension) { + dataWidth = bitmap.width; + dataHeight = bitmap.height; + } else { + bitmap = this.#bitmap; + if (bitmapWidth > maxDataDimension || bitmapHeight > maxDataDimension) { + const ratio = Math.min(maxDataDimension / bitmapWidth, maxDataDimension / bitmapHeight); + dataWidth = Math.floor(bitmapWidth * ratio); + dataHeight = Math.floor(bitmapHeight * ratio); + if (!this.#isSvg) { + bitmap = this.#scaleBitmap(dataWidth, dataHeight); + } + } + } + const offscreen = new OffscreenCanvas(dataWidth, dataHeight); + const offscreenCtx = offscreen.getContext("2d", { + willReadFrequently: true + }); + offscreenCtx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, dataWidth, dataHeight); + imageData = { + width: dataWidth, + height: dataHeight, + data: offscreenCtx.getImageData(0, 0, dataWidth, dataHeight).data + }; + } + return { + canvas, + width, + height, + imageData + }; + } + #setDimensions(width, height) { + const [parentWidth, parentHeight] = this.parentDimensions; + this.width = width / parentWidth; + this.height = height / parentHeight; + if (this._initialOptions?.isCentered) { + this.center(); + } else { + this.fixAndSetPosition(); + } + this._initialOptions = null; + if (this.#resizeTimeoutId !== null) { + clearTimeout(this.#resizeTimeoutId); + } + const TIME_TO_WAIT = 200; + this.#resizeTimeoutId = setTimeout(() => { + this.#resizeTimeoutId = null; + this.#drawBitmap(width, height); + }, TIME_TO_WAIT); + } + #scaleBitmap(width, height) { + const { + width: bitmapWidth, + height: bitmapHeight + } = this.#bitmap; + let newWidth = bitmapWidth; + let newHeight = bitmapHeight; + let bitmap = this.#bitmap; + while (newWidth > 2 * width || newHeight > 2 * height) { + const prevWidth = newWidth; + const prevHeight = newHeight; + if (newWidth > 2 * width) { + newWidth = newWidth >= 16384 ? Math.floor(newWidth / 2) - 1 : Math.ceil(newWidth / 2); + } + if (newHeight > 2 * height) { + newHeight = newHeight >= 16384 ? Math.floor(newHeight / 2) - 1 : Math.ceil(newHeight / 2); + } + const offscreen = new OffscreenCanvas(newWidth, newHeight); + const ctx = offscreen.getContext("2d"); + ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight); + bitmap = offscreen.transferToImageBitmap(); + } + return bitmap; + } + #drawBitmap(width, height) { + const outputScale = new OutputScale(); + const scaledWidth = Math.ceil(width * outputScale.sx); + const scaledHeight = Math.ceil(height * outputScale.sy); + const canvas = this.#canvas; + if (!canvas || canvas.width === scaledWidth && canvas.height === scaledHeight) { + return; + } + canvas.width = scaledWidth; + canvas.height = scaledHeight; + const bitmap = this.#isSvg ? this.#bitmap : this.#scaleBitmap(scaledWidth, scaledHeight); + const ctx = canvas.getContext("2d"); + ctx.filter = this._uiManager.hcmFilter; + ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight); + } + getImageForAltText() { + return this.#canvas; + } + #serializeBitmap(toUrl) { + if (toUrl) { + if (this.#isSvg) { + const url = this._uiManager.imageManager.getSvgUrl(this.#bitmapId); + if (url) { + return url; + } + } + const canvas = document.createElement("canvas"); + ({ + width: canvas.width, + height: canvas.height + } = this.#bitmap); + const ctx = canvas.getContext("2d"); + ctx.drawImage(this.#bitmap, 0, 0); + return canvas.toDataURL(); + } + if (this.#isSvg) { + const [pageWidth, pageHeight] = this.pageDimensions; + const width = Math.round(this.width * pageWidth * PixelsPerInch.PDF_TO_CSS_UNITS); + const height = Math.round(this.height * pageHeight * PixelsPerInch.PDF_TO_CSS_UNITS); + const offscreen = new OffscreenCanvas(width, height); + const ctx = offscreen.getContext("2d"); + ctx.drawImage(this.#bitmap, 0, 0, this.#bitmap.width, this.#bitmap.height, 0, 0, width, height); + return offscreen.transferToImageBitmap(); + } + return structuredClone(this.#bitmap); + } + #createObserver() { + if (!this._uiManager._signal) { + return; + } + this.#observer = new ResizeObserver(entries => { + const rect = entries[0].contentRect; + if (rect.width && rect.height) { + this.#setDimensions(rect.width, rect.height); + } + }); + this.#observer.observe(this.div); + this._uiManager._signal.addEventListener("abort", () => { + this.#observer?.disconnect(); + this.#observer = null; + }, { + once: true + }); + } + static async deserialize(data, parent, uiManager) { + let initialData = null; + if (data instanceof StampAnnotationElement) { + const { + data: { + rect, + rotation, + id, + structParent, + popupRef + }, + container, + parent: { + page: { + pageNumber + } + } + } = data; + const canvas = container.querySelector("canvas"); + const imageData = uiManager.imageManager.getFromCanvas(container.id, canvas); + canvas.remove(); + const altText = (await parent._structTree.getAriaAttributes(`${AnnotationPrefix}${id}`))?.get("aria-label") || ""; + initialData = data = { + annotationType: AnnotationEditorType.STAMP, + bitmapId: imageData.id, + bitmap: imageData.bitmap, + pageIndex: pageNumber - 1, + rect: rect.slice(0), + rotation, + id, + deleted: false, + accessibilityData: { + decorative: false, + altText + }, + isSvg: false, + structParent, + popupRef + }; + } + const editor = await super.deserialize(data, parent, uiManager); + const { + rect, + bitmap, + bitmapUrl, + bitmapId, + isSvg, + accessibilityData + } = data; + if (bitmapId && uiManager.imageManager.isValidId(bitmapId)) { + editor.#bitmapId = bitmapId; + if (bitmap) { + editor.#bitmap = bitmap; + } + } else { + editor.#bitmapUrl = bitmapUrl; + } + editor.#isSvg = isSvg; + const [parentWidth, parentHeight] = editor.pageDimensions; + editor.width = (rect[2] - rect[0]) / parentWidth; + editor.height = (rect[3] - rect[1]) / parentHeight; + editor.annotationElementId = data.id || null; + if (accessibilityData) { + editor.altTextData = accessibilityData; + } + editor._initialData = initialData; + editor.#hasBeenAddedInUndoStack = !!initialData; + return editor; + } + serialize(isForCopying = false, context = null) { + if (this.isEmpty()) { + return null; + } + if (this.deleted) { + return this.serializeDeleted(); + } + const serialized = { + annotationType: AnnotationEditorType.STAMP, + bitmapId: this.#bitmapId, + pageIndex: this.pageIndex, + rect: this.getRect(0, 0), + rotation: this.rotation, + isSvg: this.#isSvg, + structTreeParentId: this._structTreeParentId + }; + if (isForCopying) { + serialized.bitmapUrl = this.#serializeBitmap(true); + serialized.accessibilityData = this.serializeAltText(true); + return serialized; + } + const { + decorative, + altText + } = this.serializeAltText(false); + if (!decorative && altText) { + serialized.accessibilityData = { + type: "Figure", + alt: altText + }; + } + if (this.annotationElementId) { + const changes = this.#hasElementChanged(serialized); + if (changes.isSame) { + return null; + } + if (changes.isSameAltText) { + delete serialized.accessibilityData; + } else { + serialized.accessibilityData.structParent = this._initialData.structParent ?? -1; + } + } + serialized.id = this.annotationElementId; + if (context === null) { + return serialized; + } + context.stamps ||= new Map(); + const area = this.#isSvg ? (serialized.rect[2] - serialized.rect[0]) * (serialized.rect[3] - serialized.rect[1]) : null; + if (!context.stamps.has(this.#bitmapId)) { + context.stamps.set(this.#bitmapId, { + area, + serialized + }); + serialized.bitmap = this.#serializeBitmap(false); + } else if (this.#isSvg) { + const prevData = context.stamps.get(this.#bitmapId); + if (area > prevData.area) { + prevData.area = area; + prevData.serialized.bitmap.close(); + prevData.serialized.bitmap = this.#serializeBitmap(false); + } + } + return serialized; + } + #hasElementChanged(serialized) { + const { + pageIndex, + accessibilityData: { + altText + } + } = this._initialData; + const isSamePageIndex = serialized.pageIndex === pageIndex; + const isSameAltText = (serialized.accessibilityData?.alt || "") === altText; + return { + isSame: !this._hasBeenMoved && !this._hasBeenResized && isSamePageIndex && isSameAltText, + isSameAltText + }; + } + renderAnnotationElement(annotation) { + annotation.updateEdited({ + rect: this.getRect(0, 0) + }); + return null; + } +} + +;// ./src/display/editor/annotation_editor_layer.js + + + + + + + +class AnnotationEditorLayer { + #accessibilityManager; + #allowClick = false; + #annotationLayer = null; + #clickAC = null; + #editorFocusTimeoutId = null; + #editors = new Map(); + #hadPointerDown = false; + #isDisabling = false; + #drawingAC = null; + #textLayer = null; + #textSelectionAC = null; + #uiManager; + static _initialized = false; + static #editorTypes = new Map([FreeTextEditor, InkEditor, StampEditor, HighlightEditor].map(type => [type._editorType, type])); + constructor({ + uiManager, + pageIndex, + div, + structTreeLayer, + accessibilityManager, + annotationLayer, + drawLayer, + textLayer, + viewport, + l10n + }) { + const editorTypes = [...AnnotationEditorLayer.#editorTypes.values()]; + if (!AnnotationEditorLayer._initialized) { + AnnotationEditorLayer._initialized = true; + for (const editorType of editorTypes) { + editorType.initialize(l10n, uiManager); + } + } + uiManager.registerEditorTypes(editorTypes); + this.#uiManager = uiManager; + this.pageIndex = pageIndex; + this.div = div; + this.#accessibilityManager = accessibilityManager; + this.#annotationLayer = annotationLayer; + this.viewport = viewport; + this.#textLayer = textLayer; + this.drawLayer = drawLayer; + this._structTree = structTreeLayer; + this.#uiManager.addLayer(this); + } + get isEmpty() { + return this.#editors.size === 0; + } + get isInvisible() { + return this.isEmpty && this.#uiManager.getMode() === AnnotationEditorType.NONE; + } + updateToolbar(mode) { + this.#uiManager.updateToolbar(mode); + } + updateMode(mode = this.#uiManager.getMode()) { + this.#cleanup(); + switch (mode) { + case AnnotationEditorType.NONE: + this.disableTextSelection(); + this.togglePointerEvents(false); + this.toggleAnnotationLayerPointerEvents(true); + this.disableClick(); + return; + case AnnotationEditorType.INK: + this.disableTextSelection(); + this.togglePointerEvents(true); + this.enableClick(); + break; + case AnnotationEditorType.HIGHLIGHT: + this.enableTextSelection(); + this.togglePointerEvents(false); + this.disableClick(); + break; + default: + this.disableTextSelection(); + this.togglePointerEvents(true); + this.enableClick(); + } + this.toggleAnnotationLayerPointerEvents(false); + const { + classList + } = this.div; + for (const editorType of AnnotationEditorLayer.#editorTypes.values()) { + classList.toggle(`${editorType._type}Editing`, mode === editorType._editorType); + } + this.div.hidden = false; + } + hasTextLayer(textLayer) { + return textLayer === this.#textLayer?.div; + } + setEditingState(isEditing) { + this.#uiManager.setEditingState(isEditing); + } + addCommands(params) { + this.#uiManager.addCommands(params); + } + cleanUndoStack(type) { + this.#uiManager.cleanUndoStack(type); + } + toggleDrawing(enabled = false) { + this.div.classList.toggle("drawing", !enabled); + } + togglePointerEvents(enabled = false) { + this.div.classList.toggle("disabled", !enabled); + } + toggleAnnotationLayerPointerEvents(enabled = false) { + this.#annotationLayer?.div.classList.toggle("disabled", !enabled); + } + async enable() { + this.div.tabIndex = 0; + this.togglePointerEvents(true); + const annotationElementIds = new Set(); + for (const editor of this.#editors.values()) { + editor.enableEditing(); + editor.show(true); + if (editor.annotationElementId) { + this.#uiManager.removeChangedExistingAnnotation(editor); + annotationElementIds.add(editor.annotationElementId); + } + } + if (!this.#annotationLayer) { + return; + } + const editables = this.#annotationLayer.getEditableAnnotations(); + for (const editable of editables) { + editable.hide(); + if (this.#uiManager.isDeletedAnnotationElement(editable.data.id)) { + continue; + } + if (annotationElementIds.has(editable.data.id)) { + continue; + } + const editor = await this.deserialize(editable); + if (!editor) { + continue; + } + this.addOrRebuild(editor); + editor.enableEditing(); + } + } + disable() { + this.#isDisabling = true; + this.div.tabIndex = -1; + this.togglePointerEvents(false); + const changedAnnotations = new Map(); + const resetAnnotations = new Map(); + for (const editor of this.#editors.values()) { + editor.disableEditing(); + if (!editor.annotationElementId) { + continue; + } + if (editor.serialize() !== null) { + changedAnnotations.set(editor.annotationElementId, editor); + continue; + } else { + resetAnnotations.set(editor.annotationElementId, editor); + } + this.getEditableAnnotation(editor.annotationElementId)?.show(); + editor.remove(); + } + if (this.#annotationLayer) { + const editables = this.#annotationLayer.getEditableAnnotations(); + for (const editable of editables) { + const { + id + } = editable.data; + if (this.#uiManager.isDeletedAnnotationElement(id)) { + continue; + } + let editor = resetAnnotations.get(id); + if (editor) { + editor.resetAnnotationElement(editable); + editor.show(false); + editable.show(); + continue; + } + editor = changedAnnotations.get(id); + if (editor) { + this.#uiManager.addChangedExistingAnnotation(editor); + if (editor.renderAnnotationElement(editable)) { + editor.show(false); + } + } + editable.show(); + } + } + this.#cleanup(); + if (this.isEmpty) { + this.div.hidden = true; + } + const { + classList + } = this.div; + for (const editorType of AnnotationEditorLayer.#editorTypes.values()) { + classList.remove(`${editorType._type}Editing`); + } + this.disableTextSelection(); + this.toggleAnnotationLayerPointerEvents(true); + this.#isDisabling = false; + } + getEditableAnnotation(id) { + return this.#annotationLayer?.getEditableAnnotation(id) || null; + } + setActiveEditor(editor) { + const currentActive = this.#uiManager.getActive(); + if (currentActive === editor) { + return; + } + this.#uiManager.setActiveEditor(editor); + } + enableTextSelection() { + this.div.tabIndex = -1; + if (this.#textLayer?.div && !this.#textSelectionAC) { + this.#textSelectionAC = new AbortController(); + const signal = this.#uiManager.combinedSignal(this.#textSelectionAC); + this.#textLayer.div.addEventListener("pointerdown", this.#textLayerPointerDown.bind(this), { + signal + }); + this.#textLayer.div.classList.add("highlighting"); + } + } + disableTextSelection() { + this.div.tabIndex = 0; + if (this.#textLayer?.div && this.#textSelectionAC) { + this.#textSelectionAC.abort(); + this.#textSelectionAC = null; + this.#textLayer.div.classList.remove("highlighting"); + } + } + #textLayerPointerDown(event) { + this.#uiManager.unselectAll(); + const { + target + } = event; + if (target === this.#textLayer.div || (target.getAttribute("role") === "img" || target.classList.contains("endOfContent")) && this.#textLayer.div.contains(target)) { + const { + isMac + } = util_FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + return; + } + this.#uiManager.showAllEditors("highlight", true, true); + this.#textLayer.div.classList.add("free"); + this.toggleDrawing(); + HighlightEditor.startHighlighting(this, this.#uiManager.direction === "ltr", { + target: this.#textLayer.div, + x: event.x, + y: event.y + }); + this.#textLayer.div.addEventListener("pointerup", () => { + this.#textLayer.div.classList.remove("free"); + this.toggleDrawing(true); + }, { + once: true, + signal: this.#uiManager._signal + }); + event.preventDefault(); + } + } + enableClick() { + if (this.#clickAC) { + return; + } + this.#clickAC = new AbortController(); + const signal = this.#uiManager.combinedSignal(this.#clickAC); + this.div.addEventListener("pointerdown", this.pointerdown.bind(this), { + signal + }); + this.div.addEventListener("pointerup", this.pointerup.bind(this), { + signal + }); + } + disableClick() { + this.#clickAC?.abort(); + this.#clickAC = null; + } + attach(editor) { + this.#editors.set(editor.id, editor); + const { + annotationElementId + } = editor; + if (annotationElementId && this.#uiManager.isDeletedAnnotationElement(annotationElementId)) { + this.#uiManager.removeDeletedAnnotationElement(editor); + } + } + detach(editor) { + this.#editors.delete(editor.id); + this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv); + if (!this.#isDisabling && editor.annotationElementId) { + this.#uiManager.addDeletedAnnotationElement(editor); + } + } + remove(editor) { + this.detach(editor); + this.#uiManager.removeEditor(editor); + editor.div.remove(); + editor.isAttachedToDOM = false; + } + changeParent(editor) { + if (editor.parent === this) { + return; + } + if (editor.parent && editor.annotationElementId) { + this.#uiManager.addDeletedAnnotationElement(editor.annotationElementId); + AnnotationEditor.deleteAnnotationElement(editor); + editor.annotationElementId = null; + } + this.attach(editor); + editor.parent?.detach(editor); + editor.setParent(this); + if (editor.div && editor.isAttachedToDOM) { + editor.div.remove(); + this.div.append(editor.div); + } + } + add(editor) { + if (editor.parent === this && editor.isAttachedToDOM) { + return; + } + this.changeParent(editor); + this.#uiManager.addEditor(editor); + this.attach(editor); + if (!editor.isAttachedToDOM) { + const div = editor.render(); + this.div.append(div); + editor.isAttachedToDOM = true; + } + editor.fixAndSetPosition(); + editor.onceAdded(); + this.#uiManager.addToAnnotationStorage(editor); + editor._reportTelemetry(editor.telemetryInitialData); + } + moveEditorInDOM(editor) { + if (!editor.isAttachedToDOM) { + return; + } + const { + activeElement + } = document; + if (editor.div.contains(activeElement) && !this.#editorFocusTimeoutId) { + editor._focusEventsAllowed = false; + this.#editorFocusTimeoutId = setTimeout(() => { + this.#editorFocusTimeoutId = null; + if (!editor.div.contains(document.activeElement)) { + editor.div.addEventListener("focusin", () => { + editor._focusEventsAllowed = true; + }, { + once: true, + signal: this.#uiManager._signal + }); + activeElement.focus(); + } else { + editor._focusEventsAllowed = true; + } + }, 0); + } + editor._structTreeParentId = this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true); + } + addOrRebuild(editor) { + if (editor.needsToBeRebuilt()) { + editor.parent ||= this; + editor.rebuild(); + editor.show(); + } else { + this.add(editor); + } + } + addUndoableEditor(editor) { + const cmd = () => editor._uiManager.rebuild(editor); + const undo = () => { + editor.remove(); + }; + this.addCommands({ + cmd, + undo, + mustExec: false + }); + } + getNextId() { + return this.#uiManager.getId(); + } + get #currentEditorType() { + return AnnotationEditorLayer.#editorTypes.get(this.#uiManager.getMode()); + } + combinedSignal(ac) { + return this.#uiManager.combinedSignal(ac); + } + #createNewEditor(params) { + const editorType = this.#currentEditorType; + return editorType ? new editorType.prototype.constructor(params) : null; + } + canCreateNewEmptyEditor() { + return this.#currentEditorType?.canCreateNewEmptyEditor(); + } + pasteEditor(mode, params) { + this.#uiManager.updateToolbar(mode); + this.#uiManager.updateMode(mode); + const { + offsetX, + offsetY + } = this.#getCenterPoint(); + const id = this.getNextId(); + const editor = this.#createNewEditor({ + parent: this, + id, + x: offsetX, + y: offsetY, + uiManager: this.#uiManager, + isCentered: true, + ...params + }); + if (editor) { + this.add(editor); + } + } + async deserialize(data) { + return (await AnnotationEditorLayer.#editorTypes.get(data.annotationType ?? data.annotationEditorType)?.deserialize(data, this, this.#uiManager)) || null; + } + createAndAddNewEditor(event, isCentered, data = {}) { + const id = this.getNextId(); + const editor = this.#createNewEditor({ + parent: this, + id, + x: event.offsetX, + y: event.offsetY, + uiManager: this.#uiManager, + isCentered, + ...data + }); + if (editor) { + this.add(editor); + } + return editor; + } + #getCenterPoint() { + const { + x, + y, + width, + height + } = this.div.getBoundingClientRect(); + const tlX = Math.max(0, x); + const tlY = Math.max(0, y); + const brX = Math.min(window.innerWidth, x + width); + const brY = Math.min(window.innerHeight, y + height); + const centerX = (tlX + brX) / 2 - x; + const centerY = (tlY + brY) / 2 - y; + const [offsetX, offsetY] = this.viewport.rotation % 180 === 0 ? [centerX, centerY] : [centerY, centerX]; + return { + offsetX, + offsetY + }; + } + addNewEditor() { + this.createAndAddNewEditor(this.#getCenterPoint(), true); + } + setSelected(editor) { + this.#uiManager.setSelected(editor); + } + toggleSelected(editor) { + this.#uiManager.toggleSelected(editor); + } + unselect(editor) { + this.#uiManager.unselect(editor); + } + pointerup(event) { + const { + isMac + } = util_FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + return; + } + if (event.target !== this.div) { + return; + } + if (!this.#hadPointerDown) { + return; + } + this.#hadPointerDown = false; + if (this.#currentEditorType?.isDrawer && this.#currentEditorType.supportMultipleDrawings) { + return; + } + if (!this.#allowClick) { + this.#allowClick = true; + return; + } + if (this.#uiManager.getMode() === AnnotationEditorType.STAMP) { + this.#uiManager.unselectAll(); + return; + } + this.createAndAddNewEditor(event, false); + } + pointerdown(event) { + if (this.#uiManager.getMode() === AnnotationEditorType.HIGHLIGHT) { + this.enableTextSelection(); + } + if (this.#hadPointerDown) { + this.#hadPointerDown = false; + return; + } + const { + isMac + } = util_FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + return; + } + if (event.target !== this.div) { + return; + } + this.#hadPointerDown = true; + if (this.#currentEditorType?.isDrawer) { + this.startDrawingSession(event); + return; + } + const editor = this.#uiManager.getActive(); + this.#allowClick = !editor || editor.isEmpty(); + } + startDrawingSession(event) { + this.div.focus(); + if (this.#drawingAC) { + this.#currentEditorType.startDrawing(this, this.#uiManager, false, event); + return; + } + this.#uiManager.setCurrentDrawingSession(this); + this.#drawingAC = new AbortController(); + const signal = this.#uiManager.combinedSignal(this.#drawingAC); + this.div.addEventListener("blur", ({ + relatedTarget + }) => { + if (relatedTarget && !this.div.contains(relatedTarget)) { + this.commitOrRemove(); + } + }, { + signal + }); + this.#currentEditorType.startDrawing(this, this.#uiManager, false, event); + } + endDrawingSession(isAborted = false) { + if (!this.#drawingAC) { + return null; + } + this.#uiManager.setCurrentDrawingSession(null); + this.#drawingAC.abort(); + this.#drawingAC = null; + return this.#currentEditorType.endDrawing(isAborted); + } + findNewParent(editor, x, y) { + const layer = this.#uiManager.findParent(x, y); + if (layer === null || layer === this) { + return false; + } + layer.changeParent(editor); + return true; + } + commitOrRemove() { + if (this.#drawingAC) { + this.endDrawingSession(); + return true; + } + return false; + } + onScaleChanging() { + if (!this.#drawingAC) { + return; + } + this.#currentEditorType.onScaleChangingWhenDrawing(this); + } + destroy() { + this.commitOrRemove(); + if (this.#uiManager.getActive()?.parent === this) { + this.#uiManager.commitOrRemove(); + this.#uiManager.setActiveEditor(null); + } + if (this.#editorFocusTimeoutId) { + clearTimeout(this.#editorFocusTimeoutId); + this.#editorFocusTimeoutId = null; + } + for (const editor of this.#editors.values()) { + this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv); + editor.setParent(null); + editor.isAttachedToDOM = false; + editor.div.remove(); + } + this.div = null; + this.#editors.clear(); + this.#uiManager.removeLayer(this); + } + #cleanup() { + for (const editor of this.#editors.values()) { + if (editor.isEmpty()) { + editor.remove(); + } + } + } + render({ + viewport + }) { + this.viewport = viewport; + setLayerDimensions(this.div, viewport); + for (const editor of this.#uiManager.getEditors(this.pageIndex)) { + this.add(editor); + editor.rebuild(); + } + this.updateMode(); + } + update({ + viewport + }) { + this.#uiManager.commitOrRemove(); + this.#cleanup(); + const oldRotation = this.viewport.rotation; + const rotation = viewport.rotation; + this.viewport = viewport; + setLayerDimensions(this.div, { + rotation + }); + if (oldRotation !== rotation) { + for (const editor of this.#editors.values()) { + editor.rotate(rotation); + } + } + } + get pageDimensions() { + const { + pageWidth, + pageHeight + } = this.viewport.rawDims; + return [pageWidth, pageHeight]; + } + get scale() { + return this.#uiManager.viewParameters.realScale; + } +} + +;// ./src/display/draw_layer.js + + +class DrawLayer { + #parent = null; + #id = 0; + #mapping = new Map(); + #toUpdate = new Map(); + constructor({ + pageIndex + }) { + this.pageIndex = pageIndex; + } + setParent(parent) { + if (!this.#parent) { + this.#parent = parent; + return; + } + if (this.#parent !== parent) { + if (this.#mapping.size > 0) { + for (const root of this.#mapping.values()) { + root.remove(); + parent.append(root); + } + } + this.#parent = parent; + } + } + static get _svgFactory() { + return shadow(this, "_svgFactory", new DOMSVGFactory()); + } + static #setBox(element, [x, y, width, height]) { + const { + style + } = element; + style.top = `${100 * y}%`; + style.left = `${100 * x}%`; + style.width = `${100 * width}%`; + style.height = `${100 * height}%`; + } + #createSVG() { + const svg = DrawLayer._svgFactory.create(1, 1, true); + this.#parent.append(svg); + svg.setAttribute("aria-hidden", true); + return svg; + } + #createClipPath(defs, pathId) { + const clipPath = DrawLayer._svgFactory.createElement("clipPath"); + defs.append(clipPath); + const clipPathId = `clip_${pathId}`; + clipPath.setAttribute("id", clipPathId); + clipPath.setAttribute("clipPathUnits", "objectBoundingBox"); + const clipPathUse = DrawLayer._svgFactory.createElement("use"); + clipPath.append(clipPathUse); + clipPathUse.setAttribute("href", `#${pathId}`); + clipPathUse.classList.add("clip"); + return clipPathId; + } + #updateProperties(element, properties) { + for (const [key, value] of Object.entries(properties)) { + if (value === null) { + element.removeAttribute(key); + } else { + element.setAttribute(key, value); + } + } + } + draw(properties, isPathUpdatable = false, hasClip = false) { + const id = this.#id++; + const root = this.#createSVG(); + const defs = DrawLayer._svgFactory.createElement("defs"); + root.append(defs); + const path = DrawLayer._svgFactory.createElement("path"); + defs.append(path); + const pathId = `path_p${this.pageIndex}_${id}`; + path.setAttribute("id", pathId); + path.setAttribute("vector-effect", "non-scaling-stroke"); + if (isPathUpdatable) { + this.#toUpdate.set(id, path); + } + const clipPathId = hasClip ? this.#createClipPath(defs, pathId) : null; + const use = DrawLayer._svgFactory.createElement("use"); + root.append(use); + use.setAttribute("href", `#${pathId}`); + this.updateProperties(root, properties); + this.#mapping.set(id, root); + return { + id, + clipPathId: `url(#${clipPathId})` + }; + } + drawOutline(properties, mustRemoveSelfIntersections) { + const id = this.#id++; + const root = this.#createSVG(); + const defs = DrawLayer._svgFactory.createElement("defs"); + root.append(defs); + const path = DrawLayer._svgFactory.createElement("path"); + defs.append(path); + const pathId = `path_p${this.pageIndex}_${id}`; + path.setAttribute("id", pathId); + path.setAttribute("vector-effect", "non-scaling-stroke"); + let maskId; + if (mustRemoveSelfIntersections) { + const mask = DrawLayer._svgFactory.createElement("mask"); + defs.append(mask); + maskId = `mask_p${this.pageIndex}_${id}`; + mask.setAttribute("id", maskId); + mask.setAttribute("maskUnits", "objectBoundingBox"); + const rect = DrawLayer._svgFactory.createElement("rect"); + mask.append(rect); + rect.setAttribute("width", "1"); + rect.setAttribute("height", "1"); + rect.setAttribute("fill", "white"); + const use = DrawLayer._svgFactory.createElement("use"); + mask.append(use); + use.setAttribute("href", `#${pathId}`); + use.setAttribute("stroke", "none"); + use.setAttribute("fill", "black"); + use.setAttribute("fill-rule", "nonzero"); + use.classList.add("mask"); + } + const use1 = DrawLayer._svgFactory.createElement("use"); + root.append(use1); + use1.setAttribute("href", `#${pathId}`); + if (maskId) { + use1.setAttribute("mask", `url(#${maskId})`); + } + const use2 = use1.cloneNode(); + root.append(use2); + use1.classList.add("mainOutline"); + use2.classList.add("secondaryOutline"); + this.updateProperties(root, properties); + this.#mapping.set(id, root); + return id; + } + finalizeDraw(id, properties) { + this.#toUpdate.delete(id); + this.updateProperties(id, properties); + } + updateProperties(elementOrId, properties) { + if (!properties) { + return; + } + const { + root, + bbox, + rootClass, + path + } = properties; + const element = typeof elementOrId === "number" ? this.#mapping.get(elementOrId) : elementOrId; + if (!element) { + return; + } + if (root) { + this.#updateProperties(element, root); + } + if (bbox) { + DrawLayer.#setBox(element, bbox); + } + if (rootClass) { + const { + classList + } = element; + for (const [className, value] of Object.entries(rootClass)) { + classList.toggle(className, value); + } + } + if (path) { + const defs = element.firstChild; + const pathElement = defs.firstChild; + this.#updateProperties(pathElement, path); + } + } + updateParent(id, layer) { + if (layer === this) { + return; + } + const root = this.#mapping.get(id); + if (!root) { + return; + } + layer.#parent.append(root); + this.#mapping.delete(id); + layer.#mapping.set(id, root); + } + remove(id) { + this.#toUpdate.delete(id); + if (this.#parent === null) { + return; + } + this.#mapping.get(id).remove(); + this.#mapping.delete(id); + } + destroy() { + this.#parent = null; + for (const root of this.#mapping.values()) { + root.remove(); + } + this.#mapping.clear(); + this.#toUpdate.clear(); + } +} + +;// ./src/pdf.js + + + + + + + + + + + + + +const pdfjsVersion = "4.9.155"; +const pdfjsBuild = "a4eb8407c"; +{ + globalThis.pdfjsTestingUtils = { + HighlightOutliner: HighlightOutliner + }; +} + +var __webpack_exports__AbortException = __webpack_exports__.AbortException; +var __webpack_exports__AnnotationEditorLayer = __webpack_exports__.AnnotationEditorLayer; +var __webpack_exports__AnnotationEditorParamsType = __webpack_exports__.AnnotationEditorParamsType; +var __webpack_exports__AnnotationEditorType = __webpack_exports__.AnnotationEditorType; +var __webpack_exports__AnnotationEditorUIManager = __webpack_exports__.AnnotationEditorUIManager; +var __webpack_exports__AnnotationLayer = __webpack_exports__.AnnotationLayer; +var __webpack_exports__AnnotationMode = __webpack_exports__.AnnotationMode; +var __webpack_exports__ColorPicker = __webpack_exports__.ColorPicker; +var __webpack_exports__DOMSVGFactory = __webpack_exports__.DOMSVGFactory; +var __webpack_exports__DrawLayer = __webpack_exports__.DrawLayer; +var __webpack_exports__FeatureTest = __webpack_exports__.FeatureTest; +var __webpack_exports__GlobalWorkerOptions = __webpack_exports__.GlobalWorkerOptions; +var __webpack_exports__ImageKind = __webpack_exports__.ImageKind; +var __webpack_exports__InvalidPDFException = __webpack_exports__.InvalidPDFException; +var __webpack_exports__MissingPDFException = __webpack_exports__.MissingPDFException; +var __webpack_exports__OPS = __webpack_exports__.OPS; +var __webpack_exports__OutputScale = __webpack_exports__.OutputScale; +var __webpack_exports__PDFDataRangeTransport = __webpack_exports__.PDFDataRangeTransport; +var __webpack_exports__PDFDateString = __webpack_exports__.PDFDateString; +var __webpack_exports__PDFWorker = __webpack_exports__.PDFWorker; +var __webpack_exports__PasswordResponses = __webpack_exports__.PasswordResponses; +var __webpack_exports__PermissionFlag = __webpack_exports__.PermissionFlag; +var __webpack_exports__PixelsPerInch = __webpack_exports__.PixelsPerInch; +var __webpack_exports__RenderingCancelledException = __webpack_exports__.RenderingCancelledException; +var __webpack_exports__TextLayer = __webpack_exports__.TextLayer; +var __webpack_exports__UnexpectedResponseException = __webpack_exports__.UnexpectedResponseException; +var __webpack_exports__Util = __webpack_exports__.Util; +var __webpack_exports__VerbosityLevel = __webpack_exports__.VerbosityLevel; +var __webpack_exports__XfaLayer = __webpack_exports__.XfaLayer; +var __webpack_exports__build = __webpack_exports__.build; +var __webpack_exports__createValidAbsoluteUrl = __webpack_exports__.createValidAbsoluteUrl; +var __webpack_exports__fetchData = __webpack_exports__.fetchData; +var __webpack_exports__getDocument = __webpack_exports__.getDocument; +var __webpack_exports__getFilenameFromUrl = __webpack_exports__.getFilenameFromUrl; +var __webpack_exports__getPdfFilenameFromUrl = __webpack_exports__.getPdfFilenameFromUrl; +var __webpack_exports__getXfaPageViewport = __webpack_exports__.getXfaPageViewport; +var __webpack_exports__isDataScheme = __webpack_exports__.isDataScheme; +var __webpack_exports__isPdfFile = __webpack_exports__.isPdfFile; +var __webpack_exports__noContextMenu = __webpack_exports__.noContextMenu; +var __webpack_exports__normalizeUnicode = __webpack_exports__.normalizeUnicode; +var __webpack_exports__setLayerDimensions = __webpack_exports__.setLayerDimensions; +var __webpack_exports__shadow = __webpack_exports__.shadow; +var __webpack_exports__stopEvent = __webpack_exports__.stopEvent; +var __webpack_exports__version = __webpack_exports__.version; +export { __webpack_exports__AbortException as AbortException, __webpack_exports__AnnotationEditorLayer as AnnotationEditorLayer, __webpack_exports__AnnotationEditorParamsType as AnnotationEditorParamsType, __webpack_exports__AnnotationEditorType as AnnotationEditorType, __webpack_exports__AnnotationEditorUIManager as AnnotationEditorUIManager, __webpack_exports__AnnotationLayer as AnnotationLayer, __webpack_exports__AnnotationMode as AnnotationMode, __webpack_exports__ColorPicker as ColorPicker, __webpack_exports__DOMSVGFactory as DOMSVGFactory, __webpack_exports__DrawLayer as DrawLayer, __webpack_exports__FeatureTest as FeatureTest, __webpack_exports__GlobalWorkerOptions as GlobalWorkerOptions, __webpack_exports__ImageKind as ImageKind, __webpack_exports__InvalidPDFException as InvalidPDFException, __webpack_exports__MissingPDFException as MissingPDFException, __webpack_exports__OPS as OPS, __webpack_exports__OutputScale as OutputScale, __webpack_exports__PDFDataRangeTransport as PDFDataRangeTransport, __webpack_exports__PDFDateString as PDFDateString, __webpack_exports__PDFWorker as PDFWorker, __webpack_exports__PasswordResponses as PasswordResponses, __webpack_exports__PermissionFlag as PermissionFlag, __webpack_exports__PixelsPerInch as PixelsPerInch, __webpack_exports__RenderingCancelledException as RenderingCancelledException, __webpack_exports__TextLayer as TextLayer, __webpack_exports__UnexpectedResponseException as UnexpectedResponseException, __webpack_exports__Util as Util, __webpack_exports__VerbosityLevel as VerbosityLevel, __webpack_exports__XfaLayer as XfaLayer, __webpack_exports__build as build, __webpack_exports__createValidAbsoluteUrl as createValidAbsoluteUrl, __webpack_exports__fetchData as fetchData, __webpack_exports__getDocument as getDocument, __webpack_exports__getFilenameFromUrl as getFilenameFromUrl, __webpack_exports__getPdfFilenameFromUrl as getPdfFilenameFromUrl, __webpack_exports__getXfaPageViewport as getXfaPageViewport, __webpack_exports__isDataScheme as isDataScheme, __webpack_exports__isPdfFile as isPdfFile, __webpack_exports__noContextMenu as noContextMenu, __webpack_exports__normalizeUnicode as normalizeUnicode, __webpack_exports__setLayerDimensions as setLayerDimensions, __webpack_exports__shadow as shadow, __webpack_exports__stopEvent as stopEvent, __webpack_exports__version as version }; + +//# sourceMappingURL=pdf.mjs.map \ No newline at end of file diff --git a/pdfjs/build/pdf.mjs.map b/pdfjs/build/pdf.mjs.map new file mode 100644 index 0000000..56ee54c --- /dev/null +++ b/pdfjs/build/pdf.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"pdf.mjs","mappings":";;;;;;;;;;;;;;;;;;;;;;SAAA;SACA;;;;;UCDA;UACA;UACA;UACA;UACA,yCAAyC,wCAAwC;UACjF;UACA;UACA;;;;;UCPA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACoBA,MAAMA,QAAQ,GAEZ,OAAOC,OAAO,KAAK,QAAQ,IAC3BA,OAAO,GAAG,EAAE,KAAK,kBAAkB,IACnC,CAACA,OAAO,CAACC,QAAQ,CAACC,EAAE,IACpB,EAAEF,OAAO,CAACC,QAAQ,CAACE,QAAQ,IAAIH,OAAO,CAACI,IAAI,IAAIJ,OAAO,CAACI,IAAI,KAAK,SAAS,CAAC;AAE5E,MAAMC,eAAe,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;AAC1C,MAAMC,oBAAoB,GAAG,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,E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,CAAClG,MAAM,CAAC,CAAC;IAC9B,IAAI,CAAC,CAAC6jG,OAAO,CAACv/F,MAAM,CAAC4B,EAAE,CAAC;EAC1B;EAEArB,OAAOA,CAAA,EAAG;IACR,IAAI,CAAC,CAACY,MAAM,GAAG,IAAI;IACnB,KAAK,MAAMqpE,IAAI,IAAI,IAAI,CAAC,CAAC+0B,OAAO,CAAChyF,MAAM,CAAC,CAAC,EAAE;MACzCi9D,IAAI,CAAC9uE,MAAM,CAAC,CAAC;IACf;IACA,IAAI,CAAC,CAAC6jG,OAAO,CAAC/xF,KAAK,CAAC,CAAC;IACrB,IAAI,CAAC,CAACgyF,QAAQ,CAAChyF,KAAK,CAAC,CAAC;EACxB;AACF;;;AC5M0B;AAOA;AAeU;AACgD;AACd;AACN;AACD;AACN;AACL;AACc;AACQ;AACtB;AACF;AAGlD,MAAMqzF,YAAY,GACkB,SAAwC;AAE5E,MAAMC,UAAU,GACoB,WAAsC;AAEE;EAC1E91G,UAAU,CAAC+1G,iBAAiB,GAAG;IAC7BnY,iBAAiBA,EAAAA,iBAAAA;EACnB,CAAC;AACH","sources":["webpack://pdf.js/webpack/bootstrap","webpack://pdf.js/webpack/runtime/define property getters","webpack://pdf.js/webpack/runtime/hasOwnProperty shorthand","webpack://pdf.js/./src/shared/util.js","webpack://pdf.js/./src/display/display_utils.js","webpack://pdf.js/./src/display/editor/toolbar.js","webpack://pdf.js/./src/display/editor/tools.js","webpack://pdf.js/./src/display/editor/alt_text.js","webpack://pdf.js/./src/display/editor/editor.js","webpack://pdf.js/./src/shared/murmurhash3.js","webpack://pdf.js/./src/display/annotation_storage.js","webpack://pdf.js/./src/display/font_loader.js","webpack://pdf.js/./src/display/canvas_factory.js","webpack://pdf.js/./src/display/cmap_reader_factory.js","webpack://pdf.js/./src/display/filter_factory.js","webpack://pdf.js/./src/display/standard_fontdata_factory.js","webpack://pdf.js/./src/display/node_utils.js","webpack://pdf.js/./src/display/pattern_helper.js","webpack://pdf.js/./src/shared/image_utils.js","webpack://pdf.js/./src/display/canvas.js","webpack://pdf.js/./src/display/worker_options.js","webpack://pdf.js/./src/shared/message_handler.js","webpack://pdf.js/./src/display/metadata.js","webpack://pdf.js/./src/display/optional_content_config.js","webpack://pdf.js/./src/display/transport_stream.js","webpack://pdf.js/./src/display/content_disposition.js","webpack://pdf.js/./src/display/network_utils.js","webpack://pdf.js/./src/display/fetch_stream.js","webpack://pdf.js/./src/display/network.js","webpack://pdf.js/./src/display/node_stream.js","webpack://pdf.js/./src/display/text_layer.js","webpack://pdf.js/./src/display/xfa_text.js","webpack://pdf.js/./src/display/api.js","webpack://pdf.js/./src/shared/scripting_utils.js","webpack://pdf.js/./src/display/svg_factory.js","webpack://pdf.js/./src/display/xfa_layer.js","webpack://pdf.js/./src/display/annotation_layer.js","webpack://pdf.js/./src/display/editor/freetext.js","webpack://pdf.js/./src/display/editor/drawers/outline.js","webpack://pdf.js/./src/display/editor/drawers/freedraw.js","webpack://pdf.js/./src/display/editor/drawers/highlight.js","webpack://pdf.js/./src/display/editor/color_picker.js","webpack://pdf.js/./src/display/editor/highlight.js","webpack://pdf.js/./src/display/editor/draw.js","webpack://pdf.js/./src/display/editor/drawers/inkdraw.js","webpack://pdf.js/./src/display/editor/ink.js","webpack://pdf.js/./src/display/editor/stamp.js","webpack://pdf.js/./src/display/editor/annotation_editor_layer.js","webpack://pdf.js/./src/display/draw_layer.js","webpack://pdf.js/./src/pdf.js"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/* globals process */\n\n// NW.js / Electron is a browser context, but copies some Node.js objects; see\n// http://docs.nwjs.io/en/latest/For%20Users/Advanced/JavaScript%20Contexts%20in%20NW.js/#access-nodejs-and-nwjs-api-in-browser-context\n// https://www.electronjs.org/docs/api/process#processversionselectron-readonly\n// https://www.electronjs.org/docs/api/process#processtype-readonly\nconst isNodeJS =\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) &&\n typeof process === \"object\" &&\n process + \"\" === \"[object process]\" &&\n !process.versions.nw &&\n !(process.versions.electron && process.type && process.type !== \"browser\");\n\nconst IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];\nconst FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];\n\nconst MAX_IMAGE_SIZE_TO_CACHE = 10e6; // Ten megabytes.\n\n// Represent the percentage of the height of a single-line field over\n// the font size. Acrobat seems to use this value.\nconst LINE_FACTOR = 1.35;\nconst LINE_DESCENT_FACTOR = 0.35;\nconst BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;\n\n/**\n * Refer to the `WorkerTransport.getRenderingIntent`-method in the API, to see\n * how these flags are being used:\n * - ANY, DISPLAY, and PRINT are the normal rendering intents, note the\n * `PDFPageProxy.{render, getOperatorList, getAnnotations}`-methods.\n * - SAVE is used, on the worker-thread, when saving modified annotations.\n * - ANNOTATIONS_FORMS, ANNOTATIONS_STORAGE, ANNOTATIONS_DISABLE control which\n * annotations are rendered onto the canvas (i.e. by being included in the\n * operatorList), note the `PDFPageProxy.{render, getOperatorList}`-methods\n * and their `annotationMode`-option.\n * - IS_EDITING is used when editing is active in the viewer.\n * - OPLIST is used with the `PDFPageProxy.getOperatorList`-method, note the\n * `OperatorList`-constructor (on the worker-thread).\n */\nconst RenderingIntentFlag = {\n ANY: 0x01,\n DISPLAY: 0x02,\n PRINT: 0x04,\n SAVE: 0x08,\n ANNOTATIONS_FORMS: 0x10,\n ANNOTATIONS_STORAGE: 0x20,\n ANNOTATIONS_DISABLE: 0x40,\n IS_EDITING: 0x80,\n OPLIST: 0x100,\n};\n\nconst AnnotationMode = {\n DISABLE: 0,\n ENABLE: 1,\n ENABLE_FORMS: 2,\n ENABLE_STORAGE: 3,\n};\n\nconst AnnotationEditorPrefix = \"pdfjs_internal_editor_\";\n\nconst AnnotationEditorType = {\n DISABLE: -1,\n NONE: 0,\n FREETEXT: 3,\n HIGHLIGHT: 9,\n STAMP: 13,\n INK: 15,\n};\n\nconst AnnotationEditorParamsType = {\n RESIZE: 1,\n CREATE: 2,\n FREETEXT_SIZE: 11,\n FREETEXT_COLOR: 12,\n FREETEXT_OPACITY: 13,\n INK_COLOR: 21,\n INK_THICKNESS: 22,\n INK_OPACITY: 23,\n HIGHLIGHT_COLOR: 31,\n HIGHLIGHT_DEFAULT_COLOR: 32,\n HIGHLIGHT_THICKNESS: 33,\n HIGHLIGHT_FREE: 34,\n HIGHLIGHT_SHOW_ALL: 35,\n DRAW_STEP: 41,\n};\n\n// Permission flags from Table 22, Section 7.6.3.2 of the PDF specification.\nconst PermissionFlag = {\n PRINT: 0x04,\n MODIFY_CONTENTS: 0x08,\n COPY: 0x10,\n MODIFY_ANNOTATIONS: 0x20,\n FILL_INTERACTIVE_FORMS: 0x100,\n COPY_FOR_ACCESSIBILITY: 0x200,\n ASSEMBLE: 0x400,\n PRINT_HIGH_QUALITY: 0x800,\n};\n\nconst TextRenderingMode = {\n FILL: 0,\n STROKE: 1,\n FILL_STROKE: 2,\n INVISIBLE: 3,\n FILL_ADD_TO_PATH: 4,\n STROKE_ADD_TO_PATH: 5,\n FILL_STROKE_ADD_TO_PATH: 6,\n ADD_TO_PATH: 7,\n FILL_STROKE_MASK: 3,\n ADD_TO_PATH_FLAG: 4,\n};\n\nconst ImageKind = {\n GRAYSCALE_1BPP: 1,\n RGB_24BPP: 2,\n RGBA_32BPP: 3,\n};\n\nconst AnnotationType = {\n TEXT: 1,\n LINK: 2,\n FREETEXT: 3,\n LINE: 4,\n SQUARE: 5,\n CIRCLE: 6,\n POLYGON: 7,\n POLYLINE: 8,\n HIGHLIGHT: 9,\n UNDERLINE: 10,\n SQUIGGLY: 11,\n STRIKEOUT: 12,\n STAMP: 13,\n CARET: 14,\n INK: 15,\n POPUP: 16,\n FILEATTACHMENT: 17,\n SOUND: 18,\n MOVIE: 19,\n WIDGET: 20,\n SCREEN: 21,\n PRINTERMARK: 22,\n TRAPNET: 23,\n WATERMARK: 24,\n THREED: 25,\n REDACT: 26,\n};\n\nconst AnnotationReplyType = {\n GROUP: \"Group\",\n REPLY: \"R\",\n};\n\nconst AnnotationFlag = {\n INVISIBLE: 0x01,\n HIDDEN: 0x02,\n PRINT: 0x04,\n NOZOOM: 0x08,\n NOROTATE: 0x10,\n NOVIEW: 0x20,\n READONLY: 0x40,\n LOCKED: 0x80,\n TOGGLENOVIEW: 0x100,\n LOCKEDCONTENTS: 0x200,\n};\n\nconst AnnotationFieldFlag = {\n READONLY: 0x0000001,\n REQUIRED: 0x0000002,\n NOEXPORT: 0x0000004,\n MULTILINE: 0x0001000,\n PASSWORD: 0x0002000,\n NOTOGGLETOOFF: 0x0004000,\n RADIO: 0x0008000,\n PUSHBUTTON: 0x0010000,\n COMBO: 0x0020000,\n EDIT: 0x0040000,\n SORT: 0x0080000,\n FILESELECT: 0x0100000,\n MULTISELECT: 0x0200000,\n DONOTSPELLCHECK: 0x0400000,\n DONOTSCROLL: 0x0800000,\n COMB: 0x1000000,\n RICHTEXT: 0x2000000,\n RADIOSINUNISON: 0x2000000,\n COMMITONSELCHANGE: 0x4000000,\n};\n\nconst AnnotationBorderStyleType = {\n SOLID: 1,\n DASHED: 2,\n BEVELED: 3,\n INSET: 4,\n UNDERLINE: 5,\n};\n\nconst AnnotationActionEventType = {\n E: \"Mouse Enter\",\n X: \"Mouse Exit\",\n D: \"Mouse Down\",\n U: \"Mouse Up\",\n Fo: \"Focus\",\n Bl: \"Blur\",\n PO: \"PageOpen\",\n PC: \"PageClose\",\n PV: \"PageVisible\",\n PI: \"PageInvisible\",\n K: \"Keystroke\",\n F: \"Format\",\n V: \"Validate\",\n C: \"Calculate\",\n};\n\nconst DocumentActionEventType = {\n WC: \"WillClose\",\n WS: \"WillSave\",\n DS: \"DidSave\",\n WP: \"WillPrint\",\n DP: \"DidPrint\",\n};\n\nconst PageActionEventType = {\n O: \"PageOpen\",\n C: \"PageClose\",\n};\n\nconst VerbosityLevel = {\n ERRORS: 0,\n WARNINGS: 1,\n INFOS: 5,\n};\n\n// All the possible operations for an operator list.\nconst OPS = {\n // Intentionally start from 1 so it is easy to spot bad operators that will be\n // 0's.\n // PLEASE NOTE: We purposely keep any removed operators commented out, since\n // re-numbering the list would risk breaking third-party users.\n dependency: 1,\n setLineWidth: 2,\n setLineCap: 3,\n setLineJoin: 4,\n setMiterLimit: 5,\n setDash: 6,\n setRenderingIntent: 7,\n setFlatness: 8,\n setGState: 9,\n save: 10,\n restore: 11,\n transform: 12,\n moveTo: 13,\n lineTo: 14,\n curveTo: 15,\n curveTo2: 16,\n curveTo3: 17,\n closePath: 18,\n rectangle: 19,\n stroke: 20,\n closeStroke: 21,\n fill: 22,\n eoFill: 23,\n fillStroke: 24,\n eoFillStroke: 25,\n closeFillStroke: 26,\n closeEOFillStroke: 27,\n endPath: 28,\n clip: 29,\n eoClip: 30,\n beginText: 31,\n endText: 32,\n setCharSpacing: 33,\n setWordSpacing: 34,\n setHScale: 35,\n setLeading: 36,\n setFont: 37,\n setTextRenderingMode: 38,\n setTextRise: 39,\n moveText: 40,\n setLeadingMoveText: 41,\n setTextMatrix: 42,\n nextLine: 43,\n showText: 44,\n showSpacedText: 45,\n nextLineShowText: 46,\n nextLineSetSpacingShowText: 47,\n setCharWidth: 48,\n setCharWidthAndBounds: 49,\n setStrokeColorSpace: 50,\n setFillColorSpace: 51,\n setStrokeColor: 52,\n setStrokeColorN: 53,\n setFillColor: 54,\n setFillColorN: 55,\n setStrokeGray: 56,\n setFillGray: 57,\n setStrokeRGBColor: 58,\n setFillRGBColor: 59,\n setStrokeCMYKColor: 60,\n setFillCMYKColor: 61,\n shadingFill: 62,\n beginInlineImage: 63,\n beginImageData: 64,\n endInlineImage: 65,\n paintXObject: 66,\n markPoint: 67,\n markPointProps: 68,\n beginMarkedContent: 69,\n beginMarkedContentProps: 70,\n endMarkedContent: 71,\n beginCompat: 72,\n endCompat: 73,\n paintFormXObjectBegin: 74,\n paintFormXObjectEnd: 75,\n beginGroup: 76,\n endGroup: 77,\n // beginAnnotations: 78,\n // endAnnotations: 79,\n beginAnnotation: 80,\n endAnnotation: 81,\n // paintJpegXObject: 82,\n paintImageMaskXObject: 83,\n paintImageMaskXObjectGroup: 84,\n paintImageXObject: 85,\n paintInlineImageXObject: 86,\n paintInlineImageXObjectGroup: 87,\n paintImageXObjectRepeat: 88,\n paintImageMaskXObjectRepeat: 89,\n paintSolidColorImageMask: 90,\n constructPath: 91,\n setStrokeTransparent: 92,\n setFillTransparent: 93,\n};\n\nconst PasswordResponses = {\n NEED_PASSWORD: 1,\n INCORRECT_PASSWORD: 2,\n};\n\nlet verbosity = VerbosityLevel.WARNINGS;\n\nfunction setVerbosityLevel(level) {\n if (Number.isInteger(level)) {\n verbosity = level;\n }\n}\n\nfunction getVerbosityLevel() {\n return verbosity;\n}\n\n// A notice for devs. These are good for things that are helpful to devs, such\n// as warning that Workers were disabled, which is important to devs but not\n// end users.\nfunction info(msg) {\n if (verbosity >= VerbosityLevel.INFOS) {\n // eslint-disable-next-line no-console\n console.log(`Info: ${msg}`);\n }\n}\n\n// Non-fatal warnings.\nfunction warn(msg) {\n if (verbosity >= VerbosityLevel.WARNINGS) {\n // eslint-disable-next-line no-console\n console.log(`Warning: ${msg}`);\n }\n}\n\nfunction unreachable(msg) {\n throw new Error(msg);\n}\n\nfunction assert(cond, msg) {\n if (!cond) {\n unreachable(msg);\n }\n}\n\n// Checks if URLs use one of the allowed protocols, e.g. to avoid XSS.\nfunction _isValidProtocol(url) {\n switch (url?.protocol) {\n case \"http:\":\n case \"https:\":\n case \"ftp:\":\n case \"mailto:\":\n case \"tel:\":\n return true;\n default:\n return false;\n }\n}\n\n/**\n * Attempts to create a valid absolute URL.\n *\n * @param {URL|string} url - An absolute, or relative, URL.\n * @param {URL|string} [baseUrl] - An absolute URL.\n * @param {Object} [options]\n * @returns Either a valid {URL}, or `null` otherwise.\n */\nfunction createValidAbsoluteUrl(url, baseUrl = null, options = null) {\n if (!url) {\n return null;\n }\n try {\n if (options && typeof url === \"string\") {\n // Let URLs beginning with \"www.\" default to using the \"http://\" protocol.\n if (options.addDefaultProtocol && url.startsWith(\"www.\")) {\n const dots = url.match(/\\./g);\n // Avoid accidentally matching a *relative* URL pointing to a file named\n // e.g. \"www.pdf\" or similar.\n if (dots?.length >= 2) {\n url = `http://${url}`;\n }\n }\n\n // According to ISO 32000-1:2008, section 12.6.4.7, URIs should be encoded\n // in 7-bit ASCII. Some bad PDFs use UTF-8 encoding; see bug 1122280.\n if (options.tryConvertEncoding) {\n try {\n url = stringToUTF8String(url);\n } catch {}\n }\n }\n\n const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);\n if (_isValidProtocol(absoluteUrl)) {\n return absoluteUrl;\n }\n } catch {\n /* `new URL()` will throw on incorrect data. */\n }\n return null;\n}\n\nfunction shadow(obj, prop, value, nonSerializable = false) {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n assert(\n prop in obj,\n `shadow: Property \"${prop && prop.toString()}\" not found in object.`\n );\n }\n Object.defineProperty(obj, prop, {\n value,\n enumerable: !nonSerializable,\n configurable: true,\n writable: false,\n });\n return value;\n}\n\n/**\n * @type {any}\n */\nconst BaseException = (function BaseExceptionClosure() {\n // eslint-disable-next-line no-shadow\n function BaseException(message, name) {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === BaseException\n ) {\n unreachable(\"Cannot initialize BaseException.\");\n }\n this.message = message;\n this.name = name;\n }\n BaseException.prototype = new Error();\n BaseException.constructor = BaseException;\n\n return BaseException;\n})();\n\nclass PasswordException extends BaseException {\n constructor(msg, code) {\n super(msg, \"PasswordException\");\n this.code = code;\n }\n}\n\nclass UnknownErrorException extends BaseException {\n constructor(msg, details) {\n super(msg, \"UnknownErrorException\");\n this.details = details;\n }\n}\n\nclass InvalidPDFException extends BaseException {\n constructor(msg) {\n super(msg, \"InvalidPDFException\");\n }\n}\n\nclass MissingPDFException extends BaseException {\n constructor(msg) {\n super(msg, \"MissingPDFException\");\n }\n}\n\nclass UnexpectedResponseException extends BaseException {\n constructor(msg, status) {\n super(msg, \"UnexpectedResponseException\");\n this.status = status;\n }\n}\n\n/**\n * Error caused during parsing PDF data.\n */\nclass FormatError extends BaseException {\n constructor(msg) {\n super(msg, \"FormatError\");\n }\n}\n\n/**\n * Error used to indicate task cancellation.\n */\nclass AbortException extends BaseException {\n constructor(msg) {\n super(msg, \"AbortException\");\n }\n}\n\nfunction bytesToString(bytes) {\n if (typeof bytes !== \"object\" || bytes?.length === undefined) {\n unreachable(\"Invalid argument for bytesToString\");\n }\n const length = bytes.length;\n const MAX_ARGUMENT_COUNT = 8192;\n if (length < MAX_ARGUMENT_COUNT) {\n return String.fromCharCode.apply(null, bytes);\n }\n const strBuf = [];\n for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {\n const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);\n const chunk = bytes.subarray(i, chunkEnd);\n strBuf.push(String.fromCharCode.apply(null, chunk));\n }\n return strBuf.join(\"\");\n}\n\nfunction stringToBytes(str) {\n if (typeof str !== \"string\") {\n unreachable(\"Invalid argument for stringToBytes\");\n }\n const length = str.length;\n const bytes = new Uint8Array(length);\n for (let i = 0; i < length; ++i) {\n bytes[i] = str.charCodeAt(i) & 0xff;\n }\n return bytes;\n}\n\nfunction string32(value) {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n assert(\n typeof value === \"number\" && Math.abs(value) < 2 ** 32,\n `string32: Unexpected input \"${value}\".`\n );\n }\n return String.fromCharCode(\n (value >> 24) & 0xff,\n (value >> 16) & 0xff,\n (value >> 8) & 0xff,\n value & 0xff\n );\n}\n\nfunction objectSize(obj) {\n return Object.keys(obj).length;\n}\n\n// Ensure that the returned Object has a `null` prototype; hence why\n// `Object.fromEntries(...)` is not used.\nfunction objectFromMap(map) {\n const obj = Object.create(null);\n for (const [key, value] of map) {\n obj[key] = value;\n }\n return obj;\n}\n\n// Checks the endianness of the platform.\nfunction isLittleEndian() {\n const buffer8 = new Uint8Array(4);\n buffer8[0] = 1;\n const view32 = new Uint32Array(buffer8.buffer, 0, 1);\n return view32[0] === 1;\n}\n\n// Checks if it's possible to eval JS expressions.\nfunction isEvalSupported() {\n try {\n new Function(\"\"); // eslint-disable-line no-new, no-new-func\n return true;\n } catch {\n return false;\n }\n}\n\nclass FeatureTest {\n static get isLittleEndian() {\n return shadow(this, \"isLittleEndian\", isLittleEndian());\n }\n\n static get isEvalSupported() {\n return shadow(this, \"isEvalSupported\", isEvalSupported());\n }\n\n static get isOffscreenCanvasSupported() {\n return shadow(\n this,\n \"isOffscreenCanvasSupported\",\n typeof OffscreenCanvas !== \"undefined\"\n );\n }\n\n static get isImageDecoderSupported() {\n return shadow(\n this,\n \"isImageDecoderSupported\",\n typeof ImageDecoder !== \"undefined\"\n );\n }\n\n static get platform() {\n if (\n (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) ||\n (typeof navigator !== \"undefined\" &&\n typeof navigator?.platform === \"string\")\n ) {\n return shadow(this, \"platform\", {\n isMac: navigator.platform.includes(\"Mac\"),\n isWindows: navigator.platform.includes(\"Win\"),\n isFirefox:\n (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) ||\n (typeof navigator?.userAgent === \"string\" &&\n navigator.userAgent.includes(\"Firefox\")),\n });\n }\n return shadow(this, \"platform\", {\n isMac: false,\n isWindows: false,\n isFirefox: false,\n });\n }\n\n static get isCSSRoundSupported() {\n return shadow(\n this,\n \"isCSSRoundSupported\",\n globalThis.CSS?.supports?.(\"width: round(1.5px, 1px)\")\n );\n }\n}\n\nconst hexNumbers = Array.from(Array(256).keys(), n =>\n n.toString(16).padStart(2, \"0\")\n);\n\nclass Util {\n static makeHexColor(r, g, b) {\n return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;\n }\n\n // Apply a scaling matrix to some min/max values.\n // If a scaling factor is negative then min and max must be\n // swapped.\n static scaleMinMax(transform, minMax) {\n let temp;\n if (transform[0]) {\n if (transform[0] < 0) {\n temp = minMax[0];\n minMax[0] = minMax[2];\n minMax[2] = temp;\n }\n minMax[0] *= transform[0];\n minMax[2] *= transform[0];\n\n if (transform[3] < 0) {\n temp = minMax[1];\n minMax[1] = minMax[3];\n minMax[3] = temp;\n }\n minMax[1] *= transform[3];\n minMax[3] *= transform[3];\n } else {\n temp = minMax[0];\n minMax[0] = minMax[1];\n minMax[1] = temp;\n temp = minMax[2];\n minMax[2] = minMax[3];\n minMax[3] = temp;\n\n if (transform[1] < 0) {\n temp = minMax[1];\n minMax[1] = minMax[3];\n minMax[3] = temp;\n }\n minMax[1] *= transform[1];\n minMax[3] *= transform[1];\n\n if (transform[2] < 0) {\n temp = minMax[0];\n minMax[0] = minMax[2];\n minMax[2] = temp;\n }\n minMax[0] *= transform[2];\n minMax[2] *= transform[2];\n }\n minMax[0] += transform[4];\n minMax[1] += transform[5];\n minMax[2] += transform[4];\n minMax[3] += transform[5];\n }\n\n // Concatenates two transformation matrices together and returns the result.\n static transform(m1, m2) {\n return [\n m1[0] * m2[0] + m1[2] * m2[1],\n m1[1] * m2[0] + m1[3] * m2[1],\n m1[0] * m2[2] + m1[2] * m2[3],\n m1[1] * m2[2] + m1[3] * m2[3],\n m1[0] * m2[4] + m1[2] * m2[5] + m1[4],\n m1[1] * m2[4] + m1[3] * m2[5] + m1[5],\n ];\n }\n\n // For 2d affine transforms\n static applyTransform(p, m) {\n const xt = p[0] * m[0] + p[1] * m[2] + m[4];\n const yt = p[0] * m[1] + p[1] * m[3] + m[5];\n return [xt, yt];\n }\n\n static applyInverseTransform(p, m) {\n const d = m[0] * m[3] - m[1] * m[2];\n const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;\n const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;\n return [xt, yt];\n }\n\n // Applies the transform to the rectangle and finds the minimum axially\n // aligned bounding box.\n static getAxialAlignedBoundingBox(r, m) {\n const p1 = this.applyTransform(r, m);\n const p2 = this.applyTransform(r.slice(2, 4), m);\n const p3 = this.applyTransform([r[0], r[3]], m);\n const p4 = this.applyTransform([r[2], r[1]], m);\n return [\n Math.min(p1[0], p2[0], p3[0], p4[0]),\n Math.min(p1[1], p2[1], p3[1], p4[1]),\n Math.max(p1[0], p2[0], p3[0], p4[0]),\n Math.max(p1[1], p2[1], p3[1], p4[1]),\n ];\n }\n\n static inverseTransform(m) {\n const d = m[0] * m[3] - m[1] * m[2];\n return [\n m[3] / d,\n -m[1] / d,\n -m[2] / d,\n m[0] / d,\n (m[2] * m[5] - m[4] * m[3]) / d,\n (m[4] * m[1] - m[5] * m[0]) / d,\n ];\n }\n\n // This calculation uses Singular Value Decomposition.\n // The SVD can be represented with formula A = USV. We are interested in the\n // matrix S here because it represents the scale values.\n static singularValueDecompose2dScale(m) {\n const transpose = [m[0], m[2], m[1], m[3]];\n\n // Multiply matrix m with its transpose.\n const a = m[0] * transpose[0] + m[1] * transpose[2];\n const b = m[0] * transpose[1] + m[1] * transpose[3];\n const c = m[2] * transpose[0] + m[3] * transpose[2];\n const d = m[2] * transpose[1] + m[3] * transpose[3];\n\n // Solve the second degree polynomial to get roots.\n const first = (a + d) / 2;\n const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;\n const sx = first + second || 1;\n const sy = first - second || 1;\n\n // Scale values are the square roots of the eigenvalues.\n return [Math.sqrt(sx), Math.sqrt(sy)];\n }\n\n // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)\n // For coordinate systems whose origin lies in the bottom-left, this\n // means normalization to (BL,TR) ordering. For systems with origin in the\n // top-left, this means (TL,BR) ordering.\n static normalizeRect(rect) {\n const r = rect.slice(0); // clone rect\n if (rect[0] > rect[2]) {\n r[0] = rect[2];\n r[2] = rect[0];\n }\n if (rect[1] > rect[3]) {\n r[1] = rect[3];\n r[3] = rect[1];\n }\n return r;\n }\n\n // Returns a rectangle [x1, y1, x2, y2] corresponding to the\n // intersection of rect1 and rect2. If no intersection, returns 'null'\n // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]\n static intersect(rect1, rect2) {\n const xLow = Math.max(\n Math.min(rect1[0], rect1[2]),\n Math.min(rect2[0], rect2[2])\n );\n const xHigh = Math.min(\n Math.max(rect1[0], rect1[2]),\n Math.max(rect2[0], rect2[2])\n );\n if (xLow > xHigh) {\n return null;\n }\n const yLow = Math.max(\n Math.min(rect1[1], rect1[3]),\n Math.min(rect2[1], rect2[3])\n );\n const yHigh = Math.min(\n Math.max(rect1[1], rect1[3]),\n Math.max(rect2[1], rect2[3])\n );\n if (yLow > yHigh) {\n return null;\n }\n\n return [xLow, yLow, xHigh, yHigh];\n }\n\n static #getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, t, minMax) {\n if (t <= 0 || t >= 1) {\n return;\n }\n const mt = 1 - t;\n const tt = t * t;\n const ttt = tt * t;\n const x = mt * (mt * (mt * x0 + 3 * t * x1) + 3 * tt * x2) + ttt * x3;\n const y = mt * (mt * (mt * y0 + 3 * t * y1) + 3 * tt * y2) + ttt * y3;\n minMax[0] = Math.min(minMax[0], x);\n minMax[1] = Math.min(minMax[1], y);\n minMax[2] = Math.max(minMax[2], x);\n minMax[3] = Math.max(minMax[3], y);\n }\n\n static #getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, a, b, c, minMax) {\n if (Math.abs(a) < 1e-12) {\n if (Math.abs(b) >= 1e-12) {\n this.#getExtremumOnCurve(\n x0,\n x1,\n x2,\n x3,\n y0,\n y1,\n y2,\n y3,\n -c / b,\n minMax\n );\n }\n return;\n }\n\n const delta = b ** 2 - 4 * c * a;\n if (delta < 0) {\n return;\n }\n const sqrtDelta = Math.sqrt(delta);\n const a2 = 2 * a;\n this.#getExtremumOnCurve(\n x0,\n x1,\n x2,\n x3,\n y0,\n y1,\n y2,\n y3,\n (-b + sqrtDelta) / a2,\n minMax\n );\n this.#getExtremumOnCurve(\n x0,\n x1,\n x2,\n x3,\n y0,\n y1,\n y2,\n y3,\n (-b - sqrtDelta) / a2,\n minMax\n );\n }\n\n // From https://github.com/adobe-webplatform/Snap.svg/blob/b365287722a72526000ac4bfcf0ce4cac2faa015/src/path.js#L852\n static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax) {\n if (minMax) {\n minMax[0] = Math.min(minMax[0], x0, x3);\n minMax[1] = Math.min(minMax[1], y0, y3);\n minMax[2] = Math.max(minMax[2], x0, x3);\n minMax[3] = Math.max(minMax[3], y0, y3);\n } else {\n minMax = [\n Math.min(x0, x3),\n Math.min(y0, y3),\n Math.max(x0, x3),\n Math.max(y0, y3),\n ];\n }\n this.#getExtremum(\n x0,\n x1,\n x2,\n x3,\n y0,\n y1,\n y2,\n y3,\n 3 * (-x0 + 3 * (x1 - x2) + x3),\n 6 * (x0 - 2 * x1 + x2),\n 3 * (x1 - x0),\n minMax\n );\n this.#getExtremum(\n x0,\n x1,\n x2,\n x3,\n y0,\n y1,\n y2,\n y3,\n 3 * (-y0 + 3 * (y1 - y2) + y3),\n 6 * (y0 - 2 * y1 + y2),\n 3 * (y1 - y0),\n minMax\n );\n return minMax;\n }\n}\n\nconst PDFStringTranslateTable = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2d8,\n 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192,\n 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018,\n 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d,\n 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac,\n];\n\nfunction stringToPDFString(str) {\n // See section 7.9.2.2 Text String Type.\n // The string can contain some language codes bracketed with 0x0b,\n // so we must remove them.\n if (str[0] >= \"\\xEF\") {\n let encoding;\n if (str[0] === \"\\xFE\" && str[1] === \"\\xFF\") {\n encoding = \"utf-16be\";\n if (str.length % 2 === 1) {\n str = str.slice(0, -1);\n }\n } else if (str[0] === \"\\xFF\" && str[1] === \"\\xFE\") {\n encoding = \"utf-16le\";\n if (str.length % 2 === 1) {\n str = str.slice(0, -1);\n }\n } else if (str[0] === \"\\xEF\" && str[1] === \"\\xBB\" && str[2] === \"\\xBF\") {\n encoding = \"utf-8\";\n }\n\n if (encoding) {\n try {\n const decoder = new TextDecoder(encoding, { fatal: true });\n const buffer = stringToBytes(str);\n const decoded = decoder.decode(buffer);\n if (!decoded.includes(\"\\x1b\")) {\n return decoded;\n }\n return decoded.replaceAll(/\\x1b[^\\x1b]*(?:\\x1b|$)/g, \"\");\n } catch (ex) {\n warn(`stringToPDFString: \"${ex}\".`);\n }\n }\n }\n // ISO Latin 1\n const strBuf = [];\n for (let i = 0, ii = str.length; i < ii; i++) {\n const charCode = str.charCodeAt(i);\n if (charCode === 0x1b) {\n // eslint-disable-next-line no-empty\n while (++i < ii && str.charCodeAt(i) !== 0x1b) {}\n continue;\n }\n const code = PDFStringTranslateTable[charCode];\n strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));\n }\n return strBuf.join(\"\");\n}\n\nfunction stringToUTF8String(str) {\n return decodeURIComponent(escape(str));\n}\n\nfunction utf8StringToString(str) {\n return unescape(encodeURIComponent(str));\n}\n\nfunction isArrayEqual(arr1, arr2) {\n if (arr1.length !== arr2.length) {\n return false;\n }\n for (let i = 0, ii = arr1.length; i < ii; i++) {\n if (arr1[i] !== arr2[i]) {\n return false;\n }\n }\n return true;\n}\n\nfunction getModificationDate(date = new Date()) {\n const buffer = [\n date.getUTCFullYear().toString(),\n (date.getUTCMonth() + 1).toString().padStart(2, \"0\"),\n date.getUTCDate().toString().padStart(2, \"0\"),\n date.getUTCHours().toString().padStart(2, \"0\"),\n date.getUTCMinutes().toString().padStart(2, \"0\"),\n date.getUTCSeconds().toString().padStart(2, \"0\"),\n ];\n\n return buffer.join(\"\");\n}\n\nlet NormalizeRegex = null;\nlet NormalizationMap = null;\nfunction normalizeUnicode(str) {\n if (!NormalizeRegex) {\n // In order to generate the following regex:\n // - create a PDF containing all the chars in the range 0000-FFFF with\n // a NFKC which is different of the char.\n // - copy and paste all those chars and get the ones where NFKC is\n // required.\n // It appears that most the chars here contain some ligatures.\n NormalizeRegex =\n /([\\u00a0\\u00b5\\u037e\\u0eb3\\u2000-\\u200a\\u202f\\u2126\\ufb00-\\ufb04\\ufb06\\ufb20-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40-\\ufb41\\ufb43-\\ufb44\\ufb46-\\ufba1\\ufba4-\\ufba9\\ufbae-\\ufbb1\\ufbd3-\\ufbdc\\ufbde-\\ufbe7\\ufbea-\\ufbf8\\ufbfc-\\ufbfd\\ufc00-\\ufc5d\\ufc64-\\ufcf1\\ufcf5-\\ufd3d\\ufd88\\ufdf4\\ufdfa-\\ufdfb\\ufe71\\ufe77\\ufe79\\ufe7b\\ufe7d]+)|(\\ufb05+)/gu;\n NormalizationMap = new Map([[\"ſt\", \"ſt\"]]);\n }\n return str.replaceAll(NormalizeRegex, (_, p1, p2) =>\n p1 ? p1.normalize(\"NFKC\") : NormalizationMap.get(p2)\n );\n}\n\nfunction getUuid() {\n if (\n (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) ||\n typeof crypto.randomUUID === \"function\"\n ) {\n return crypto.randomUUID();\n }\n const buf = new Uint8Array(32);\n crypto.getRandomValues(buf);\n return bytesToString(buf);\n}\n\nconst AnnotationPrefix = \"pdfjs_internal_id_\";\n\nconst FontRenderOps = {\n BEZIER_CURVE_TO: 0,\n MOVE_TO: 1,\n LINE_TO: 2,\n QUADRATIC_CURVE_TO: 3,\n RESTORE: 4,\n SAVE: 5,\n SCALE: 6,\n TRANSFORM: 7,\n TRANSLATE: 8,\n};\n\n// TODO: Remove this once `Uint8Array.prototype.toHex` is generally available.\nfunction toHexUtil(arr) {\n if (Uint8Array.prototype.toHex) {\n return arr.toHex();\n }\n return Array.from(arr, num => hexNumbers[num]).join(\"\");\n}\n\n// TODO: Remove this once `Uint8Array.prototype.toBase64` is generally\n// available.\nfunction toBase64Util(arr) {\n if (Uint8Array.prototype.toBase64) {\n return arr.toBase64();\n }\n return btoa(bytesToString(arr));\n}\n\n// TODO: Remove this once `Uint8Array.fromBase64` is generally available.\nfunction fromBase64Util(str) {\n if (Uint8Array.fromBase64) {\n return Uint8Array.fromBase64(str);\n }\n return stringToBytes(atob(str));\n}\n\n// TODO: Remove this once https://bugzilla.mozilla.org/show_bug.cgi?id=1928493\n// is fixed.\nif (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"SKIP_BABEL\")) &&\n typeof Promise.try !== \"function\"\n) {\n Promise.try = function (fn, ...args) {\n return new Promise(resolve => {\n resolve(fn(...args));\n });\n };\n}\n\nexport {\n AbortException,\n AnnotationActionEventType,\n AnnotationBorderStyleType,\n AnnotationEditorParamsType,\n AnnotationEditorPrefix,\n AnnotationEditorType,\n AnnotationFieldFlag,\n AnnotationFlag,\n AnnotationMode,\n AnnotationPrefix,\n AnnotationReplyType,\n AnnotationType,\n assert,\n BaseException,\n BASELINE_FACTOR,\n bytesToString,\n createValidAbsoluteUrl,\n DocumentActionEventType,\n FeatureTest,\n FONT_IDENTITY_MATRIX,\n FontRenderOps,\n FormatError,\n fromBase64Util,\n getModificationDate,\n getUuid,\n getVerbosityLevel,\n hexNumbers,\n IDENTITY_MATRIX,\n ImageKind,\n info,\n InvalidPDFException,\n isArrayEqual,\n isNodeJS,\n LINE_DESCENT_FACTOR,\n LINE_FACTOR,\n MAX_IMAGE_SIZE_TO_CACHE,\n MissingPDFException,\n normalizeUnicode,\n objectFromMap,\n objectSize,\n OPS,\n PageActionEventType,\n PasswordException,\n PasswordResponses,\n PermissionFlag,\n RenderingIntentFlag,\n setVerbosityLevel,\n shadow,\n string32,\n stringToBytes,\n stringToPDFString,\n stringToUTF8String,\n TextRenderingMode,\n toBase64Util,\n toHexUtil,\n UnexpectedResponseException,\n UnknownErrorException,\n unreachable,\n utf8StringToString,\n Util,\n VerbosityLevel,\n warn,\n};\n","/* Copyright 2015 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BaseException,\n FeatureTest,\n shadow,\n Util,\n warn,\n} from \"../shared/util.js\";\n\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n\nclass PixelsPerInch {\n static CSS = 96.0;\n\n static PDF = 72.0;\n\n static PDF_TO_CSS_UNITS = this.CSS / this.PDF;\n}\n\nasync function fetchData(url, type = \"text\") {\n if (\n (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) ||\n isValidFetchUrl(url, document.baseURI)\n ) {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n switch (type) {\n case \"arraybuffer\":\n return response.arrayBuffer();\n case \"blob\":\n return response.blob();\n case \"json\":\n return response.json();\n }\n return response.text();\n }\n\n // The Fetch API is not supported.\n return new Promise((resolve, reject) => {\n const request = new XMLHttpRequest();\n request.open(\"GET\", url, /* async = */ true);\n request.responseType = type;\n\n request.onreadystatechange = () => {\n if (request.readyState !== XMLHttpRequest.DONE) {\n return;\n }\n if (request.status === 200 || request.status === 0) {\n switch (type) {\n case \"arraybuffer\":\n case \"blob\":\n case \"json\":\n resolve(request.response);\n return;\n }\n resolve(request.responseText);\n return;\n }\n reject(new Error(request.statusText));\n };\n\n request.send(null);\n });\n}\n\n/**\n * @typedef {Object} PageViewportParameters\n * @property {Array} viewBox - The xMin, yMin, xMax and\n * yMax coordinates.\n * @property {number} scale - The scale of the viewport.\n * @property {number} rotation - The rotation, in degrees, of the viewport.\n * @property {number} [offsetX] - The horizontal, i.e. x-axis, offset. The\n * default value is `0`.\n * @property {number} [offsetY] - The vertical, i.e. y-axis, offset. The\n * default value is `0`.\n * @property {boolean} [dontFlip] - If true, the y-axis will not be flipped.\n * The default value is `false`.\n */\n\n/**\n * @typedef {Object} PageViewportCloneParameters\n * @property {number} [scale] - The scale, overriding the one in the cloned\n * viewport. The default value is `this.scale`.\n * @property {number} [rotation] - The rotation, in degrees, overriding the one\n * in the cloned viewport. The default value is `this.rotation`.\n * @property {number} [offsetX] - The horizontal, i.e. x-axis, offset.\n * The default value is `this.offsetX`.\n * @property {number} [offsetY] - The vertical, i.e. y-axis, offset.\n * The default value is `this.offsetY`.\n * @property {boolean} [dontFlip] - If true, the x-axis will not be flipped.\n * The default value is `false`.\n */\n\n/**\n * PDF page viewport created based on scale, rotation and offset.\n */\nclass PageViewport {\n /**\n * @param {PageViewportParameters}\n */\n constructor({\n viewBox,\n scale,\n rotation,\n offsetX = 0,\n offsetY = 0,\n dontFlip = false,\n }) {\n this.viewBox = viewBox;\n this.scale = scale;\n this.rotation = rotation;\n this.offsetX = offsetX;\n this.offsetY = offsetY;\n\n // creating transform to convert pdf coordinate system to the normal\n // canvas like coordinates taking in account scale and rotation\n const centerX = (viewBox[2] + viewBox[0]) / 2;\n const centerY = (viewBox[3] + viewBox[1]) / 2;\n let rotateA, rotateB, rotateC, rotateD;\n // Normalize the rotation, by clamping it to the [0, 360) range.\n rotation %= 360;\n if (rotation < 0) {\n rotation += 360;\n }\n switch (rotation) {\n case 180:\n rotateA = -1;\n rotateB = 0;\n rotateC = 0;\n rotateD = 1;\n break;\n case 90:\n rotateA = 0;\n rotateB = 1;\n rotateC = 1;\n rotateD = 0;\n break;\n case 270:\n rotateA = 0;\n rotateB = -1;\n rotateC = -1;\n rotateD = 0;\n break;\n case 0:\n rotateA = 1;\n rotateB = 0;\n rotateC = 0;\n rotateD = -1;\n break;\n default:\n throw new Error(\n \"PageViewport: Invalid rotation, must be a multiple of 90 degrees.\"\n );\n }\n\n if (dontFlip) {\n rotateC = -rotateC;\n rotateD = -rotateD;\n }\n\n let offsetCanvasX, offsetCanvasY;\n let width, height;\n if (rotateA === 0) {\n offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;\n offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;\n width = (viewBox[3] - viewBox[1]) * scale;\n height = (viewBox[2] - viewBox[0]) * scale;\n } else {\n offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;\n offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;\n width = (viewBox[2] - viewBox[0]) * scale;\n height = (viewBox[3] - viewBox[1]) * scale;\n }\n // creating transform for the following operations:\n // translate(-centerX, -centerY), rotate and flip vertically,\n // scale, and translate(offsetCanvasX, offsetCanvasY)\n this.transform = [\n rotateA * scale,\n rotateB * scale,\n rotateC * scale,\n rotateD * scale,\n offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,\n offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY,\n ];\n\n this.width = width;\n this.height = height;\n }\n\n /**\n * The original, un-scaled, viewport dimensions.\n * @type {Object}\n */\n get rawDims() {\n const { viewBox } = this;\n return shadow(this, \"rawDims\", {\n pageWidth: viewBox[2] - viewBox[0],\n pageHeight: viewBox[3] - viewBox[1],\n pageX: viewBox[0],\n pageY: viewBox[1],\n });\n }\n\n /**\n * Clones viewport, with optional additional properties.\n * @param {PageViewportCloneParameters} [params]\n * @returns {PageViewport} Cloned viewport.\n */\n clone({\n scale = this.scale,\n rotation = this.rotation,\n offsetX = this.offsetX,\n offsetY = this.offsetY,\n dontFlip = false,\n } = {}) {\n return new PageViewport({\n viewBox: this.viewBox.slice(),\n scale,\n rotation,\n offsetX,\n offsetY,\n dontFlip,\n });\n }\n\n /**\n * Converts PDF point to the viewport coordinates. For examples, useful for\n * converting PDF location into canvas pixel coordinates.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @returns {Array} Array containing `x`- and `y`-coordinates of the\n * point in the viewport coordinate space.\n * @see {@link convertToPdfPoint}\n * @see {@link convertToViewportRectangle}\n */\n convertToViewportPoint(x, y) {\n return Util.applyTransform([x, y], this.transform);\n }\n\n /**\n * Converts PDF rectangle to the viewport coordinates.\n * @param {Array} rect - The xMin, yMin, xMax and yMax coordinates.\n * @returns {Array} Array containing corresponding coordinates of the\n * rectangle in the viewport coordinate space.\n * @see {@link convertToViewportPoint}\n */\n convertToViewportRectangle(rect) {\n const topLeft = Util.applyTransform([rect[0], rect[1]], this.transform);\n const bottomRight = Util.applyTransform([rect[2], rect[3]], this.transform);\n return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];\n }\n\n /**\n * Converts viewport coordinates to the PDF location. For examples, useful\n * for converting canvas pixel location into PDF one.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @returns {Array} Array containing `x`- and `y`-coordinates of the\n * point in the PDF coordinate space.\n * @see {@link convertToViewportPoint}\n */\n convertToPdfPoint(x, y) {\n return Util.applyInverseTransform([x, y], this.transform);\n }\n}\n\nclass RenderingCancelledException extends BaseException {\n constructor(msg, extraDelay = 0) {\n super(msg, \"RenderingCancelledException\");\n this.extraDelay = extraDelay;\n }\n}\n\nfunction isDataScheme(url) {\n const ii = url.length;\n let i = 0;\n while (i < ii && url[i].trim() === \"\") {\n i++;\n }\n return url.substring(i, i + 5).toLowerCase() === \"data:\";\n}\n\nfunction isPdfFile(filename) {\n return typeof filename === \"string\" && /\\.pdf$/i.test(filename);\n}\n\n/**\n * Gets the filename from a given URL.\n * @param {string} url\n * @returns {string}\n */\nfunction getFilenameFromUrl(url) {\n [url] = url.split(/[#?]/, 1);\n return url.substring(url.lastIndexOf(\"/\") + 1);\n}\n\n/**\n * Returns the filename or guessed filename from the url (see issue 3455).\n * @param {string} url - The original PDF location.\n * @param {string} defaultFilename - The value returned if the filename is\n * unknown, or the protocol is unsupported.\n * @returns {string} Guessed PDF filename.\n */\nfunction getPdfFilenameFromUrl(url, defaultFilename = \"document.pdf\") {\n if (typeof url !== \"string\") {\n return defaultFilename;\n }\n if (isDataScheme(url)) {\n warn('getPdfFilenameFromUrl: ignore \"data:\"-URL for performance reasons.');\n return defaultFilename;\n }\n const reURI = /^(?:(?:[^:]+:)?\\/\\/[^/]+)?([^?#]*)(\\?[^#]*)?(#.*)?$/;\n // SCHEME HOST 1.PATH 2.QUERY 3.REF\n // Pattern to get last matching NAME.pdf\n const reFilename = /[^/?#=]+\\.pdf\\b(?!.*\\.pdf\\b)/i;\n const splitURI = reURI.exec(url);\n let suggestedFilename =\n reFilename.exec(splitURI[1]) ||\n reFilename.exec(splitURI[2]) ||\n reFilename.exec(splitURI[3]);\n if (suggestedFilename) {\n suggestedFilename = suggestedFilename[0];\n if (suggestedFilename.includes(\"%\")) {\n // URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf\n try {\n suggestedFilename = reFilename.exec(\n decodeURIComponent(suggestedFilename)\n )[0];\n } catch {\n // Possible (extremely rare) errors:\n // URIError \"Malformed URI\", e.g. for \"%AA.pdf\"\n // TypeError \"null has no properties\", e.g. for \"%2F.pdf\"\n }\n }\n }\n return suggestedFilename || defaultFilename;\n}\n\nclass StatTimer {\n started = Object.create(null);\n\n times = [];\n\n time(name) {\n if (name in this.started) {\n warn(`Timer is already running for ${name}`);\n }\n this.started[name] = Date.now();\n }\n\n timeEnd(name) {\n if (!(name in this.started)) {\n warn(`Timer has not been started for ${name}`);\n }\n this.times.push({\n name,\n start: this.started[name],\n end: Date.now(),\n });\n // Remove timer from started so it can be called again.\n delete this.started[name];\n }\n\n toString() {\n // Find the longest name for padding purposes.\n const outBuf = [];\n let longest = 0;\n for (const { name } of this.times) {\n longest = Math.max(name.length, longest);\n }\n for (const { name, start, end } of this.times) {\n outBuf.push(`${name.padEnd(longest)} ${end - start}ms\\n`);\n }\n return outBuf.join(\"\");\n }\n}\n\nfunction isValidFetchUrl(url, baseUrl) {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: isValidFetchUrl\");\n }\n try {\n const { protocol } = baseUrl ? new URL(url, baseUrl) : new URL(url);\n // The Fetch API only supports the http/https protocols, and not file/ftp.\n return protocol === \"http:\" || protocol === \"https:\";\n } catch {\n return false; // `new URL()` will throw on incorrect data.\n }\n}\n\n/**\n * Event handler to suppress context menu.\n */\nfunction noContextMenu(e) {\n e.preventDefault();\n}\n\nfunction stopEvent(e) {\n e.preventDefault();\n e.stopPropagation();\n}\n\n// Deprecated API function -- display regardless of the `verbosity` setting.\nfunction deprecated(details) {\n // eslint-disable-next-line no-console\n console.log(\"Deprecated API usage: \" + details);\n}\n\nclass PDFDateString {\n static #regex;\n\n /**\n * Convert a PDF date string to a JavaScript `Date` object.\n *\n * The PDF date string format is described in section 7.9.4 of the official\n * PDF 32000-1:2008 specification. However, in the PDF 1.7 reference (sixth\n * edition) Adobe describes the same format including a trailing apostrophe.\n * This syntax in incorrect, but Adobe Acrobat creates PDF files that contain\n * them. We ignore all apostrophes as they are not necessary for date parsing.\n *\n * Moreover, Adobe Acrobat doesn't handle changing the date to universal time\n * and doesn't use the user's time zone (effectively ignoring the HH' and mm'\n * parts of the date string).\n *\n * @param {string} input\n * @returns {Date|null}\n */\n static toDateObject(input) {\n if (!input || typeof input !== \"string\") {\n return null;\n }\n\n // Lazily initialize the regular expression.\n this.#regex ||= new RegExp(\n \"^D:\" + // Prefix (required)\n \"(\\\\d{4})\" + // Year (required)\n \"(\\\\d{2})?\" + // Month (optional)\n \"(\\\\d{2})?\" + // Day (optional)\n \"(\\\\d{2})?\" + // Hour (optional)\n \"(\\\\d{2})?\" + // Minute (optional)\n \"(\\\\d{2})?\" + // Second (optional)\n \"([Z|+|-])?\" + // Universal time relation (optional)\n \"(\\\\d{2})?\" + // Offset hour (optional)\n \"'?\" + // Splitting apostrophe (optional)\n \"(\\\\d{2})?\" + // Offset minute (optional)\n \"'?\" // Trailing apostrophe (optional)\n );\n\n // Optional fields that don't satisfy the requirements from the regular\n // expression (such as incorrect digit counts or numbers that are out of\n // range) will fall back the defaults from the specification.\n const matches = this.#regex.exec(input);\n if (!matches) {\n return null;\n }\n\n // JavaScript's `Date` object expects the month to be between 0 and 11\n // instead of 1 and 12, so we have to correct for that.\n const year = parseInt(matches[1], 10);\n let month = parseInt(matches[2], 10);\n month = month >= 1 && month <= 12 ? month - 1 : 0;\n let day = parseInt(matches[3], 10);\n day = day >= 1 && day <= 31 ? day : 1;\n let hour = parseInt(matches[4], 10);\n hour = hour >= 0 && hour <= 23 ? hour : 0;\n let minute = parseInt(matches[5], 10);\n minute = minute >= 0 && minute <= 59 ? minute : 0;\n let second = parseInt(matches[6], 10);\n second = second >= 0 && second <= 59 ? second : 0;\n const universalTimeRelation = matches[7] || \"Z\";\n let offsetHour = parseInt(matches[8], 10);\n offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;\n let offsetMinute = parseInt(matches[9], 10) || 0;\n offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;\n\n // Universal time relation 'Z' means that the local time is equal to the\n // universal time, whereas the relations '+'/'-' indicate that the local\n // time is later respectively earlier than the universal time. Every date\n // is normalized to universal time.\n if (universalTimeRelation === \"-\") {\n hour += offsetHour;\n minute += offsetMinute;\n } else if (universalTimeRelation === \"+\") {\n hour -= offsetHour;\n minute -= offsetMinute;\n }\n\n return new Date(Date.UTC(year, month, day, hour, minute, second));\n }\n}\n\n/**\n * NOTE: This is (mostly) intended to support printing of XFA forms.\n */\nfunction getXfaPageViewport(xfaPage, { scale = 1, rotation = 0 }) {\n const { width, height } = xfaPage.attributes.style;\n const viewBox = [0, 0, parseInt(width), parseInt(height)];\n\n return new PageViewport({\n viewBox,\n scale,\n rotation,\n });\n}\n\nfunction getRGB(color) {\n if (color.startsWith(\"#\")) {\n const colorRGB = parseInt(color.slice(1), 16);\n return [\n (colorRGB & 0xff0000) >> 16,\n (colorRGB & 0x00ff00) >> 8,\n colorRGB & 0x0000ff,\n ];\n }\n\n if (color.startsWith(\"rgb(\")) {\n // getComputedStyle(...).color returns a `rgb(R, G, B)` color.\n return color\n .slice(/* \"rgb(\".length */ 4, -1) // Strip out \"rgb(\" and \")\".\n .split(\",\")\n .map(x => parseInt(x));\n }\n\n if (color.startsWith(\"rgba(\")) {\n return color\n .slice(/* \"rgba(\".length */ 5, -1) // Strip out \"rgba(\" and \")\".\n .split(\",\")\n .map(x => parseInt(x))\n .slice(0, 3);\n }\n\n warn(`Not a valid color format: \"${color}\"`);\n return [0, 0, 0];\n}\n\nfunction getColorValues(colors) {\n const span = document.createElement(\"span\");\n span.style.visibility = \"hidden\";\n document.body.append(span);\n for (const name of colors.keys()) {\n span.style.color = name;\n const computedColor = window.getComputedStyle(span).color;\n colors.set(name, getRGB(computedColor));\n }\n span.remove();\n}\n\nfunction getCurrentTransform(ctx) {\n const { a, b, c, d, e, f } = ctx.getTransform();\n return [a, b, c, d, e, f];\n}\n\nfunction getCurrentTransformInverse(ctx) {\n const { a, b, c, d, e, f } = ctx.getTransform().invertSelf();\n return [a, b, c, d, e, f];\n}\n\n/**\n * @param {HTMLDivElement} div\n * @param {PageViewport} viewport\n * @param {boolean} mustFlip\n * @param {boolean} mustRotate\n */\nfunction setLayerDimensions(\n div,\n viewport,\n mustFlip = false,\n mustRotate = true\n) {\n if (viewport instanceof PageViewport) {\n const { pageWidth, pageHeight } = viewport.rawDims;\n const { style } = div;\n const useRound = FeatureTest.isCSSRoundSupported;\n\n const w = `var(--scale-factor) * ${pageWidth}px`,\n h = `var(--scale-factor) * ${pageHeight}px`;\n const widthStr = useRound\n ? `round(down, ${w}, var(--scale-round-x, 1px))`\n : `calc(${w})`,\n heightStr = useRound\n ? `round(down, ${h}, var(--scale-round-y, 1px))`\n : `calc(${h})`;\n\n if (!mustFlip || viewport.rotation % 180 === 0) {\n style.width = widthStr;\n style.height = heightStr;\n } else {\n style.width = heightStr;\n style.height = widthStr;\n }\n }\n\n if (mustRotate) {\n div.setAttribute(\"data-main-rotation\", viewport.rotation);\n }\n}\n\n/**\n * Scale factors for the canvas, necessary with HiDPI displays.\n */\nclass OutputScale {\n constructor() {\n const pixelRatio = window.devicePixelRatio || 1;\n\n /**\n * @type {number} Horizontal scale.\n */\n this.sx = pixelRatio;\n\n /**\n * @type {number} Vertical scale.\n */\n this.sy = pixelRatio;\n }\n\n /**\n * @type {boolean} Returns `true` when scaling is required, `false` otherwise.\n */\n get scaled() {\n return this.sx !== 1 || this.sy !== 1;\n }\n\n get symmetric() {\n return this.sx === this.sy;\n }\n}\n\nexport {\n deprecated,\n fetchData,\n getColorValues,\n getCurrentTransform,\n getCurrentTransformInverse,\n getFilenameFromUrl,\n getPdfFilenameFromUrl,\n getRGB,\n getXfaPageViewport,\n isDataScheme,\n isPdfFile,\n isValidFetchUrl,\n noContextMenu,\n OutputScale,\n PageViewport,\n PDFDateString,\n PixelsPerInch,\n RenderingCancelledException,\n setLayerDimensions,\n StatTimer,\n stopEvent,\n SVG_NS,\n};\n","/* Copyright 2023 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { noContextMenu, stopEvent } from \"../display_utils.js\";\n\nclass EditorToolbar {\n #toolbar = null;\n\n #colorPicker = null;\n\n #editor;\n\n #buttons = null;\n\n #altText = null;\n\n static #l10nRemove = null;\n\n constructor(editor) {\n this.#editor = editor;\n\n EditorToolbar.#l10nRemove ||= Object.freeze({\n freetext: \"pdfjs-editor-remove-freetext-button\",\n highlight: \"pdfjs-editor-remove-highlight-button\",\n ink: \"pdfjs-editor-remove-ink-button\",\n stamp: \"pdfjs-editor-remove-stamp-button\",\n });\n }\n\n render() {\n const editToolbar = (this.#toolbar = document.createElement(\"div\"));\n editToolbar.classList.add(\"editToolbar\", \"hidden\");\n editToolbar.setAttribute(\"role\", \"toolbar\");\n const signal = this.#editor._uiManager._signal;\n editToolbar.addEventListener(\"contextmenu\", noContextMenu, { signal });\n editToolbar.addEventListener(\"pointerdown\", EditorToolbar.#pointerDown, {\n signal,\n });\n\n const buttons = (this.#buttons = document.createElement(\"div\"));\n buttons.className = \"buttons\";\n editToolbar.append(buttons);\n\n const position = this.#editor.toolbarPosition;\n if (position) {\n const { style } = editToolbar;\n const x =\n this.#editor._uiManager.direction === \"ltr\"\n ? 1 - position[0]\n : position[0];\n style.insetInlineEnd = `${100 * x}%`;\n style.top = `calc(${\n 100 * position[1]\n }% + var(--editor-toolbar-vert-offset))`;\n }\n\n this.#addDeleteButton();\n\n return editToolbar;\n }\n\n get div() {\n return this.#toolbar;\n }\n\n static #pointerDown(e) {\n e.stopPropagation();\n }\n\n #focusIn(e) {\n this.#editor._focusEventsAllowed = false;\n stopEvent(e);\n }\n\n #focusOut(e) {\n this.#editor._focusEventsAllowed = true;\n stopEvent(e);\n }\n\n #addListenersToElement(element) {\n // If we're clicking on a button with the keyboard or with\n // the mouse, we don't want to trigger any focus events on\n // the editor.\n const signal = this.#editor._uiManager._signal;\n element.addEventListener(\"focusin\", this.#focusIn.bind(this), {\n capture: true,\n signal,\n });\n element.addEventListener(\"focusout\", this.#focusOut.bind(this), {\n capture: true,\n signal,\n });\n element.addEventListener(\"contextmenu\", noContextMenu, { signal });\n }\n\n hide() {\n this.#toolbar.classList.add(\"hidden\");\n this.#colorPicker?.hideDropdown();\n }\n\n show() {\n this.#toolbar.classList.remove(\"hidden\");\n this.#altText?.shown();\n }\n\n #addDeleteButton() {\n const { editorType, _uiManager } = this.#editor;\n\n const button = document.createElement(\"button\");\n button.className = \"delete\";\n button.tabIndex = 0;\n button.setAttribute(\"data-l10n-id\", EditorToolbar.#l10nRemove[editorType]);\n this.#addListenersToElement(button);\n button.addEventListener(\n \"click\",\n e => {\n _uiManager.delete();\n },\n { signal: _uiManager._signal }\n );\n this.#buttons.append(button);\n }\n\n get #divider() {\n const divider = document.createElement(\"div\");\n divider.className = \"divider\";\n return divider;\n }\n\n async addAltText(altText) {\n const button = await altText.render();\n this.#addListenersToElement(button);\n this.#buttons.prepend(button, this.#divider);\n this.#altText = altText;\n }\n\n addColorPicker(colorPicker) {\n this.#colorPicker = colorPicker;\n const button = colorPicker.renderButton();\n this.#addListenersToElement(button);\n this.#buttons.prepend(button, this.#divider);\n }\n\n remove() {\n this.#toolbar.remove();\n this.#colorPicker?.destroy();\n this.#colorPicker = null;\n }\n}\n\nclass HighlightToolbar {\n #buttons = null;\n\n #toolbar = null;\n\n #uiManager;\n\n constructor(uiManager) {\n this.#uiManager = uiManager;\n }\n\n #render() {\n const editToolbar = (this.#toolbar = document.createElement(\"div\"));\n editToolbar.className = \"editToolbar\";\n editToolbar.setAttribute(\"role\", \"toolbar\");\n editToolbar.addEventListener(\"contextmenu\", noContextMenu, {\n signal: this.#uiManager._signal,\n });\n\n const buttons = (this.#buttons = document.createElement(\"div\"));\n buttons.className = \"buttons\";\n editToolbar.append(buttons);\n\n this.#addHighlightButton();\n\n return editToolbar;\n }\n\n #getLastPoint(boxes, isLTR) {\n let lastY = 0;\n let lastX = 0;\n for (const box of boxes) {\n const y = box.y + box.height;\n if (y < lastY) {\n continue;\n }\n const x = box.x + (isLTR ? box.width : 0);\n if (y > lastY) {\n lastX = x;\n lastY = y;\n continue;\n }\n if (isLTR) {\n if (x > lastX) {\n lastX = x;\n }\n } else if (x < lastX) {\n lastX = x;\n }\n }\n return [isLTR ? 1 - lastX : lastX, lastY];\n }\n\n show(parent, boxes, isLTR) {\n const [x, y] = this.#getLastPoint(boxes, isLTR);\n const { style } = (this.#toolbar ||= this.#render());\n parent.append(this.#toolbar);\n style.insetInlineEnd = `${100 * x}%`;\n style.top = `calc(${100 * y}% + var(--editor-toolbar-vert-offset))`;\n }\n\n hide() {\n this.#toolbar.remove();\n }\n\n #addHighlightButton() {\n const button = document.createElement(\"button\");\n button.className = \"highlightButton\";\n button.tabIndex = 0;\n button.setAttribute(\"data-l10n-id\", `pdfjs-highlight-floating-button1`);\n const span = document.createElement(\"span\");\n button.append(span);\n span.className = \"visuallyHidden\";\n span.setAttribute(\"data-l10n-id\", \"pdfjs-highlight-floating-button-label\");\n const signal = this.#uiManager._signal;\n button.addEventListener(\"contextmenu\", noContextMenu, { signal });\n button.addEventListener(\n \"click\",\n () => {\n this.#uiManager.highlightSelection(\"floating_button\");\n },\n { signal }\n );\n this.#buttons.append(button);\n }\n}\n\nexport { EditorToolbar, HighlightToolbar };\n","/* Copyright 2022 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./editor.js\").AnnotationEditor} AnnotationEditor */\n// eslint-disable-next-line max-len\n/** @typedef {import(\"./annotation_editor_layer.js\").AnnotationEditorLayer} AnnotationEditorLayer */\n\nimport {\n AnnotationEditorParamsType,\n AnnotationEditorPrefix,\n AnnotationEditorType,\n FeatureTest,\n getUuid,\n shadow,\n Util,\n warn,\n} from \"../../shared/util.js\";\nimport {\n fetchData,\n getColorValues,\n getRGB,\n PixelsPerInch,\n stopEvent,\n} from \"../display_utils.js\";\nimport { HighlightToolbar } from \"./toolbar.js\";\n\nfunction bindEvents(obj, element, names) {\n for (const name of names) {\n element.addEventListener(name, obj[name].bind(obj));\n }\n}\n\n/**\n * Convert a number between 0 and 100 into an hex number between 0 and 255.\n * @param {number} opacity\n * @return {string}\n */\nfunction opacityToHex(opacity) {\n return Math.round(Math.min(255, Math.max(1, 255 * opacity)))\n .toString(16)\n .padStart(2, \"0\");\n}\n\n/**\n * Class to create some unique ids for the different editors.\n */\nclass IdManager {\n #id = 0;\n\n constructor() {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"TESTING\")) {\n Object.defineProperty(this, \"reset\", {\n value: () => (this.#id = 0),\n });\n }\n }\n\n /**\n * Get a unique id.\n * @returns {string}\n */\n get id() {\n return `${AnnotationEditorPrefix}${this.#id++}`;\n }\n}\n\n/**\n * Class to manage the images used by the editors.\n * The main idea is to try to minimize the memory used by the images.\n * The images are cached and reused when possible\n * We use a refCounter to know when an image is not used anymore but we need to\n * be able to restore an image after a remove+undo, so we keep a file reference\n * or an url one.\n */\nclass ImageManager {\n #baseId = getUuid();\n\n #id = 0;\n\n #cache = null;\n\n static get _isSVGFittingCanvas() {\n // By default, Firefox doesn't rescale without preserving the aspect ratio\n // when drawing an SVG image on a canvas, see https://bugzilla.mozilla.org/1547776.\n // The \"workaround\" is to append \"svgView(preserveAspectRatio(none))\" to the\n // url, but according to comment #15, it seems that it leads to unexpected\n // behavior in Safari.\n const svg = `data:image/svg+xml;charset=UTF-8,`;\n const canvas = new OffscreenCanvas(1, 3);\n const ctx = canvas.getContext(\"2d\", { willReadFrequently: true });\n const image = new Image();\n image.src = svg;\n const promise = image.decode().then(() => {\n ctx.drawImage(image, 0, 0, 1, 1, 0, 0, 1, 3);\n return new Uint32Array(ctx.getImageData(0, 0, 1, 1).data.buffer)[0] === 0;\n });\n\n return shadow(this, \"_isSVGFittingCanvas\", promise);\n }\n\n async #get(key, rawData) {\n this.#cache ||= new Map();\n let data = this.#cache.get(key);\n if (data === null) {\n // We already tried to load the image but it failed.\n return null;\n }\n if (data?.bitmap) {\n data.refCounter += 1;\n return data;\n }\n try {\n data ||= {\n bitmap: null,\n id: `image_${this.#baseId}_${this.#id++}`,\n refCounter: 0,\n isSvg: false,\n };\n let image;\n if (typeof rawData === \"string\") {\n data.url = rawData;\n image = await fetchData(rawData, \"blob\");\n } else if (rawData instanceof File) {\n image = data.file = rawData;\n } else if (rawData instanceof Blob) {\n image = rawData;\n }\n\n if (image.type === \"image/svg+xml\") {\n // Unfortunately, createImageBitmap doesn't work with SVG images.\n // (see https://bugzilla.mozilla.org/1841972).\n const mustRemoveAspectRatioPromise = ImageManager._isSVGFittingCanvas;\n const fileReader = new FileReader();\n const imageElement = new Image();\n const imagePromise = new Promise((resolve, reject) => {\n imageElement.onload = () => {\n data.bitmap = imageElement;\n data.isSvg = true;\n resolve();\n };\n fileReader.onload = async () => {\n const url = (data.svgUrl = fileReader.result);\n // We need to set the preserveAspectRatio to none in order to let\n // the image fits the canvas when resizing.\n imageElement.src = (await mustRemoveAspectRatioPromise)\n ? `${url}#svgView(preserveAspectRatio(none))`\n : url;\n };\n imageElement.onerror = fileReader.onerror = reject;\n });\n fileReader.readAsDataURL(image);\n await imagePromise;\n } else {\n data.bitmap = await createImageBitmap(image);\n }\n data.refCounter = 1;\n } catch (e) {\n warn(e);\n data = null;\n }\n this.#cache.set(key, data);\n if (data) {\n this.#cache.set(data.id, data);\n }\n return data;\n }\n\n async getFromFile(file) {\n const { lastModified, name, size, type } = file;\n return this.#get(`${lastModified}_${name}_${size}_${type}`, file);\n }\n\n async getFromUrl(url) {\n return this.#get(url, url);\n }\n\n async getFromBlob(id, blobPromise) {\n const blob = await blobPromise;\n return this.#get(id, blob);\n }\n\n async getFromId(id) {\n this.#cache ||= new Map();\n const data = this.#cache.get(id);\n if (!data) {\n return null;\n }\n if (data.bitmap) {\n data.refCounter += 1;\n return data;\n }\n\n if (data.file) {\n return this.getFromFile(data.file);\n }\n if (data.blobPromise) {\n const { blobPromise } = data;\n delete data.blobPromise;\n return this.getFromBlob(data.id, blobPromise);\n }\n return this.getFromUrl(data.url);\n }\n\n getFromCanvas(id, canvas) {\n this.#cache ||= new Map();\n let data = this.#cache.get(id);\n if (data?.bitmap) {\n data.refCounter += 1;\n return data;\n }\n const offscreen = new OffscreenCanvas(canvas.width, canvas.height);\n const ctx = offscreen.getContext(\"2d\");\n ctx.drawImage(canvas, 0, 0);\n data = {\n bitmap: offscreen.transferToImageBitmap(),\n id: `image_${this.#baseId}_${this.#id++}`,\n refCounter: 1,\n isSvg: false,\n };\n this.#cache.set(id, data);\n this.#cache.set(data.id, data);\n return data;\n }\n\n getSvgUrl(id) {\n const data = this.#cache.get(id);\n if (!data?.isSvg) {\n return null;\n }\n return data.svgUrl;\n }\n\n deleteId(id) {\n this.#cache ||= new Map();\n const data = this.#cache.get(id);\n if (!data) {\n return;\n }\n data.refCounter -= 1;\n if (data.refCounter !== 0) {\n return;\n }\n const { bitmap } = data;\n if (!data.url && !data.file) {\n // The image has no way to be restored (ctrl+z) so we must fix that.\n const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);\n const ctx = canvas.getContext(\"bitmaprenderer\");\n ctx.transferFromImageBitmap(bitmap);\n data.blobPromise = canvas.convertToBlob();\n }\n\n bitmap.close?.();\n data.bitmap = null;\n }\n\n // We can use the id only if it belongs this manager.\n // We must take care of having the right manager because we can copy/paste\n // some images from other documents, hence it'd be a pity to use an id from an\n // other manager.\n isValidId(id) {\n return id.startsWith(`image_${this.#baseId}_`);\n }\n}\n\n/**\n * Class to handle undo/redo.\n * Commands are just saved in a buffer.\n * If we hit some memory issues we could likely use a circular buffer.\n * It has to be used as a singleton.\n */\nclass CommandManager {\n #commands = [];\n\n #locked = false;\n\n #maxSize;\n\n #position = -1;\n\n constructor(maxSize = 128) {\n this.#maxSize = maxSize;\n }\n\n /**\n * @typedef {Object} addOptions\n * @property {function} cmd\n * @property {function} undo\n * @property {function} [post]\n * @property {boolean} mustExec\n * @property {number} type\n * @property {boolean} overwriteIfSameType\n * @property {boolean} keepUndo\n */\n\n /**\n * Add a new couple of commands to be used in case of redo/undo.\n * @param {addOptions} options\n */\n add({\n cmd,\n undo,\n post,\n mustExec,\n type = NaN,\n overwriteIfSameType = false,\n keepUndo = false,\n }) {\n if (mustExec) {\n cmd();\n }\n\n if (this.#locked) {\n return;\n }\n\n const save = { cmd, undo, post, type };\n if (this.#position === -1) {\n if (this.#commands.length > 0) {\n // All the commands have been undone and then a new one is added\n // hence we clear the queue.\n this.#commands.length = 0;\n }\n this.#position = 0;\n this.#commands.push(save);\n return;\n }\n\n if (overwriteIfSameType && this.#commands[this.#position].type === type) {\n // For example when we change a color we don't want to\n // be able to undo all the steps, hence we only want to\n // keep the last undoable action in this sequence of actions.\n if (keepUndo) {\n save.undo = this.#commands[this.#position].undo;\n }\n this.#commands[this.#position] = save;\n return;\n }\n\n const next = this.#position + 1;\n if (next === this.#maxSize) {\n this.#commands.splice(0, 1);\n } else {\n this.#position = next;\n if (next < this.#commands.length) {\n this.#commands.splice(next);\n }\n }\n\n this.#commands.push(save);\n }\n\n /**\n * Undo the last command.\n */\n undo() {\n if (this.#position === -1) {\n // Nothing to undo.\n return;\n }\n\n // Avoid to insert something during the undo execution.\n this.#locked = true;\n const { undo, post } = this.#commands[this.#position];\n undo();\n post?.();\n this.#locked = false;\n\n this.#position -= 1;\n }\n\n /**\n * Redo the last command.\n */\n redo() {\n if (this.#position < this.#commands.length - 1) {\n this.#position += 1;\n\n // Avoid to insert something during the redo execution.\n this.#locked = true;\n const { cmd, post } = this.#commands[this.#position];\n cmd();\n post?.();\n this.#locked = false;\n }\n }\n\n /**\n * Check if there is something to undo.\n * @returns {boolean}\n */\n hasSomethingToUndo() {\n return this.#position !== -1;\n }\n\n /**\n * Check if there is something to redo.\n * @returns {boolean}\n */\n hasSomethingToRedo() {\n return this.#position < this.#commands.length - 1;\n }\n\n cleanType(type) {\n if (this.#position === -1) {\n return;\n }\n for (let i = this.#position; i >= 0; i--) {\n if (this.#commands[i].type !== type) {\n this.#commands.splice(i + 1, this.#position - i);\n this.#position = i;\n return;\n }\n }\n this.#commands.length = 0;\n this.#position = -1;\n }\n\n destroy() {\n this.#commands = null;\n }\n}\n\n/**\n * Class to handle the different keyboards shortcuts we can have on mac or\n * non-mac OSes.\n */\nclass KeyboardManager {\n /**\n * Create a new keyboard manager class.\n * @param {Array} callbacks - an array containing an array of shortcuts\n * and a callback to call.\n * A shortcut is a string like `ctrl+c` or `mac+ctrl+c` for mac OS.\n */\n constructor(callbacks) {\n this.buffer = [];\n this.callbacks = new Map();\n this.allKeys = new Set();\n\n const { isMac } = FeatureTest.platform;\n for (const [keys, callback, options = {}] of callbacks) {\n for (const key of keys) {\n const isMacKey = key.startsWith(\"mac+\");\n if (isMac && isMacKey) {\n this.callbacks.set(key.slice(4), { callback, options });\n this.allKeys.add(key.split(\"+\").at(-1));\n } else if (!isMac && !isMacKey) {\n this.callbacks.set(key, { callback, options });\n this.allKeys.add(key.split(\"+\").at(-1));\n }\n }\n }\n }\n\n /**\n * Serialize an event into a string in order to match a\n * potential key for a callback.\n * @param {KeyboardEvent} event\n * @returns {string}\n */\n #serialize(event) {\n if (event.altKey) {\n this.buffer.push(\"alt\");\n }\n if (event.ctrlKey) {\n this.buffer.push(\"ctrl\");\n }\n if (event.metaKey) {\n this.buffer.push(\"meta\");\n }\n if (event.shiftKey) {\n this.buffer.push(\"shift\");\n }\n this.buffer.push(event.key);\n const str = this.buffer.join(\"+\");\n this.buffer.length = 0;\n\n return str;\n }\n\n /**\n * Execute a callback, if any, for a given keyboard event.\n * The self is used as `this` in the callback.\n * @param {Object} self\n * @param {KeyboardEvent} event\n * @returns\n */\n exec(self, event) {\n if (!this.allKeys.has(event.key)) {\n return;\n }\n const info = this.callbacks.get(this.#serialize(event));\n if (!info) {\n return;\n }\n const {\n callback,\n options: { bubbles = false, args = [], checker = null },\n } = info;\n\n if (checker && !checker(self, event)) {\n return;\n }\n callback.bind(self, ...args, event)();\n\n // For example, ctrl+s in a FreeText must be handled by the viewer, hence\n // the event must bubble.\n if (!bubbles) {\n stopEvent(event);\n }\n }\n}\n\nclass ColorManager {\n static _colorsMapping = new Map([\n [\"CanvasText\", [0, 0, 0]],\n [\"Canvas\", [255, 255, 255]],\n ]);\n\n get _colors() {\n if (\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"LIB\") &&\n typeof document === \"undefined\"\n ) {\n return shadow(this, \"_colors\", ColorManager._colorsMapping);\n }\n\n const colors = new Map([\n [\"CanvasText\", null],\n [\"Canvas\", null],\n ]);\n getColorValues(colors);\n return shadow(this, \"_colors\", colors);\n }\n\n /**\n * In High Contrast Mode, the color on the screen is not always the\n * real color used in the pdf.\n * For example in some cases white can appear to be black but when saving\n * we want to have white.\n * @param {string} color\n * @returns {Array}\n */\n convert(color) {\n const rgb = getRGB(color);\n if (!window.matchMedia(\"(forced-colors: active)\").matches) {\n return rgb;\n }\n\n for (const [name, RGB] of this._colors) {\n if (RGB.every((x, i) => x === rgb[i])) {\n return ColorManager._colorsMapping.get(name);\n }\n }\n return rgb;\n }\n\n /**\n * An input element must have its color value as a hex string\n * and not as color name.\n * So this function converts a name into an hex string.\n * @param {string} name\n * @returns {string}\n */\n getHexCode(name) {\n const rgb = this._colors.get(name);\n if (!rgb) {\n return name;\n }\n return Util.makeHexColor(...rgb);\n }\n}\n\n/**\n * A pdf has several pages and each of them when it will rendered\n * will have an AnnotationEditorLayer which will contain the some\n * new Annotations associated to an editor in order to modify them.\n *\n * This class is used to manage all the different layers, editors and\n * some action like copy/paste, undo/redo, ...\n */\nclass AnnotationEditorUIManager {\n #abortController = new AbortController();\n\n #activeEditor = null;\n\n #allEditors = new Map();\n\n #allLayers = new Map();\n\n #altTextManager = null;\n\n #annotationStorage = null;\n\n #changedExistingAnnotations = null;\n\n #commandManager = new CommandManager();\n\n #copyPasteAC = null;\n\n #currentDrawingSession = null;\n\n #currentPageIndex = 0;\n\n #deletedAnnotationsElementIds = new Set();\n\n #draggingEditors = null;\n\n #editorTypes = null;\n\n #editorsToRescale = new Set();\n\n _editorUndoBar = null;\n\n #enableHighlightFloatingButton = false;\n\n #enableUpdatedAddImage = false;\n\n #enableNewAltTextWhenAddingImage = false;\n\n #filterFactory = null;\n\n #focusMainContainerTimeoutId = null;\n\n #focusManagerAC = null;\n\n #highlightColors = null;\n\n #highlightWhenShiftUp = false;\n\n #highlightToolbar = null;\n\n #idManager = new IdManager();\n\n #isEnabled = false;\n\n #isWaiting = false;\n\n #keyboardManagerAC = null;\n\n #lastActiveElement = null;\n\n #mainHighlightColorPicker = null;\n\n #mlManager = null;\n\n #mode = AnnotationEditorType.NONE;\n\n #selectedEditors = new Set();\n\n #selectedTextNode = null;\n\n #pageColors = null;\n\n #showAllStates = null;\n\n #previousStates = {\n isEditing: false,\n isEmpty: true,\n hasSomethingToUndo: false,\n hasSomethingToRedo: false,\n hasSelectedEditor: false,\n hasSelectedText: false,\n };\n\n #translation = [0, 0];\n\n #translationTimeoutId = null;\n\n #container = null;\n\n #viewer = null;\n\n #updateModeCapability = null;\n\n static TRANSLATE_SMALL = 1; // page units.\n\n static TRANSLATE_BIG = 10; // page units.\n\n static get _keyboardManager() {\n const proto = AnnotationEditorUIManager.prototype;\n\n /**\n * If the focused element is an input, we don't want to handle the arrow.\n * For example, sliders can be controlled with the arrow keys.\n */\n const arrowChecker = self =>\n self.#container.contains(document.activeElement) &&\n document.activeElement.tagName !== \"BUTTON\" &&\n self.hasSomethingToControl();\n\n const textInputChecker = (_self, { target: el }) => {\n if (el instanceof HTMLInputElement) {\n const { type } = el;\n return type !== \"text\" && type !== \"number\";\n }\n return true;\n };\n\n const small = this.TRANSLATE_SMALL;\n const big = this.TRANSLATE_BIG;\n\n return shadow(\n this,\n \"_keyboardManager\",\n new KeyboardManager([\n [\n [\"ctrl+a\", \"mac+meta+a\"],\n proto.selectAll,\n { checker: textInputChecker },\n ],\n [[\"ctrl+z\", \"mac+meta+z\"], proto.undo, { checker: textInputChecker }],\n [\n // On mac, depending of the OS version, the event.key is either \"z\" or\n // \"Z\" when the user presses \"meta+shift+z\".\n [\n \"ctrl+y\",\n \"ctrl+shift+z\",\n \"mac+meta+shift+z\",\n \"ctrl+shift+Z\",\n \"mac+meta+shift+Z\",\n ],\n proto.redo,\n { checker: textInputChecker },\n ],\n [\n [\n \"Backspace\",\n \"alt+Backspace\",\n \"ctrl+Backspace\",\n \"shift+Backspace\",\n \"mac+Backspace\",\n \"mac+alt+Backspace\",\n \"mac+ctrl+Backspace\",\n \"Delete\",\n \"ctrl+Delete\",\n \"shift+Delete\",\n \"mac+Delete\",\n ],\n proto.delete,\n { checker: textInputChecker },\n ],\n [\n [\"Enter\", \"mac+Enter\"],\n proto.addNewEditorFromKeyboard,\n {\n // Those shortcuts can be used in the toolbar for some other actions\n // like zooming, hence we need to check if the container has the\n // focus.\n checker: (self, { target: el }) =>\n !(el instanceof HTMLButtonElement) &&\n self.#container.contains(el) &&\n !self.isEnterHandled,\n },\n ],\n [\n [\" \", \"mac+ \"],\n proto.addNewEditorFromKeyboard,\n {\n // Those shortcuts can be used in the toolbar for some other actions\n // like zooming, hence we need to check if the container has the\n // focus.\n checker: (self, { target: el }) =>\n !(el instanceof HTMLButtonElement) &&\n self.#container.contains(document.activeElement),\n },\n ],\n [[\"Escape\", \"mac+Escape\"], proto.unselectAll],\n [\n [\"ArrowLeft\", \"mac+ArrowLeft\"],\n proto.translateSelectedEditors,\n { args: [-small, 0], checker: arrowChecker },\n ],\n [\n [\"ctrl+ArrowLeft\", \"mac+shift+ArrowLeft\"],\n proto.translateSelectedEditors,\n { args: [-big, 0], checker: arrowChecker },\n ],\n [\n [\"ArrowRight\", \"mac+ArrowRight\"],\n proto.translateSelectedEditors,\n { args: [small, 0], checker: arrowChecker },\n ],\n [\n [\"ctrl+ArrowRight\", \"mac+shift+ArrowRight\"],\n proto.translateSelectedEditors,\n { args: [big, 0], checker: arrowChecker },\n ],\n [\n [\"ArrowUp\", \"mac+ArrowUp\"],\n proto.translateSelectedEditors,\n { args: [0, -small], checker: arrowChecker },\n ],\n [\n [\"ctrl+ArrowUp\", \"mac+shift+ArrowUp\"],\n proto.translateSelectedEditors,\n { args: [0, -big], checker: arrowChecker },\n ],\n [\n [\"ArrowDown\", \"mac+ArrowDown\"],\n proto.translateSelectedEditors,\n { args: [0, small], checker: arrowChecker },\n ],\n [\n [\"ctrl+ArrowDown\", \"mac+shift+ArrowDown\"],\n proto.translateSelectedEditors,\n { args: [0, big], checker: arrowChecker },\n ],\n ])\n );\n }\n\n constructor(\n container,\n viewer,\n altTextManager,\n eventBus,\n pdfDocument,\n pageColors,\n highlightColors,\n enableHighlightFloatingButton,\n enableUpdatedAddImage,\n enableNewAltTextWhenAddingImage,\n mlManager,\n editorUndoBar\n ) {\n const signal = (this._signal = this.#abortController.signal);\n this.#container = container;\n this.#viewer = viewer;\n this.#altTextManager = altTextManager;\n this._eventBus = eventBus;\n eventBus._on(\"editingaction\", this.onEditingAction.bind(this), { signal });\n eventBus._on(\"pagechanging\", this.onPageChanging.bind(this), { signal });\n eventBus._on(\"scalechanging\", this.onScaleChanging.bind(this), { signal });\n eventBus._on(\"rotationchanging\", this.onRotationChanging.bind(this), {\n signal,\n });\n eventBus._on(\"setpreference\", this.onSetPreference.bind(this), { signal });\n eventBus._on(\n \"switchannotationeditorparams\",\n evt => this.updateParams(evt.type, evt.value),\n { signal }\n );\n this.#addSelectionListener();\n this.#addDragAndDropListeners();\n this.#addKeyboardManager();\n this.#annotationStorage = pdfDocument.annotationStorage;\n this.#filterFactory = pdfDocument.filterFactory;\n this.#pageColors = pageColors;\n this.#highlightColors = highlightColors || null;\n this.#enableHighlightFloatingButton = enableHighlightFloatingButton;\n this.#enableUpdatedAddImage = enableUpdatedAddImage;\n this.#enableNewAltTextWhenAddingImage = enableNewAltTextWhenAddingImage;\n this.#mlManager = mlManager || null;\n this.viewParameters = {\n realScale: PixelsPerInch.PDF_TO_CSS_UNITS,\n rotation: 0,\n };\n this.isShiftKeyDown = false;\n this._editorUndoBar = editorUndoBar || null;\n\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"TESTING\")) {\n Object.defineProperty(this, \"reset\", {\n value: () => {\n this.selectAll();\n this.delete();\n this.#idManager.reset();\n },\n });\n }\n }\n\n destroy() {\n this.#updateModeCapability?.resolve();\n this.#updateModeCapability = null;\n\n this.#abortController?.abort();\n this.#abortController = null;\n this._signal = null;\n\n for (const layer of this.#allLayers.values()) {\n layer.destroy();\n }\n this.#allLayers.clear();\n this.#allEditors.clear();\n this.#editorsToRescale.clear();\n this.#activeEditor = null;\n this.#selectedEditors.clear();\n this.#commandManager.destroy();\n this.#altTextManager?.destroy();\n this.#highlightToolbar?.hide();\n this.#highlightToolbar = null;\n if (this.#focusMainContainerTimeoutId) {\n clearTimeout(this.#focusMainContainerTimeoutId);\n this.#focusMainContainerTimeoutId = null;\n }\n if (this.#translationTimeoutId) {\n clearTimeout(this.#translationTimeoutId);\n this.#translationTimeoutId = null;\n }\n this._editorUndoBar?.destroy();\n }\n\n combinedSignal(ac) {\n return AbortSignal.any([this._signal, ac.signal]);\n }\n\n get mlManager() {\n return this.#mlManager;\n }\n\n get useNewAltTextFlow() {\n return this.#enableUpdatedAddImage;\n }\n\n get useNewAltTextWhenAddingImage() {\n return this.#enableNewAltTextWhenAddingImage;\n }\n\n get hcmFilter() {\n return shadow(\n this,\n \"hcmFilter\",\n this.#pageColors\n ? this.#filterFactory.addHCMFilter(\n this.#pageColors.foreground,\n this.#pageColors.background\n )\n : \"none\"\n );\n }\n\n get direction() {\n return shadow(\n this,\n \"direction\",\n getComputedStyle(this.#container).direction\n );\n }\n\n get highlightColors() {\n return shadow(\n this,\n \"highlightColors\",\n this.#highlightColors\n ? new Map(\n this.#highlightColors\n .split(\",\")\n .map(pair => pair.split(\"=\").map(x => x.trim()))\n )\n : null\n );\n }\n\n get highlightColorNames() {\n return shadow(\n this,\n \"highlightColorNames\",\n this.highlightColors\n ? new Map(Array.from(this.highlightColors, e => e.reverse()))\n : null\n );\n }\n\n /**\n * Set the current drawing session.\n * @param {AnnotationEditorLayer} layer\n */\n setCurrentDrawingSession(layer) {\n if (layer) {\n this.unselectAll();\n this.disableUserSelect(true);\n } else {\n this.disableUserSelect(false);\n }\n this.#currentDrawingSession = layer;\n }\n\n setMainHighlightColorPicker(colorPicker) {\n this.#mainHighlightColorPicker = colorPicker;\n }\n\n editAltText(editor, firstTime = false) {\n this.#altTextManager?.editAltText(this, editor, firstTime);\n }\n\n switchToMode(mode, callback) {\n // Switching to a mode can be asynchronous.\n this._eventBus.on(\"annotationeditormodechanged\", callback, {\n once: true,\n signal: this._signal,\n });\n this._eventBus.dispatch(\"showannotationeditorui\", {\n source: this,\n mode,\n });\n }\n\n setPreference(name, value) {\n this._eventBus.dispatch(\"setpreference\", {\n source: this,\n name,\n value,\n });\n }\n\n onSetPreference({ name, value }) {\n switch (name) {\n case \"enableNewAltTextWhenAddingImage\":\n this.#enableNewAltTextWhenAddingImage = value;\n break;\n }\n }\n\n onPageChanging({ pageNumber }) {\n this.#currentPageIndex = pageNumber - 1;\n }\n\n focusMainContainer() {\n this.#container.focus();\n }\n\n findParent(x, y) {\n for (const layer of this.#allLayers.values()) {\n const {\n x: layerX,\n y: layerY,\n width,\n height,\n } = layer.div.getBoundingClientRect();\n if (\n x >= layerX &&\n x <= layerX + width &&\n y >= layerY &&\n y <= layerY + height\n ) {\n return layer;\n }\n }\n return null;\n }\n\n disableUserSelect(value = false) {\n this.#viewer.classList.toggle(\"noUserSelect\", value);\n }\n\n addShouldRescale(editor) {\n this.#editorsToRescale.add(editor);\n }\n\n removeShouldRescale(editor) {\n this.#editorsToRescale.delete(editor);\n }\n\n onScaleChanging({ scale }) {\n this.commitOrRemove();\n this.viewParameters.realScale = scale * PixelsPerInch.PDF_TO_CSS_UNITS;\n for (const editor of this.#editorsToRescale) {\n editor.onScaleChanging();\n }\n this.#currentDrawingSession?.onScaleChanging();\n }\n\n onRotationChanging({ pagesRotation }) {\n this.commitOrRemove();\n this.viewParameters.rotation = pagesRotation;\n }\n\n #getAnchorElementForSelection({ anchorNode }) {\n return anchorNode.nodeType === Node.TEXT_NODE\n ? anchorNode.parentElement\n : anchorNode;\n }\n\n #getLayerForTextLayer(textLayer) {\n const { currentLayer } = this;\n if (currentLayer.hasTextLayer(textLayer)) {\n return currentLayer;\n }\n for (const layer of this.#allLayers.values()) {\n if (layer.hasTextLayer(textLayer)) {\n return layer;\n }\n }\n return null;\n }\n\n highlightSelection(methodOfCreation = \"\") {\n const selection = document.getSelection();\n if (!selection || selection.isCollapsed) {\n return;\n }\n const { anchorNode, anchorOffset, focusNode, focusOffset } = selection;\n const text = selection.toString();\n const anchorElement = this.#getAnchorElementForSelection(selection);\n const textLayer = anchorElement.closest(\".textLayer\");\n const boxes = this.getSelectionBoxes(textLayer);\n if (!boxes) {\n return;\n }\n selection.empty();\n\n const layer = this.#getLayerForTextLayer(textLayer);\n const isNoneMode = this.#mode === AnnotationEditorType.NONE;\n const callback = () => {\n layer?.createAndAddNewEditor({ x: 0, y: 0 }, false, {\n methodOfCreation,\n boxes,\n anchorNode,\n anchorOffset,\n focusNode,\n focusOffset,\n text,\n });\n if (isNoneMode) {\n this.showAllEditors(\"highlight\", true, /* updateButton = */ true);\n }\n };\n if (isNoneMode) {\n this.switchToMode(AnnotationEditorType.HIGHLIGHT, callback);\n return;\n }\n callback();\n }\n\n #displayHighlightToolbar() {\n const selection = document.getSelection();\n if (!selection || selection.isCollapsed) {\n return;\n }\n const anchorElement = this.#getAnchorElementForSelection(selection);\n const textLayer = anchorElement.closest(\".textLayer\");\n const boxes = this.getSelectionBoxes(textLayer);\n if (!boxes) {\n return;\n }\n this.#highlightToolbar ||= new HighlightToolbar(this);\n this.#highlightToolbar.show(textLayer, boxes, this.direction === \"ltr\");\n }\n\n /**\n * Add an editor in the annotation storage.\n * @param {AnnotationEditor} editor\n */\n addToAnnotationStorage(editor) {\n if (\n !editor.isEmpty() &&\n this.#annotationStorage &&\n !this.#annotationStorage.has(editor.id)\n ) {\n this.#annotationStorage.setValue(editor.id, editor);\n }\n }\n\n #selectionChange() {\n const selection = document.getSelection();\n if (!selection || selection.isCollapsed) {\n if (this.#selectedTextNode) {\n this.#highlightToolbar?.hide();\n this.#selectedTextNode = null;\n this.#dispatchUpdateStates({\n hasSelectedText: false,\n });\n }\n return;\n }\n const { anchorNode } = selection;\n if (anchorNode === this.#selectedTextNode) {\n return;\n }\n\n const anchorElement = this.#getAnchorElementForSelection(selection);\n const textLayer = anchorElement.closest(\".textLayer\");\n if (!textLayer) {\n if (this.#selectedTextNode) {\n this.#highlightToolbar?.hide();\n this.#selectedTextNode = null;\n this.#dispatchUpdateStates({\n hasSelectedText: false,\n });\n }\n return;\n }\n\n this.#highlightToolbar?.hide();\n this.#selectedTextNode = anchorNode;\n this.#dispatchUpdateStates({\n hasSelectedText: true,\n });\n\n if (\n this.#mode !== AnnotationEditorType.HIGHLIGHT &&\n this.#mode !== AnnotationEditorType.NONE\n ) {\n return;\n }\n\n if (this.#mode === AnnotationEditorType.HIGHLIGHT) {\n this.showAllEditors(\"highlight\", true, /* updateButton = */ true);\n }\n\n this.#highlightWhenShiftUp = this.isShiftKeyDown;\n if (!this.isShiftKeyDown) {\n const activeLayer =\n this.#mode === AnnotationEditorType.HIGHLIGHT\n ? this.#getLayerForTextLayer(textLayer)\n : null;\n activeLayer?.toggleDrawing();\n\n const ac = new AbortController();\n const signal = this.combinedSignal(ac);\n\n const pointerup = e => {\n if (e.type === \"pointerup\" && e.button !== 0) {\n // Do nothing on right click.\n return;\n }\n ac.abort();\n activeLayer?.toggleDrawing(true);\n if (e.type === \"pointerup\") {\n this.#onSelectEnd(\"main_toolbar\");\n }\n };\n window.addEventListener(\"pointerup\", pointerup, { signal });\n window.addEventListener(\"blur\", pointerup, { signal });\n }\n }\n\n #onSelectEnd(methodOfCreation = \"\") {\n if (this.#mode === AnnotationEditorType.HIGHLIGHT) {\n this.highlightSelection(methodOfCreation);\n } else if (this.#enableHighlightFloatingButton) {\n this.#displayHighlightToolbar();\n }\n }\n\n #addSelectionListener() {\n document.addEventListener(\n \"selectionchange\",\n this.#selectionChange.bind(this),\n { signal: this._signal }\n );\n }\n\n #addFocusManager() {\n if (this.#focusManagerAC) {\n return;\n }\n this.#focusManagerAC = new AbortController();\n const signal = this.combinedSignal(this.#focusManagerAC);\n\n window.addEventListener(\"focus\", this.focus.bind(this), { signal });\n window.addEventListener(\"blur\", this.blur.bind(this), { signal });\n }\n\n #removeFocusManager() {\n this.#focusManagerAC?.abort();\n this.#focusManagerAC = null;\n }\n\n blur() {\n this.isShiftKeyDown = false;\n if (this.#highlightWhenShiftUp) {\n this.#highlightWhenShiftUp = false;\n this.#onSelectEnd(\"main_toolbar\");\n }\n if (!this.hasSelection) {\n return;\n }\n // When several editors are selected and the window loses focus, we want to\n // keep the last active element in order to be able to focus it again when\n // the window gets the focus back but we don't want to trigger any focus\n // callbacks else only one editor will be selected.\n const { activeElement } = document;\n for (const editor of this.#selectedEditors) {\n if (editor.div.contains(activeElement)) {\n this.#lastActiveElement = [editor, activeElement];\n editor._focusEventsAllowed = false;\n break;\n }\n }\n }\n\n focus() {\n if (!this.#lastActiveElement) {\n return;\n }\n const [lastEditor, lastActiveElement] = this.#lastActiveElement;\n this.#lastActiveElement = null;\n lastActiveElement.addEventListener(\n \"focusin\",\n () => {\n lastEditor._focusEventsAllowed = true;\n },\n { once: true, signal: this._signal }\n );\n lastActiveElement.focus();\n }\n\n #addKeyboardManager() {\n if (this.#keyboardManagerAC) {\n return;\n }\n this.#keyboardManagerAC = new AbortController();\n const signal = this.combinedSignal(this.#keyboardManagerAC);\n\n // The keyboard events are caught at the container level in order to be able\n // to execute some callbacks even if the current page doesn't have focus.\n window.addEventListener(\"keydown\", this.keydown.bind(this), { signal });\n window.addEventListener(\"keyup\", this.keyup.bind(this), { signal });\n }\n\n #removeKeyboardManager() {\n this.#keyboardManagerAC?.abort();\n this.#keyboardManagerAC = null;\n }\n\n #addCopyPasteListeners() {\n if (this.#copyPasteAC) {\n return;\n }\n this.#copyPasteAC = new AbortController();\n const signal = this.combinedSignal(this.#copyPasteAC);\n\n document.addEventListener(\"copy\", this.copy.bind(this), { signal });\n document.addEventListener(\"cut\", this.cut.bind(this), { signal });\n document.addEventListener(\"paste\", this.paste.bind(this), { signal });\n }\n\n #removeCopyPasteListeners() {\n this.#copyPasteAC?.abort();\n this.#copyPasteAC = null;\n }\n\n #addDragAndDropListeners() {\n const signal = this._signal;\n document.addEventListener(\"dragover\", this.dragOver.bind(this), { signal });\n document.addEventListener(\"drop\", this.drop.bind(this), { signal });\n }\n\n addEditListeners() {\n this.#addKeyboardManager();\n this.#addCopyPasteListeners();\n }\n\n removeEditListeners() {\n this.#removeKeyboardManager();\n this.#removeCopyPasteListeners();\n }\n\n dragOver(event) {\n for (const { type } of event.dataTransfer.items) {\n for (const editorType of this.#editorTypes) {\n if (editorType.isHandlingMimeForPasting(type)) {\n event.dataTransfer.dropEffect = \"copy\";\n event.preventDefault();\n return;\n }\n }\n }\n }\n\n /**\n * Drop callback.\n * @param {DragEvent} event\n */\n drop(event) {\n for (const item of event.dataTransfer.items) {\n for (const editorType of this.#editorTypes) {\n if (editorType.isHandlingMimeForPasting(item.type)) {\n editorType.paste(item, this.currentLayer);\n event.preventDefault();\n return;\n }\n }\n }\n }\n\n /**\n * Copy callback.\n * @param {ClipboardEvent} event\n */\n copy(event) {\n event.preventDefault();\n\n // An editor is being edited so just commit it.\n this.#activeEditor?.commitOrRemove();\n\n if (!this.hasSelection) {\n return;\n }\n\n const editors = [];\n for (const editor of this.#selectedEditors) {\n const serialized = editor.serialize(/* isForCopying = */ true);\n if (serialized) {\n editors.push(serialized);\n }\n }\n if (editors.length === 0) {\n return;\n }\n\n event.clipboardData.setData(\"application/pdfjs\", JSON.stringify(editors));\n }\n\n /**\n * Cut callback.\n * @param {ClipboardEvent} event\n */\n cut(event) {\n this.copy(event);\n this.delete();\n }\n\n /**\n * Paste callback.\n * @param {ClipboardEvent} event\n */\n async paste(event) {\n event.preventDefault();\n const { clipboardData } = event;\n for (const item of clipboardData.items) {\n for (const editorType of this.#editorTypes) {\n if (editorType.isHandlingMimeForPasting(item.type)) {\n editorType.paste(item, this.currentLayer);\n return;\n }\n }\n }\n\n let data = clipboardData.getData(\"application/pdfjs\");\n if (!data) {\n return;\n }\n\n try {\n data = JSON.parse(data);\n } catch (ex) {\n warn(`paste: \"${ex.message}\".`);\n return;\n }\n\n if (!Array.isArray(data)) {\n return;\n }\n\n this.unselectAll();\n const layer = this.currentLayer;\n\n try {\n const newEditors = [];\n for (const editor of data) {\n const deserializedEditor = await layer.deserialize(editor);\n if (!deserializedEditor) {\n return;\n }\n newEditors.push(deserializedEditor);\n }\n\n const cmd = () => {\n for (const editor of newEditors) {\n this.#addEditorToLayer(editor);\n }\n this.#selectEditors(newEditors);\n };\n const undo = () => {\n for (const editor of newEditors) {\n editor.remove();\n }\n };\n this.addCommands({ cmd, undo, mustExec: true });\n } catch (ex) {\n warn(`paste: \"${ex.message}\".`);\n }\n }\n\n /**\n * Keydown callback.\n * @param {KeyboardEvent} event\n */\n keydown(event) {\n if (!this.isShiftKeyDown && event.key === \"Shift\") {\n this.isShiftKeyDown = true;\n }\n if (\n this.#mode !== AnnotationEditorType.NONE &&\n !this.isEditorHandlingKeyboard\n ) {\n AnnotationEditorUIManager._keyboardManager.exec(this, event);\n }\n }\n\n /**\n * Keyup callback.\n * @param {KeyboardEvent} event\n */\n keyup(event) {\n if (this.isShiftKeyDown && event.key === \"Shift\") {\n this.isShiftKeyDown = false;\n if (this.#highlightWhenShiftUp) {\n this.#highlightWhenShiftUp = false;\n this.#onSelectEnd(\"main_toolbar\");\n }\n }\n }\n\n /**\n * Execute an action for a given name.\n * For example, the user can click on the \"Undo\" entry in the context menu\n * and it'll trigger the undo action.\n */\n onEditingAction({ name }) {\n switch (name) {\n case \"undo\":\n case \"redo\":\n case \"delete\":\n case \"selectAll\":\n this[name]();\n break;\n case \"highlightSelection\":\n this.highlightSelection(\"context_menu\");\n break;\n }\n }\n\n /**\n * Update the different possible states of this manager, e.g. is there\n * something to undo, redo, ...\n * @param {Object} details\n */\n #dispatchUpdateStates(details) {\n const hasChanged = Object.entries(details).some(\n ([key, value]) => this.#previousStates[key] !== value\n );\n\n if (hasChanged) {\n this._eventBus.dispatch(\"annotationeditorstateschanged\", {\n source: this,\n details: Object.assign(this.#previousStates, details),\n });\n // We could listen on our own event but it sounds like a bit weird and\n // it's a way to simpler to handle that stuff here instead of having to\n // add something in every place where an editor can be unselected.\n if (\n this.#mode === AnnotationEditorType.HIGHLIGHT &&\n details.hasSelectedEditor === false\n ) {\n this.#dispatchUpdateUI([\n [AnnotationEditorParamsType.HIGHLIGHT_FREE, true],\n ]);\n }\n }\n }\n\n #dispatchUpdateUI(details) {\n this._eventBus.dispatch(\"annotationeditorparamschanged\", {\n source: this,\n details,\n });\n }\n\n /**\n * Set the editing state.\n * It can be useful to temporarily disable it when the user is editing a\n * FreeText annotation.\n * @param {boolean} isEditing\n */\n setEditingState(isEditing) {\n if (isEditing) {\n this.#addFocusManager();\n this.#addCopyPasteListeners();\n this.#dispatchUpdateStates({\n isEditing: this.#mode !== AnnotationEditorType.NONE,\n isEmpty: this.#isEmpty(),\n hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),\n hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),\n hasSelectedEditor: false,\n });\n } else {\n this.#removeFocusManager();\n this.#removeCopyPasteListeners();\n this.#dispatchUpdateStates({\n isEditing: false,\n });\n this.disableUserSelect(false);\n }\n }\n\n registerEditorTypes(types) {\n if (this.#editorTypes) {\n return;\n }\n this.#editorTypes = types;\n for (const editorType of this.#editorTypes) {\n this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);\n }\n }\n\n /**\n * Get an id.\n * @returns {string}\n */\n getId() {\n return this.#idManager.id;\n }\n\n get currentLayer() {\n return this.#allLayers.get(this.#currentPageIndex);\n }\n\n getLayer(pageIndex) {\n return this.#allLayers.get(pageIndex);\n }\n\n get currentPageIndex() {\n return this.#currentPageIndex;\n }\n\n /**\n * Add a new layer for a page which will contains the editors.\n * @param {AnnotationEditorLayer} layer\n */\n addLayer(layer) {\n this.#allLayers.set(layer.pageIndex, layer);\n if (this.#isEnabled) {\n layer.enable();\n } else {\n layer.disable();\n }\n }\n\n /**\n * Remove a layer.\n * @param {AnnotationEditorLayer} layer\n */\n removeLayer(layer) {\n this.#allLayers.delete(layer.pageIndex);\n }\n\n /**\n * Change the editor mode (None, FreeText, Ink, ...)\n * @param {number} mode\n * @param {string|null} editId\n * @param {boolean} [isFromKeyboard] - true if the mode change is due to a\n * keyboard action.\n */\n async updateMode(mode, editId = null, isFromKeyboard = false) {\n if (this.#mode === mode) {\n return;\n }\n\n if (this.#updateModeCapability) {\n await this.#updateModeCapability.promise;\n if (!this.#updateModeCapability) {\n // This ui manager has been destroyed.\n return;\n }\n }\n\n this.#updateModeCapability = Promise.withResolvers();\n\n this.#mode = mode;\n if (mode === AnnotationEditorType.NONE) {\n this.setEditingState(false);\n this.#disableAll();\n\n this._editorUndoBar?.hide();\n\n this.#updateModeCapability.resolve();\n return;\n }\n this.setEditingState(true);\n await this.#enableAll();\n this.unselectAll();\n for (const layer of this.#allLayers.values()) {\n layer.updateMode(mode);\n }\n if (!editId) {\n if (isFromKeyboard) {\n this.addNewEditorFromKeyboard();\n }\n\n this.#updateModeCapability.resolve();\n return;\n }\n\n for (const editor of this.#allEditors.values()) {\n if (editor.annotationElementId === editId) {\n this.setSelected(editor);\n editor.enterInEditMode();\n } else {\n editor.unselect();\n }\n }\n\n this.#updateModeCapability.resolve();\n }\n\n addNewEditorFromKeyboard() {\n if (this.currentLayer.canCreateNewEmptyEditor()) {\n this.currentLayer.addNewEditor();\n }\n }\n\n /**\n * Update the toolbar if it's required to reflect the tool currently used.\n * @param {number} mode\n * @returns {undefined}\n */\n updateToolbar(mode) {\n if (mode === this.#mode) {\n return;\n }\n this._eventBus.dispatch(\"switchannotationeditormode\", {\n source: this,\n mode,\n });\n }\n\n /**\n * Update a parameter in the current editor or globally.\n * @param {number} type\n * @param {*} value\n */\n updateParams(type, value) {\n if (!this.#editorTypes) {\n return;\n }\n\n switch (type) {\n case AnnotationEditorParamsType.CREATE:\n this.currentLayer.addNewEditor();\n return;\n case AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:\n this.#mainHighlightColorPicker?.updateColor(value);\n break;\n case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:\n this._eventBus.dispatch(\"reporttelemetry\", {\n source: this,\n details: {\n type: \"editing\",\n data: {\n type: \"highlight\",\n action: \"toggle_visibility\",\n },\n },\n });\n (this.#showAllStates ||= new Map()).set(type, value);\n this.showAllEditors(\"highlight\", value);\n break;\n }\n\n for (const editor of this.#selectedEditors) {\n editor.updateParams(type, value);\n }\n\n for (const editorType of this.#editorTypes) {\n editorType.updateDefaultParams(type, value);\n }\n }\n\n showAllEditors(type, visible, updateButton = false) {\n for (const editor of this.#allEditors.values()) {\n if (editor.editorType === type) {\n editor.show(visible);\n }\n }\n const state =\n this.#showAllStates?.get(AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL) ??\n true;\n if (state !== visible) {\n this.#dispatchUpdateUI([\n [AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL, visible],\n ]);\n }\n }\n\n enableWaiting(mustWait = false) {\n if (this.#isWaiting === mustWait) {\n return;\n }\n this.#isWaiting = mustWait;\n for (const layer of this.#allLayers.values()) {\n if (mustWait) {\n layer.disableClick();\n } else {\n layer.enableClick();\n }\n layer.div.classList.toggle(\"waiting\", mustWait);\n }\n }\n\n /**\n * Enable all the layers.\n */\n async #enableAll() {\n if (!this.#isEnabled) {\n this.#isEnabled = true;\n const promises = [];\n for (const layer of this.#allLayers.values()) {\n promises.push(layer.enable());\n }\n await Promise.all(promises);\n for (const editor of this.#allEditors.values()) {\n editor.enable();\n }\n }\n }\n\n /**\n * Disable all the layers.\n */\n #disableAll() {\n this.unselectAll();\n if (this.#isEnabled) {\n this.#isEnabled = false;\n for (const layer of this.#allLayers.values()) {\n layer.disable();\n }\n for (const editor of this.#allEditors.values()) {\n editor.disable();\n }\n }\n }\n\n /**\n * Get all the editors belonging to a given page.\n * @param {number} pageIndex\n * @returns {Array}\n */\n getEditors(pageIndex) {\n const editors = [];\n for (const editor of this.#allEditors.values()) {\n if (editor.pageIndex === pageIndex) {\n editors.push(editor);\n }\n }\n return editors;\n }\n\n /**\n * Get an editor with the given id.\n * @param {string} id\n * @returns {AnnotationEditor}\n */\n getEditor(id) {\n return this.#allEditors.get(id);\n }\n\n /**\n * Add a new editor.\n * @param {AnnotationEditor} editor\n */\n addEditor(editor) {\n this.#allEditors.set(editor.id, editor);\n }\n\n /**\n * Remove an editor.\n * @param {AnnotationEditor} editor\n */\n removeEditor(editor) {\n if (editor.div.contains(document.activeElement)) {\n if (this.#focusMainContainerTimeoutId) {\n clearTimeout(this.#focusMainContainerTimeoutId);\n }\n this.#focusMainContainerTimeoutId = setTimeout(() => {\n // When the div is removed from DOM the focus can move on the\n // document.body, so we need to move it back to the main container.\n this.focusMainContainer();\n this.#focusMainContainerTimeoutId = null;\n }, 0);\n }\n this.#allEditors.delete(editor.id);\n this.unselect(editor);\n if (\n !editor.annotationElementId ||\n !this.#deletedAnnotationsElementIds.has(editor.annotationElementId)\n ) {\n this.#annotationStorage?.remove(editor.id);\n }\n }\n\n /**\n * The annotation element with the given id has been deleted.\n * @param {AnnotationEditor} editor\n */\n addDeletedAnnotationElement(editor) {\n this.#deletedAnnotationsElementIds.add(editor.annotationElementId);\n this.addChangedExistingAnnotation(editor);\n editor.deleted = true;\n }\n\n /**\n * Check if the annotation element with the given id has been deleted.\n * @param {string} annotationElementId\n * @returns {boolean}\n */\n isDeletedAnnotationElement(annotationElementId) {\n return this.#deletedAnnotationsElementIds.has(annotationElementId);\n }\n\n /**\n * The annotation element with the given id have been restored.\n * @param {AnnotationEditor} editor\n */\n removeDeletedAnnotationElement(editor) {\n this.#deletedAnnotationsElementIds.delete(editor.annotationElementId);\n this.removeChangedExistingAnnotation(editor);\n editor.deleted = false;\n }\n\n /**\n * Add an editor to the layer it belongs to or add it to the global map.\n * @param {AnnotationEditor} editor\n */\n #addEditorToLayer(editor) {\n const layer = this.#allLayers.get(editor.pageIndex);\n if (layer) {\n layer.addOrRebuild(editor);\n } else {\n this.addEditor(editor);\n this.addToAnnotationStorage(editor);\n }\n }\n\n /**\n * Set the given editor as the active one.\n * @param {AnnotationEditor} editor\n */\n setActiveEditor(editor) {\n if (this.#activeEditor === editor) {\n return;\n }\n\n this.#activeEditor = editor;\n if (editor) {\n this.#dispatchUpdateUI(editor.propertiesToUpdate);\n }\n }\n\n get #lastSelectedEditor() {\n let ed = null;\n for (ed of this.#selectedEditors) {\n // Iterate to get the last element.\n }\n return ed;\n }\n\n /**\n * Update the UI of the active editor.\n * @param {AnnotationEditor} editor\n */\n updateUI(editor) {\n if (this.#lastSelectedEditor === editor) {\n this.#dispatchUpdateUI(editor.propertiesToUpdate);\n }\n }\n\n updateUIForDefaultProperties(editorType) {\n this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);\n }\n\n /**\n * Add or remove an editor the current selection.\n * @param {AnnotationEditor} editor\n */\n toggleSelected(editor) {\n if (this.#selectedEditors.has(editor)) {\n this.#selectedEditors.delete(editor);\n editor.unselect();\n this.#dispatchUpdateStates({\n hasSelectedEditor: this.hasSelection,\n });\n return;\n }\n this.#selectedEditors.add(editor);\n editor.select();\n this.#dispatchUpdateUI(editor.propertiesToUpdate);\n this.#dispatchUpdateStates({\n hasSelectedEditor: true,\n });\n }\n\n /**\n * Set the last selected editor.\n * @param {AnnotationEditor} editor\n */\n setSelected(editor) {\n this.#currentDrawingSession?.commitOrRemove();\n for (const ed of this.#selectedEditors) {\n if (ed !== editor) {\n ed.unselect();\n }\n }\n this.#selectedEditors.clear();\n\n this.#selectedEditors.add(editor);\n editor.select();\n this.#dispatchUpdateUI(editor.propertiesToUpdate);\n this.#dispatchUpdateStates({\n hasSelectedEditor: true,\n });\n }\n\n /**\n * Check if the editor is selected.\n * @param {AnnotationEditor} editor\n */\n isSelected(editor) {\n return this.#selectedEditors.has(editor);\n }\n\n get firstSelectedEditor() {\n return this.#selectedEditors.values().next().value;\n }\n\n /**\n * Unselect an editor.\n * @param {AnnotationEditor} editor\n */\n unselect(editor) {\n editor.unselect();\n this.#selectedEditors.delete(editor);\n this.#dispatchUpdateStates({\n hasSelectedEditor: this.hasSelection,\n });\n }\n\n get hasSelection() {\n return this.#selectedEditors.size !== 0;\n }\n\n get isEnterHandled() {\n return (\n this.#selectedEditors.size === 1 &&\n this.firstSelectedEditor.isEnterHandled\n );\n }\n\n /**\n * Undo the last command.\n */\n undo() {\n this.#commandManager.undo();\n this.#dispatchUpdateStates({\n hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),\n hasSomethingToRedo: true,\n isEmpty: this.#isEmpty(),\n });\n this._editorUndoBar?.hide();\n }\n\n /**\n * Redo the last undoed command.\n */\n redo() {\n this.#commandManager.redo();\n this.#dispatchUpdateStates({\n hasSomethingToUndo: true,\n hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),\n isEmpty: this.#isEmpty(),\n });\n }\n\n /**\n * Add a command to execute (cmd) and another one to undo it.\n * @param {Object} params\n */\n addCommands(params) {\n this.#commandManager.add(params);\n this.#dispatchUpdateStates({\n hasSomethingToUndo: true,\n hasSomethingToRedo: false,\n isEmpty: this.#isEmpty(),\n });\n }\n\n cleanUndoStack(type) {\n this.#commandManager.cleanType(type);\n }\n\n #isEmpty() {\n if (this.#allEditors.size === 0) {\n return true;\n }\n\n if (this.#allEditors.size === 1) {\n for (const editor of this.#allEditors.values()) {\n return editor.isEmpty();\n }\n }\n\n return false;\n }\n\n /**\n * Delete the current editor or all.\n */\n delete() {\n this.commitOrRemove();\n const drawingEditor = this.currentLayer?.endDrawingSession(\n /* isAborted = */ true\n );\n if (!this.hasSelection && !drawingEditor) {\n return;\n }\n\n const editors = drawingEditor\n ? [drawingEditor]\n : [...this.#selectedEditors];\n const cmd = () => {\n this._editorUndoBar?.show(\n undo,\n editors.length === 1 ? editors[0].editorType : editors.length\n );\n for (const editor of editors) {\n editor.remove();\n }\n };\n const undo = () => {\n for (const editor of editors) {\n this.#addEditorToLayer(editor);\n }\n };\n\n this.addCommands({ cmd, undo, mustExec: true });\n }\n\n commitOrRemove() {\n // An editor is being edited so just commit it.\n this.#activeEditor?.commitOrRemove();\n }\n\n hasSomethingToControl() {\n return this.#activeEditor || this.hasSelection;\n }\n\n /**\n * Select the editors.\n * @param {Array} editors\n */\n #selectEditors(editors) {\n for (const editor of this.#selectedEditors) {\n editor.unselect();\n }\n this.#selectedEditors.clear();\n for (const editor of editors) {\n if (editor.isEmpty()) {\n continue;\n }\n this.#selectedEditors.add(editor);\n editor.select();\n }\n this.#dispatchUpdateStates({ hasSelectedEditor: this.hasSelection });\n }\n\n /**\n * Select all the editors.\n */\n selectAll() {\n for (const editor of this.#selectedEditors) {\n editor.commit();\n }\n this.#selectEditors(this.#allEditors.values());\n }\n\n /**\n * Unselect all the selected editors.\n */\n unselectAll() {\n if (this.#activeEditor) {\n // An editor is being edited so just commit it.\n this.#activeEditor.commitOrRemove();\n if (this.#mode !== AnnotationEditorType.NONE) {\n // If the mode is NONE, we want to really unselect the editor, hence we\n // mustn't return here.\n return;\n }\n }\n\n if (this.#currentDrawingSession?.commitOrRemove()) {\n return;\n }\n\n if (!this.hasSelection) {\n return;\n }\n for (const editor of this.#selectedEditors) {\n editor.unselect();\n }\n this.#selectedEditors.clear();\n this.#dispatchUpdateStates({\n hasSelectedEditor: false,\n });\n }\n\n translateSelectedEditors(x, y, noCommit = false) {\n if (!noCommit) {\n this.commitOrRemove();\n }\n if (!this.hasSelection) {\n return;\n }\n\n this.#translation[0] += x;\n this.#translation[1] += y;\n const [totalX, totalY] = this.#translation;\n const editors = [...this.#selectedEditors];\n\n // We don't want to have an undo/redo for each translation so we wait a bit\n // before adding the command to the command manager.\n const TIME_TO_WAIT = 1000;\n\n if (this.#translationTimeoutId) {\n clearTimeout(this.#translationTimeoutId);\n }\n\n this.#translationTimeoutId = setTimeout(() => {\n this.#translationTimeoutId = null;\n this.#translation[0] = this.#translation[1] = 0;\n\n this.addCommands({\n cmd: () => {\n for (const editor of editors) {\n if (this.#allEditors.has(editor.id)) {\n editor.translateInPage(totalX, totalY);\n }\n }\n },\n undo: () => {\n for (const editor of editors) {\n if (this.#allEditors.has(editor.id)) {\n editor.translateInPage(-totalX, -totalY);\n }\n }\n },\n mustExec: false,\n });\n }, TIME_TO_WAIT);\n\n for (const editor of editors) {\n editor.translateInPage(x, y);\n }\n }\n\n /**\n * Set up the drag session for moving the selected editors.\n */\n setUpDragSession() {\n // Note: don't use any references to the editor's parent which can be null\n // if the editor belongs to a destroyed page.\n if (!this.hasSelection) {\n return;\n }\n // Avoid to have spurious text selection in the text layer when dragging.\n this.disableUserSelect(true);\n this.#draggingEditors = new Map();\n for (const editor of this.#selectedEditors) {\n this.#draggingEditors.set(editor, {\n savedX: editor.x,\n savedY: editor.y,\n savedPageIndex: editor.pageIndex,\n newX: 0,\n newY: 0,\n newPageIndex: -1,\n });\n }\n }\n\n /**\n * Ends the drag session.\n * @returns {boolean} true if at least one editor has been moved.\n */\n endDragSession() {\n if (!this.#draggingEditors) {\n return false;\n }\n this.disableUserSelect(false);\n const map = this.#draggingEditors;\n this.#draggingEditors = null;\n let mustBeAddedInUndoStack = false;\n\n for (const [{ x, y, pageIndex }, value] of map) {\n value.newX = x;\n value.newY = y;\n value.newPageIndex = pageIndex;\n mustBeAddedInUndoStack ||=\n x !== value.savedX ||\n y !== value.savedY ||\n pageIndex !== value.savedPageIndex;\n }\n\n if (!mustBeAddedInUndoStack) {\n return false;\n }\n\n const move = (editor, x, y, pageIndex) => {\n if (this.#allEditors.has(editor.id)) {\n // The editor can be undone/redone on a page which is not visible (and\n // which potentially has no annotation editor layer), hence we need to\n // use the pageIndex instead of the parent.\n const parent = this.#allLayers.get(pageIndex);\n if (parent) {\n editor._setParentAndPosition(parent, x, y);\n } else {\n editor.pageIndex = pageIndex;\n editor.x = x;\n editor.y = y;\n }\n }\n };\n\n this.addCommands({\n cmd: () => {\n for (const [editor, { newX, newY, newPageIndex }] of map) {\n move(editor, newX, newY, newPageIndex);\n }\n },\n undo: () => {\n for (const [editor, { savedX, savedY, savedPageIndex }] of map) {\n move(editor, savedX, savedY, savedPageIndex);\n }\n },\n mustExec: true,\n });\n\n return true;\n }\n\n /**\n * Drag the set of selected editors.\n * @param {number} tx\n * @param {number} ty\n */\n dragSelectedEditors(tx, ty) {\n if (!this.#draggingEditors) {\n return;\n }\n for (const editor of this.#draggingEditors.keys()) {\n editor.drag(tx, ty);\n }\n }\n\n /**\n * Rebuild the editor (usually on undo/redo actions) on a potentially\n * non-rendered page.\n * @param {AnnotationEditor} editor\n */\n rebuild(editor) {\n if (editor.parent === null) {\n const parent = this.getLayer(editor.pageIndex);\n if (parent) {\n parent.changeParent(editor);\n parent.addOrRebuild(editor);\n } else {\n this.addEditor(editor);\n this.addToAnnotationStorage(editor);\n editor.rebuild();\n }\n } else {\n editor.parent.addOrRebuild(editor);\n }\n }\n\n get isEditorHandlingKeyboard() {\n return (\n this.getActive()?.shouldGetKeyboardEvents() ||\n (this.#selectedEditors.size === 1 &&\n this.firstSelectedEditor.shouldGetKeyboardEvents())\n );\n }\n\n /**\n * Is the current editor the one passed as argument?\n * @param {AnnotationEditor} editor\n * @returns\n */\n isActive(editor) {\n return this.#activeEditor === editor;\n }\n\n /**\n * Get the current active editor.\n * @returns {AnnotationEditor|null}\n */\n getActive() {\n return this.#activeEditor;\n }\n\n /**\n * Get the current editor mode.\n * @returns {number}\n */\n getMode() {\n return this.#mode;\n }\n\n get imageManager() {\n return shadow(this, \"imageManager\", new ImageManager());\n }\n\n getSelectionBoxes(textLayer) {\n if (!textLayer) {\n return null;\n }\n const selection = document.getSelection();\n for (let i = 0, ii = selection.rangeCount; i < ii; i++) {\n if (\n !textLayer.contains(selection.getRangeAt(i).commonAncestorContainer)\n ) {\n return null;\n }\n }\n\n const {\n x: layerX,\n y: layerY,\n width: parentWidth,\n height: parentHeight,\n } = textLayer.getBoundingClientRect();\n\n // We must rotate the boxes because we want to have them in the non-rotated\n // page coordinates.\n let rotator;\n switch (textLayer.getAttribute(\"data-main-rotation\")) {\n case \"90\":\n rotator = (x, y, w, h) => ({\n x: (y - layerY) / parentHeight,\n y: 1 - (x + w - layerX) / parentWidth,\n width: h / parentHeight,\n height: w / parentWidth,\n });\n break;\n case \"180\":\n rotator = (x, y, w, h) => ({\n x: 1 - (x + w - layerX) / parentWidth,\n y: 1 - (y + h - layerY) / parentHeight,\n width: w / parentWidth,\n height: h / parentHeight,\n });\n break;\n case \"270\":\n rotator = (x, y, w, h) => ({\n x: 1 - (y + h - layerY) / parentHeight,\n y: (x - layerX) / parentWidth,\n width: h / parentHeight,\n height: w / parentWidth,\n });\n break;\n default:\n rotator = (x, y, w, h) => ({\n x: (x - layerX) / parentWidth,\n y: (y - layerY) / parentHeight,\n width: w / parentWidth,\n height: h / parentHeight,\n });\n break;\n }\n\n const boxes = [];\n for (let i = 0, ii = selection.rangeCount; i < ii; i++) {\n const range = selection.getRangeAt(i);\n if (range.collapsed) {\n continue;\n }\n for (const { x, y, width, height } of range.getClientRects()) {\n if (width === 0 || height === 0) {\n continue;\n }\n boxes.push(rotator(x, y, width, height));\n }\n }\n return boxes.length === 0 ? null : boxes;\n }\n\n addChangedExistingAnnotation({ annotationElementId, id }) {\n (this.#changedExistingAnnotations ||= new Map()).set(\n annotationElementId,\n id\n );\n }\n\n removeChangedExistingAnnotation({ annotationElementId }) {\n this.#changedExistingAnnotations?.delete(annotationElementId);\n }\n\n renderAnnotationElement(annotation) {\n const editorId = this.#changedExistingAnnotations?.get(annotation.data.id);\n if (!editorId) {\n return;\n }\n const editor = this.#annotationStorage.getRawValue(editorId);\n if (!editor) {\n return;\n }\n if (this.#mode === AnnotationEditorType.NONE && !editor.hasBeenModified) {\n return;\n }\n editor.renderAnnotationElement(annotation);\n }\n}\n\nexport {\n AnnotationEditorUIManager,\n bindEvents,\n ColorManager,\n CommandManager,\n KeyboardManager,\n opacityToHex,\n};\n","/* Copyright 2023 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { noContextMenu } from \"../display_utils.js\";\n\nclass AltText {\n #altText = null;\n\n #altTextDecorative = false;\n\n #altTextButton = null;\n\n #altTextButtonLabel = null;\n\n #altTextTooltip = null;\n\n #altTextTooltipTimeout = null;\n\n #altTextWasFromKeyBoard = false;\n\n #badge = null;\n\n #editor = null;\n\n #guessedText = null;\n\n #textWithDisclaimer = null;\n\n #useNewAltTextFlow = false;\n\n static #l10nNewButton = null;\n\n static _l10n = null;\n\n constructor(editor) {\n this.#editor = editor;\n this.#useNewAltTextFlow = editor._uiManager.useNewAltTextFlow;\n\n AltText.#l10nNewButton ||= Object.freeze({\n added: \"pdfjs-editor-new-alt-text-added-button\",\n \"added-label\": \"pdfjs-editor-new-alt-text-added-button-label\",\n missing: \"pdfjs-editor-new-alt-text-missing-button\",\n \"missing-label\": \"pdfjs-editor-new-alt-text-missing-button-label\",\n review: \"pdfjs-editor-new-alt-text-to-review-button\",\n \"review-label\": \"pdfjs-editor-new-alt-text-to-review-button-label\",\n });\n }\n\n static initialize(l10n) {\n AltText._l10n ??= l10n;\n }\n\n async render() {\n const altText = (this.#altTextButton = document.createElement(\"button\"));\n altText.className = \"altText\";\n altText.tabIndex = \"0\";\n\n const label = (this.#altTextButtonLabel = document.createElement(\"span\"));\n altText.append(label);\n\n if (this.#useNewAltTextFlow) {\n altText.classList.add(\"new\");\n altText.setAttribute(\"data-l10n-id\", AltText.#l10nNewButton.missing);\n label.setAttribute(\n \"data-l10n-id\",\n AltText.#l10nNewButton[\"missing-label\"]\n );\n } else {\n altText.setAttribute(\"data-l10n-id\", \"pdfjs-editor-alt-text-button\");\n label.setAttribute(\"data-l10n-id\", \"pdfjs-editor-alt-text-button-label\");\n }\n\n const signal = this.#editor._uiManager._signal;\n altText.addEventListener(\"contextmenu\", noContextMenu, { signal });\n altText.addEventListener(\"pointerdown\", event => event.stopPropagation(), {\n signal,\n });\n\n const onClick = event => {\n event.preventDefault();\n this.#editor._uiManager.editAltText(this.#editor);\n if (this.#useNewAltTextFlow) {\n this.#editor._reportTelemetry({\n action: \"pdfjs.image.alt_text.image_status_label_clicked\",\n data: { label: this.#label },\n });\n }\n };\n altText.addEventListener(\"click\", onClick, { capture: true, signal });\n altText.addEventListener(\n \"keydown\",\n event => {\n if (event.target === altText && event.key === \"Enter\") {\n this.#altTextWasFromKeyBoard = true;\n onClick(event);\n }\n },\n { signal }\n );\n await this.#setState();\n\n return altText;\n }\n\n get #label() {\n return (\n (this.#altText && \"added\") ||\n (this.#altText === null && this.guessedText && \"review\") ||\n \"missing\"\n );\n }\n\n finish() {\n if (!this.#altTextButton) {\n return;\n }\n this.#altTextButton.focus({ focusVisible: this.#altTextWasFromKeyBoard });\n this.#altTextWasFromKeyBoard = false;\n }\n\n isEmpty() {\n if (this.#useNewAltTextFlow) {\n return this.#altText === null;\n }\n return !this.#altText && !this.#altTextDecorative;\n }\n\n hasData() {\n if (this.#useNewAltTextFlow) {\n return this.#altText !== null || !!this.#guessedText;\n }\n return this.isEmpty();\n }\n\n get guessedText() {\n return this.#guessedText;\n }\n\n async setGuessedText(guessedText) {\n if (this.#altText !== null) {\n // The user provided their own alt text, so we don't want to overwrite it.\n return;\n }\n this.#guessedText = guessedText;\n this.#textWithDisclaimer = await AltText._l10n.get(\n \"pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer\",\n { generatedAltText: guessedText }\n );\n this.#setState();\n }\n\n toggleAltTextBadge(visibility = false) {\n if (!this.#useNewAltTextFlow || this.#altText) {\n this.#badge?.remove();\n this.#badge = null;\n return;\n }\n if (!this.#badge) {\n const badge = (this.#badge = document.createElement(\"div\"));\n badge.className = \"noAltTextBadge\";\n this.#editor.div.append(badge);\n }\n this.#badge.classList.toggle(\"hidden\", !visibility);\n }\n\n serialize(isForCopying) {\n let altText = this.#altText;\n if (!isForCopying && this.#guessedText === altText) {\n altText = this.#textWithDisclaimer;\n }\n return {\n altText,\n decorative: this.#altTextDecorative,\n guessedText: this.#guessedText,\n textWithDisclaimer: this.#textWithDisclaimer,\n };\n }\n\n get data() {\n return {\n altText: this.#altText,\n decorative: this.#altTextDecorative,\n };\n }\n\n /**\n * Set the alt text data.\n */\n set data({\n altText,\n decorative,\n guessedText,\n textWithDisclaimer,\n cancel = false,\n }) {\n if (guessedText) {\n this.#guessedText = guessedText;\n this.#textWithDisclaimer = textWithDisclaimer;\n }\n if (this.#altText === altText && this.#altTextDecorative === decorative) {\n return;\n }\n if (!cancel) {\n this.#altText = altText;\n this.#altTextDecorative = decorative;\n }\n this.#setState();\n }\n\n toggle(enabled = false) {\n if (!this.#altTextButton) {\n return;\n }\n if (!enabled && this.#altTextTooltipTimeout) {\n clearTimeout(this.#altTextTooltipTimeout);\n this.#altTextTooltipTimeout = null;\n }\n this.#altTextButton.disabled = !enabled;\n }\n\n shown() {\n this.#editor._reportTelemetry({\n action: \"pdfjs.image.alt_text.image_status_label_displayed\",\n data: { label: this.#label },\n });\n }\n\n destroy() {\n this.#altTextButton?.remove();\n this.#altTextButton = null;\n this.#altTextButtonLabel = null;\n this.#altTextTooltip = null;\n this.#badge?.remove();\n this.#badge = null;\n }\n\n async #setState() {\n const button = this.#altTextButton;\n if (!button) {\n return;\n }\n\n if (this.#useNewAltTextFlow) {\n button.classList.toggle(\"done\", !!this.#altText);\n button.setAttribute(\"data-l10n-id\", AltText.#l10nNewButton[this.#label]);\n\n this.#altTextButtonLabel?.setAttribute(\n \"data-l10n-id\",\n AltText.#l10nNewButton[`${this.#label}-label`]\n );\n if (!this.#altText) {\n this.#altTextTooltip?.remove();\n return;\n }\n } else {\n if (!this.#altText && !this.#altTextDecorative) {\n button.classList.remove(\"done\");\n this.#altTextTooltip?.remove();\n return;\n }\n button.classList.add(\"done\");\n button.setAttribute(\"data-l10n-id\", \"pdfjs-editor-alt-text-edit-button\");\n }\n\n let tooltip = this.#altTextTooltip;\n if (!tooltip) {\n this.#altTextTooltip = tooltip = document.createElement(\"span\");\n tooltip.className = \"tooltip\";\n tooltip.setAttribute(\"role\", \"tooltip\");\n tooltip.id = `alt-text-tooltip-${this.#editor.id}`;\n\n const DELAY_TO_SHOW_TOOLTIP = 100;\n const signal = this.#editor._uiManager._signal;\n signal.addEventListener(\n \"abort\",\n () => {\n clearTimeout(this.#altTextTooltipTimeout);\n this.#altTextTooltipTimeout = null;\n },\n { once: true }\n );\n button.addEventListener(\n \"mouseenter\",\n () => {\n this.#altTextTooltipTimeout = setTimeout(() => {\n this.#altTextTooltipTimeout = null;\n this.#altTextTooltip.classList.add(\"show\");\n this.#editor._reportTelemetry({\n action: \"alt_text_tooltip\",\n });\n }, DELAY_TO_SHOW_TOOLTIP);\n },\n { signal }\n );\n button.addEventListener(\n \"mouseleave\",\n () => {\n if (this.#altTextTooltipTimeout) {\n clearTimeout(this.#altTextTooltipTimeout);\n this.#altTextTooltipTimeout = null;\n }\n this.#altTextTooltip?.classList.remove(\"show\");\n },\n { signal }\n );\n }\n if (this.#altTextDecorative) {\n tooltip.setAttribute(\n \"data-l10n-id\",\n \"pdfjs-editor-alt-text-decorative-tooltip\"\n );\n } else {\n tooltip.removeAttribute(\"data-l10n-id\");\n tooltip.textContent = this.#altText;\n }\n\n if (!tooltip.parentNode) {\n button.append(tooltip);\n }\n\n const element = this.#editor.getImageForAltText();\n element?.setAttribute(\"aria-describedby\", tooltip.id);\n }\n}\n\nexport { AltText };\n","/* Copyright 2022 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line max-len\n/** @typedef {import(\"./annotation_editor_layer.js\").AnnotationEditorLayer} AnnotationEditorLayer */\n\nimport {\n AnnotationEditorUIManager,\n bindEvents,\n ColorManager,\n KeyboardManager,\n} from \"./tools.js\";\nimport { FeatureTest, shadow, unreachable } from \"../../shared/util.js\";\nimport { noContextMenu, stopEvent } from \"../display_utils.js\";\nimport { AltText } from \"./alt_text.js\";\nimport { EditorToolbar } from \"./toolbar.js\";\n\n/**\n * @typedef {Object} AnnotationEditorParameters\n * @property {AnnotationEditorUIManager} uiManager - the global manager\n * @property {AnnotationEditorLayer} parent - the layer containing this editor\n * @property {string} id - editor id\n * @property {number} x - x-coordinate\n * @property {number} y - y-coordinate\n */\n\n/**\n * Base class for editors.\n */\nclass AnnotationEditor {\n #accessibilityData = null;\n\n #allResizerDivs = null;\n\n #altText = null;\n\n #disabled = false;\n\n #dragPointerId = null;\n\n #dragPointerType = \"\";\n\n #keepAspectRatio = false;\n\n #resizersDiv = null;\n\n #lastPointerCoords = null;\n\n #savedDimensions = null;\n\n #focusAC = null;\n\n #focusedResizerName = \"\";\n\n #hasBeenClicked = false;\n\n #initialRect = null;\n\n #isEditing = false;\n\n #isInEditMode = false;\n\n #isResizerEnabledForKeyboard = false;\n\n #moveInDOMTimeout = null;\n\n #prevDragX = 0;\n\n #prevDragY = 0;\n\n #telemetryTimeouts = null;\n\n _editToolbar = null;\n\n _initialOptions = Object.create(null);\n\n _initialData = null;\n\n _isVisible = true;\n\n _uiManager = null;\n\n _focusEventsAllowed = true;\n\n static _l10n = null;\n\n static _l10nResizer = null;\n\n #isDraggable = false;\n\n #zIndex = AnnotationEditor._zIndex++;\n\n static _borderLineWidth = -1;\n\n static _colorManager = new ColorManager();\n\n static _zIndex = 1;\n\n // Time to wait (in ms) before sending the telemetry data.\n // We wait a bit to avoid sending too many requests when changing something\n // like the thickness of a line.\n static _telemetryTimeout = 1000;\n\n static get _resizerKeyboardManager() {\n const resize = AnnotationEditor.prototype._resizeWithKeyboard;\n const small = AnnotationEditorUIManager.TRANSLATE_SMALL;\n const big = AnnotationEditorUIManager.TRANSLATE_BIG;\n\n return shadow(\n this,\n \"_resizerKeyboardManager\",\n new KeyboardManager([\n [[\"ArrowLeft\", \"mac+ArrowLeft\"], resize, { args: [-small, 0] }],\n [\n [\"ctrl+ArrowLeft\", \"mac+shift+ArrowLeft\"],\n resize,\n { args: [-big, 0] },\n ],\n [[\"ArrowRight\", \"mac+ArrowRight\"], resize, { args: [small, 0] }],\n [\n [\"ctrl+ArrowRight\", \"mac+shift+ArrowRight\"],\n resize,\n { args: [big, 0] },\n ],\n [[\"ArrowUp\", \"mac+ArrowUp\"], resize, { args: [0, -small] }],\n [[\"ctrl+ArrowUp\", \"mac+shift+ArrowUp\"], resize, { args: [0, -big] }],\n [[\"ArrowDown\", \"mac+ArrowDown\"], resize, { args: [0, small] }],\n [[\"ctrl+ArrowDown\", \"mac+shift+ArrowDown\"], resize, { args: [0, big] }],\n [\n [\"Escape\", \"mac+Escape\"],\n AnnotationEditor.prototype._stopResizingWithKeyboard,\n ],\n ])\n );\n }\n\n /**\n * @param {AnnotationEditorParameters} parameters\n */\n constructor(parameters) {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === AnnotationEditor\n ) {\n unreachable(\"Cannot initialize AnnotationEditor.\");\n }\n\n this.parent = parameters.parent;\n this.id = parameters.id;\n this.width = this.height = null;\n this.pageIndex = parameters.parent.pageIndex;\n this.name = parameters.name;\n this.div = null;\n this._uiManager = parameters.uiManager;\n this.annotationElementId = null;\n this._willKeepAspectRatio = false;\n this._initialOptions.isCentered = parameters.isCentered;\n this._structTreeParentId = null;\n\n const {\n rotation,\n rawDims: { pageWidth, pageHeight, pageX, pageY },\n } = this.parent.viewport;\n\n this.rotation = rotation;\n this.pageRotation =\n (360 + rotation - this._uiManager.viewParameters.rotation) % 360;\n this.pageDimensions = [pageWidth, pageHeight];\n this.pageTranslation = [pageX, pageY];\n\n const [width, height] = this.parentDimensions;\n this.x = parameters.x / width;\n this.y = parameters.y / height;\n\n this.isAttachedToDOM = false;\n this.deleted = false;\n }\n\n get editorType() {\n return Object.getPrototypeOf(this).constructor._type;\n }\n\n static get isDrawer() {\n return false;\n }\n\n static get _defaultLineColor() {\n return shadow(\n this,\n \"_defaultLineColor\",\n this._colorManager.getHexCode(\"CanvasText\")\n );\n }\n\n static deleteAnnotationElement(editor) {\n const fakeEditor = new FakeEditor({\n id: editor.parent.getNextId(),\n parent: editor.parent,\n uiManager: editor._uiManager,\n });\n fakeEditor.annotationElementId = editor.annotationElementId;\n fakeEditor.deleted = true;\n fakeEditor._uiManager.addToAnnotationStorage(fakeEditor);\n }\n\n /**\n * Initialize the l10n stuff for this type of editor.\n * @param {Object} l10n\n */\n static initialize(l10n, _uiManager) {\n AnnotationEditor._l10n ??= l10n;\n\n AnnotationEditor._l10nResizer ||= Object.freeze({\n topLeft: \"pdfjs-editor-resizer-top-left\",\n topMiddle: \"pdfjs-editor-resizer-top-middle\",\n topRight: \"pdfjs-editor-resizer-top-right\",\n middleRight: \"pdfjs-editor-resizer-middle-right\",\n bottomRight: \"pdfjs-editor-resizer-bottom-right\",\n bottomMiddle: \"pdfjs-editor-resizer-bottom-middle\",\n bottomLeft: \"pdfjs-editor-resizer-bottom-left\",\n middleLeft: \"pdfjs-editor-resizer-middle-left\",\n });\n\n if (AnnotationEditor._borderLineWidth !== -1) {\n return;\n }\n const style = getComputedStyle(document.documentElement);\n AnnotationEditor._borderLineWidth =\n parseFloat(style.getPropertyValue(\"--outline-width\")) || 0;\n }\n\n /**\n * Update the default parameters for this type of editor.\n * @param {number} _type\n * @param {*} _value\n */\n static updateDefaultParams(_type, _value) {}\n\n /**\n * Get the default properties to set in the UI for this type of editor.\n * @returns {Array}\n */\n static get defaultPropertiesToUpdate() {\n return [];\n }\n\n /**\n * Check if this kind of editor is able to handle the given mime type for\n * pasting.\n * @param {string} mime\n * @returns {boolean}\n */\n static isHandlingMimeForPasting(mime) {\n return false;\n }\n\n /**\n * Extract the data from the clipboard item and delegate the creation of the\n * editor to the parent.\n * @param {DataTransferItem} item\n * @param {AnnotationEditorLayer} parent\n */\n static paste(item, parent) {\n unreachable(\"Not implemented\");\n }\n\n /**\n * Get the properties to update in the UI for this editor.\n * @returns {Array}\n */\n get propertiesToUpdate() {\n return [];\n }\n\n get _isDraggable() {\n return this.#isDraggable;\n }\n\n set _isDraggable(value) {\n this.#isDraggable = value;\n this.div?.classList.toggle(\"draggable\", value);\n }\n\n /**\n * @returns {boolean} true if the editor handles the Enter key itself.\n */\n get isEnterHandled() {\n return true;\n }\n\n center() {\n const [pageWidth, pageHeight] = this.pageDimensions;\n switch (this.parentRotation) {\n case 90:\n this.x -= (this.height * pageHeight) / (pageWidth * 2);\n this.y += (this.width * pageWidth) / (pageHeight * 2);\n break;\n case 180:\n this.x += this.width / 2;\n this.y += this.height / 2;\n break;\n case 270:\n this.x += (this.height * pageHeight) / (pageWidth * 2);\n this.y -= (this.width * pageWidth) / (pageHeight * 2);\n break;\n default:\n this.x -= this.width / 2;\n this.y -= this.height / 2;\n break;\n }\n this.fixAndSetPosition();\n }\n\n /**\n * Add some commands into the CommandManager (undo/redo stuff).\n * @param {Object} params\n */\n addCommands(params) {\n this._uiManager.addCommands(params);\n }\n\n get currentLayer() {\n return this._uiManager.currentLayer;\n }\n\n /**\n * This editor will be behind the others.\n */\n setInBackground() {\n this.div.style.zIndex = 0;\n }\n\n /**\n * This editor will be in the foreground.\n */\n setInForeground() {\n this.div.style.zIndex = this.#zIndex;\n }\n\n setParent(parent) {\n if (parent !== null) {\n this.pageIndex = parent.pageIndex;\n this.pageDimensions = parent.pageDimensions;\n } else {\n // The editor is being removed from the DOM, so we need to stop resizing.\n this.#stopResizing();\n }\n this.parent = parent;\n }\n\n /**\n * onfocus callback.\n */\n focusin(event) {\n if (!this._focusEventsAllowed) {\n return;\n }\n if (!this.#hasBeenClicked) {\n this.parent.setSelected(this);\n } else {\n this.#hasBeenClicked = false;\n }\n }\n\n /**\n * onblur callback.\n * @param {FocusEvent} event\n */\n focusout(event) {\n if (!this._focusEventsAllowed) {\n return;\n }\n\n if (!this.isAttachedToDOM) {\n return;\n }\n\n // In case of focusout, the relatedTarget is the element which\n // is grabbing the focus.\n // So if the related target is an element under the div for this\n // editor, then the editor isn't unactive.\n const target = event.relatedTarget;\n if (target?.closest(`#${this.id}`)) {\n return;\n }\n\n event.preventDefault();\n\n if (!this.parent?.isMultipleSelection) {\n this.commitOrRemove();\n }\n }\n\n commitOrRemove() {\n if (this.isEmpty()) {\n this.remove();\n } else {\n this.commit();\n }\n }\n\n /**\n * Commit the data contained in this editor.\n */\n commit() {\n this.addToAnnotationStorage();\n }\n\n addToAnnotationStorage() {\n this._uiManager.addToAnnotationStorage(this);\n }\n\n /**\n * Set the editor position within its parent.\n * @param {number} x\n * @param {number} y\n * @param {number} tx - x-translation in screen coordinates.\n * @param {number} ty - y-translation in screen coordinates.\n */\n setAt(x, y, tx, ty) {\n const [width, height] = this.parentDimensions;\n [tx, ty] = this.screenToPageTranslation(tx, ty);\n\n this.x = (x + tx) / width;\n this.y = (y + ty) / height;\n\n this.fixAndSetPosition();\n }\n\n #translate([width, height], x, y) {\n [x, y] = this.screenToPageTranslation(x, y);\n\n this.x += x / width;\n this.y += y / height;\n\n this._onTranslating(this.x, this.y);\n\n this.fixAndSetPosition();\n }\n\n /**\n * Translate the editor position within its parent.\n * @param {number} x - x-translation in screen coordinates.\n * @param {number} y - y-translation in screen coordinates.\n */\n translate(x, y) {\n // We don't change the initial position because the move here hasn't been\n // done by the user.\n this.#translate(this.parentDimensions, x, y);\n }\n\n /**\n * Translate the editor position within its page and adjust the scroll\n * in order to have the editor in the view.\n * @param {number} x - x-translation in page coordinates.\n * @param {number} y - y-translation in page coordinates.\n */\n translateInPage(x, y) {\n this.#initialRect ||= [this.x, this.y, this.width, this.height];\n this.#translate(this.pageDimensions, x, y);\n this.div.scrollIntoView({ block: \"nearest\" });\n }\n\n drag(tx, ty) {\n this.#initialRect ||= [this.x, this.y, this.width, this.height];\n const {\n div,\n parentDimensions: [parentWidth, parentHeight],\n } = this;\n this.x += tx / parentWidth;\n this.y += ty / parentHeight;\n if (this.parent && (this.x < 0 || this.x > 1 || this.y < 0 || this.y > 1)) {\n // It's possible to not have a parent: for example, when the user is\n // dragging all the selected editors but this one on a page which has been\n // destroyed.\n // It's why we need to check for it. In such a situation, it isn't really\n // a problem to not find a new parent: it's something which is related to\n // what the user is seeing, hence it depends on how pages are layed out.\n\n // The element will be outside of its parent so change the parent.\n const { x, y } = this.div.getBoundingClientRect();\n if (this.parent.findNewParent(this, x, y)) {\n this.x -= Math.floor(this.x);\n this.y -= Math.floor(this.y);\n }\n }\n\n // The editor can be moved wherever the user wants, so we don't need to fix\n // the position: it'll be done when the user will release the mouse button.\n\n let { x, y } = this;\n const [bx, by] = this.getBaseTranslation();\n x += bx;\n y += by;\n\n const { style } = div;\n style.left = `${(100 * x).toFixed(2)}%`;\n style.top = `${(100 * y).toFixed(2)}%`;\n\n this._onTranslating(x, y);\n\n div.scrollIntoView({ block: \"nearest\" });\n }\n\n /**\n * Called when the editor is being translated.\n * @param {number} x - in page coordinates.\n * @param {number} y - in page coordinates.\n */\n _onTranslating(x, y) {}\n\n /**\n * Called when the editor has been translated.\n * @param {number} x - in page coordinates.\n * @param {number} y - in page coordinates.\n */\n _onTranslated(x, y) {}\n\n get _hasBeenMoved() {\n return (\n !!this.#initialRect &&\n (this.#initialRect[0] !== this.x || this.#initialRect[1] !== this.y)\n );\n }\n\n get _hasBeenResized() {\n return (\n !!this.#initialRect &&\n (this.#initialRect[2] !== this.width ||\n this.#initialRect[3] !== this.height)\n );\n }\n\n /**\n * Get the translation to take into account the editor border.\n * The CSS engine positions the element by taking the border into account so\n * we must apply the opposite translation to have the editor in the right\n * position.\n * @returns {Array}\n */\n getBaseTranslation() {\n const [parentWidth, parentHeight] = this.parentDimensions;\n const { _borderLineWidth } = AnnotationEditor;\n const x = _borderLineWidth / parentWidth;\n const y = _borderLineWidth / parentHeight;\n switch (this.rotation) {\n case 90:\n return [-x, y];\n case 180:\n return [x, y];\n case 270:\n return [x, -y];\n default:\n return [-x, -y];\n }\n }\n\n /**\n * @returns {boolean} true if position must be fixed (i.e. make the x and y\n * living in the page).\n */\n get _mustFixPosition() {\n return true;\n }\n\n /**\n * Fix the position of the editor in order to keep it inside its parent page.\n * @param {number} [rotation] - the rotation of the page.\n */\n fixAndSetPosition(rotation = this.rotation) {\n const {\n div: { style },\n pageDimensions: [pageWidth, pageHeight],\n } = this;\n let { x, y, width, height } = this;\n width *= pageWidth;\n height *= pageHeight;\n x *= pageWidth;\n y *= pageHeight;\n\n if (this._mustFixPosition) {\n switch (rotation) {\n case 0:\n x = Math.max(0, Math.min(pageWidth - width, x));\n y = Math.max(0, Math.min(pageHeight - height, y));\n break;\n case 90:\n x = Math.max(0, Math.min(pageWidth - height, x));\n y = Math.min(pageHeight, Math.max(width, y));\n break;\n case 180:\n x = Math.min(pageWidth, Math.max(width, x));\n y = Math.min(pageHeight, Math.max(height, y));\n break;\n case 270:\n x = Math.min(pageWidth, Math.max(height, x));\n y = Math.max(0, Math.min(pageHeight - width, y));\n break;\n }\n }\n\n this.x = x /= pageWidth;\n this.y = y /= pageHeight;\n\n const [bx, by] = this.getBaseTranslation();\n x += bx;\n y += by;\n\n style.left = `${(100 * x).toFixed(2)}%`;\n style.top = `${(100 * y).toFixed(2)}%`;\n\n this.moveInDOM();\n }\n\n static #rotatePoint(x, y, angle) {\n switch (angle) {\n case 90:\n return [y, -x];\n case 180:\n return [-x, -y];\n case 270:\n return [-y, x];\n default:\n return [x, y];\n }\n }\n\n /**\n * Convert a screen translation into a page one.\n * @param {number} x\n * @param {number} y\n */\n screenToPageTranslation(x, y) {\n return AnnotationEditor.#rotatePoint(x, y, this.parentRotation);\n }\n\n /**\n * Convert a page translation into a screen one.\n * @param {number} x\n * @param {number} y\n */\n pageTranslationToScreen(x, y) {\n return AnnotationEditor.#rotatePoint(x, y, 360 - this.parentRotation);\n }\n\n #getRotationMatrix(rotation) {\n switch (rotation) {\n case 90: {\n const [pageWidth, pageHeight] = this.pageDimensions;\n return [0, -pageWidth / pageHeight, pageHeight / pageWidth, 0];\n }\n case 180:\n return [-1, 0, 0, -1];\n case 270: {\n const [pageWidth, pageHeight] = this.pageDimensions;\n return [0, pageWidth / pageHeight, -pageHeight / pageWidth, 0];\n }\n default:\n return [1, 0, 0, 1];\n }\n }\n\n get parentScale() {\n return this._uiManager.viewParameters.realScale;\n }\n\n get parentRotation() {\n return (this._uiManager.viewParameters.rotation + this.pageRotation) % 360;\n }\n\n get parentDimensions() {\n const {\n parentScale,\n pageDimensions: [pageWidth, pageHeight],\n } = this;\n return [pageWidth * parentScale, pageHeight * parentScale];\n }\n\n /**\n * Set the dimensions of this editor.\n * @param {number} width\n * @param {number} height\n */\n setDims(width, height) {\n const [parentWidth, parentHeight] = this.parentDimensions;\n const { style } = this.div;\n style.width = `${((100 * width) / parentWidth).toFixed(2)}%`;\n if (!this.#keepAspectRatio) {\n style.height = `${((100 * height) / parentHeight).toFixed(2)}%`;\n }\n }\n\n fixDims() {\n const { style } = this.div;\n const { height, width } = style;\n const widthPercent = width.endsWith(\"%\");\n const heightPercent = !this.#keepAspectRatio && height.endsWith(\"%\");\n if (widthPercent && heightPercent) {\n return;\n }\n\n const [parentWidth, parentHeight] = this.parentDimensions;\n if (!widthPercent) {\n style.width = `${((100 * parseFloat(width)) / parentWidth).toFixed(2)}%`;\n }\n if (!this.#keepAspectRatio && !heightPercent) {\n style.height = `${((100 * parseFloat(height)) / parentHeight).toFixed(2)}%`;\n }\n }\n\n /**\n * Get the translation used to position this editor when it's created.\n * @returns {Array}\n */\n getInitialTranslation() {\n return [0, 0];\n }\n\n #createResizers() {\n if (this.#resizersDiv) {\n return;\n }\n this.#resizersDiv = document.createElement(\"div\");\n this.#resizersDiv.classList.add(\"resizers\");\n // When the resizers are used with the keyboard, they're focusable, hence\n // we want to have them in this order (top left, top middle, top right, ...)\n // in the DOM to have the focus order correct.\n const classes = this._willKeepAspectRatio\n ? [\"topLeft\", \"topRight\", \"bottomRight\", \"bottomLeft\"]\n : [\n \"topLeft\",\n \"topMiddle\",\n \"topRight\",\n \"middleRight\",\n \"bottomRight\",\n \"bottomMiddle\",\n \"bottomLeft\",\n \"middleLeft\",\n ];\n const signal = this._uiManager._signal;\n for (const name of classes) {\n const div = document.createElement(\"div\");\n this.#resizersDiv.append(div);\n div.classList.add(\"resizer\", name);\n div.setAttribute(\"data-resizer-name\", name);\n div.addEventListener(\n \"pointerdown\",\n this.#resizerPointerdown.bind(this, name),\n { signal }\n );\n div.addEventListener(\"contextmenu\", noContextMenu, { signal });\n div.tabIndex = -1;\n }\n this.div.prepend(this.#resizersDiv);\n }\n\n #resizerPointerdown(name, event) {\n event.preventDefault();\n const { isMac } = FeatureTest.platform;\n if (event.button !== 0 || (event.ctrlKey && isMac)) {\n return;\n }\n\n this.#altText?.toggle(false);\n\n const savedDraggable = this._isDraggable;\n this._isDraggable = false;\n this.#lastPointerCoords = [event.screenX, event.screenY];\n\n const ac = new AbortController();\n const signal = this._uiManager.combinedSignal(ac);\n\n this.parent.togglePointerEvents(false);\n window.addEventListener(\n \"pointermove\",\n this.#resizerPointermove.bind(this, name),\n { passive: true, capture: true, signal }\n );\n window.addEventListener(\n \"touchmove\",\n stopEvent /* Prevent the page from scrolling */,\n { passive: false, signal }\n );\n window.addEventListener(\"contextmenu\", noContextMenu, { signal });\n this.#savedDimensions = {\n savedX: this.x,\n savedY: this.y,\n savedWidth: this.width,\n savedHeight: this.height,\n };\n const savedParentCursor = this.parent.div.style.cursor;\n const savedCursor = this.div.style.cursor;\n this.div.style.cursor = this.parent.div.style.cursor =\n window.getComputedStyle(event.target).cursor;\n\n const pointerUpCallback = () => {\n ac.abort();\n this.parent.togglePointerEvents(true);\n this.#altText?.toggle(true);\n this._isDraggable = savedDraggable;\n this.parent.div.style.cursor = savedParentCursor;\n this.div.style.cursor = savedCursor;\n\n this.#addResizeToUndoStack();\n };\n window.addEventListener(\"pointerup\", pointerUpCallback, { signal });\n // If the user switches to another window (with alt+tab), then we end the\n // resize session.\n window.addEventListener(\"blur\", pointerUpCallback, { signal });\n }\n\n #resize(x, y, width, height) {\n this.width = width;\n this.height = height;\n this.x = x;\n this.y = y;\n const [parentWidth, parentHeight] = this.parentDimensions;\n this.setDims(parentWidth * width, parentHeight * height);\n this.fixAndSetPosition();\n this._onResized();\n }\n\n /**\n * Called when the editor has been resized.\n */\n _onResized() {}\n\n #addResizeToUndoStack() {\n if (!this.#savedDimensions) {\n return;\n }\n const { savedX, savedY, savedWidth, savedHeight } = this.#savedDimensions;\n this.#savedDimensions = null;\n\n const newX = this.x;\n const newY = this.y;\n const newWidth = this.width;\n const newHeight = this.height;\n if (\n newX === savedX &&\n newY === savedY &&\n newWidth === savedWidth &&\n newHeight === savedHeight\n ) {\n return;\n }\n\n this.addCommands({\n cmd: this.#resize.bind(this, newX, newY, newWidth, newHeight),\n undo: this.#resize.bind(this, savedX, savedY, savedWidth, savedHeight),\n mustExec: true,\n });\n }\n\n #resizerPointermove(name, event) {\n const [parentWidth, parentHeight] = this.parentDimensions;\n const savedX = this.x;\n const savedY = this.y;\n const savedWidth = this.width;\n const savedHeight = this.height;\n const minWidth = AnnotationEditor.MIN_SIZE / parentWidth;\n const minHeight = AnnotationEditor.MIN_SIZE / parentHeight;\n\n // 10000 because we multiply by 100 and use toFixed(2) in fixAndSetPosition.\n // Without rounding, the positions of the corners other than the top left\n // one can be slightly wrong.\n const round = x => Math.round(x * 10000) / 10000;\n const rotationMatrix = this.#getRotationMatrix(this.rotation);\n const transf = (x, y) => [\n rotationMatrix[0] * x + rotationMatrix[2] * y,\n rotationMatrix[1] * x + rotationMatrix[3] * y,\n ];\n const invRotationMatrix = this.#getRotationMatrix(360 - this.rotation);\n const invTransf = (x, y) => [\n invRotationMatrix[0] * x + invRotationMatrix[2] * y,\n invRotationMatrix[1] * x + invRotationMatrix[3] * y,\n ];\n let getPoint;\n let getOpposite;\n let isDiagonal = false;\n let isHorizontal = false;\n\n switch (name) {\n case \"topLeft\":\n isDiagonal = true;\n getPoint = (w, h) => [0, 0];\n getOpposite = (w, h) => [w, h];\n break;\n case \"topMiddle\":\n getPoint = (w, h) => [w / 2, 0];\n getOpposite = (w, h) => [w / 2, h];\n break;\n case \"topRight\":\n isDiagonal = true;\n getPoint = (w, h) => [w, 0];\n getOpposite = (w, h) => [0, h];\n break;\n case \"middleRight\":\n isHorizontal = true;\n getPoint = (w, h) => [w, h / 2];\n getOpposite = (w, h) => [0, h / 2];\n break;\n case \"bottomRight\":\n isDiagonal = true;\n getPoint = (w, h) => [w, h];\n getOpposite = (w, h) => [0, 0];\n break;\n case \"bottomMiddle\":\n getPoint = (w, h) => [w / 2, h];\n getOpposite = (w, h) => [w / 2, 0];\n break;\n case \"bottomLeft\":\n isDiagonal = true;\n getPoint = (w, h) => [0, h];\n getOpposite = (w, h) => [w, 0];\n break;\n case \"middleLeft\":\n isHorizontal = true;\n getPoint = (w, h) => [0, h / 2];\n getOpposite = (w, h) => [w, h / 2];\n break;\n }\n\n const point = getPoint(savedWidth, savedHeight);\n const oppositePoint = getOpposite(savedWidth, savedHeight);\n let transfOppositePoint = transf(...oppositePoint);\n const oppositeX = round(savedX + transfOppositePoint[0]);\n const oppositeY = round(savedY + transfOppositePoint[1]);\n let ratioX = 1;\n let ratioY = 1;\n\n let deltaX, deltaY;\n\n if (!event.fromKeyboard) {\n // We can't use event.movementX/Y because they're not reliable:\n // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementX\n // (it was buggy on a laptop with a touch screen).\n const { screenX, screenY } = event;\n const [lastScreenX, lastScreenY] = this.#lastPointerCoords;\n [deltaX, deltaY] = this.screenToPageTranslation(\n screenX - lastScreenX,\n screenY - lastScreenY\n );\n this.#lastPointerCoords[0] = screenX;\n this.#lastPointerCoords[1] = screenY;\n } else {\n ({ deltaX, deltaY } = event);\n }\n [deltaX, deltaY] = invTransf(deltaX / parentWidth, deltaY / parentHeight);\n\n if (isDiagonal) {\n const oldDiag = Math.hypot(savedWidth, savedHeight);\n ratioX = ratioY = Math.max(\n Math.min(\n Math.hypot(\n oppositePoint[0] - point[0] - deltaX,\n oppositePoint[1] - point[1] - deltaY\n ) / oldDiag,\n // Avoid the editor to be larger than the page.\n 1 / savedWidth,\n 1 / savedHeight\n ),\n // Avoid the editor to be smaller than the minimum size.\n minWidth / savedWidth,\n minHeight / savedHeight\n );\n } else if (isHorizontal) {\n ratioX =\n Math.max(\n minWidth,\n Math.min(1, Math.abs(oppositePoint[0] - point[0] - deltaX))\n ) / savedWidth;\n } else {\n ratioY =\n Math.max(\n minHeight,\n Math.min(1, Math.abs(oppositePoint[1] - point[1] - deltaY))\n ) / savedHeight;\n }\n\n const newWidth = round(savedWidth * ratioX);\n const newHeight = round(savedHeight * ratioY);\n transfOppositePoint = transf(...getOpposite(newWidth, newHeight));\n const newX = oppositeX - transfOppositePoint[0];\n const newY = oppositeY - transfOppositePoint[1];\n\n this.#initialRect ||= [this.x, this.y, this.width, this.height];\n this.width = newWidth;\n this.height = newHeight;\n this.x = newX;\n this.y = newY;\n\n this.setDims(parentWidth * newWidth, parentHeight * newHeight);\n this.fixAndSetPosition();\n\n this._onResizing();\n }\n\n /**\n * Called when the editor is being resized.\n */\n _onResizing() {}\n\n /**\n * Called when the alt text dialog is closed.\n */\n altTextFinish() {\n this.#altText?.finish();\n }\n\n /**\n * Add a toolbar for this editor.\n * @returns {Promise}\n */\n async addEditToolbar() {\n if (this._editToolbar || this.#isInEditMode) {\n return this._editToolbar;\n }\n this._editToolbar = new EditorToolbar(this);\n this.div.append(this._editToolbar.render());\n if (this.#altText) {\n await this._editToolbar.addAltText(this.#altText);\n }\n\n return this._editToolbar;\n }\n\n removeEditToolbar() {\n if (!this._editToolbar) {\n return;\n }\n this._editToolbar.remove();\n this._editToolbar = null;\n\n // We destroy the alt text but we don't null it because we want to be able\n // to restore it in case the user undoes the deletion.\n this.#altText?.destroy();\n }\n\n addContainer(container) {\n const editToolbarDiv = this._editToolbar?.div;\n if (editToolbarDiv) {\n editToolbarDiv.before(container);\n } else {\n this.div.append(container);\n }\n }\n\n getClientDimensions() {\n return this.div.getBoundingClientRect();\n }\n\n async addAltTextButton() {\n if (this.#altText) {\n return;\n }\n AltText.initialize(AnnotationEditor._l10n);\n this.#altText = new AltText(this);\n if (this.#accessibilityData) {\n this.#altText.data = this.#accessibilityData;\n this.#accessibilityData = null;\n }\n await this.addEditToolbar();\n }\n\n get altTextData() {\n return this.#altText?.data;\n }\n\n /**\n * Set the alt text data.\n */\n set altTextData(data) {\n if (!this.#altText) {\n return;\n }\n this.#altText.data = data;\n }\n\n get guessedAltText() {\n return this.#altText?.guessedText;\n }\n\n async setGuessedAltText(text) {\n await this.#altText?.setGuessedText(text);\n }\n\n serializeAltText(isForCopying) {\n return this.#altText?.serialize(isForCopying);\n }\n\n hasAltText() {\n return !!this.#altText && !this.#altText.isEmpty();\n }\n\n hasAltTextData() {\n return this.#altText?.hasData() ?? false;\n }\n\n /**\n * Render this editor in a div.\n * @returns {HTMLDivElement | null}\n */\n render() {\n this.div = document.createElement(\"div\");\n this.div.setAttribute(\"data-editor-rotation\", (360 - this.rotation) % 360);\n this.div.className = this.name;\n this.div.setAttribute(\"id\", this.id);\n this.div.tabIndex = this.#disabled ? -1 : 0;\n if (!this._isVisible) {\n this.div.classList.add(\"hidden\");\n }\n\n this.setInForeground();\n this.#addFocusListeners();\n\n const [parentWidth, parentHeight] = this.parentDimensions;\n if (this.parentRotation % 180 !== 0) {\n this.div.style.maxWidth = `${((100 * parentHeight) / parentWidth).toFixed(\n 2\n )}%`;\n this.div.style.maxHeight = `${(\n (100 * parentWidth) /\n parentHeight\n ).toFixed(2)}%`;\n }\n\n const [tx, ty] = this.getInitialTranslation();\n this.translate(tx, ty);\n\n bindEvents(this, this.div, [\"pointerdown\"]);\n\n this._uiManager._editorUndoBar?.hide();\n\n return this.div;\n }\n\n /**\n * Onpointerdown callback.\n * @param {PointerEvent} event\n */\n pointerdown(event) {\n const { isMac } = FeatureTest.platform;\n if (event.button !== 0 || (event.ctrlKey && isMac)) {\n // Avoid to focus this editor because of a non-left click.\n event.preventDefault();\n return;\n }\n\n this.#hasBeenClicked = true;\n\n if (this._isDraggable) {\n this.#setUpDragSession(event);\n return;\n }\n\n this.#selectOnPointerEvent(event);\n }\n\n get isSelected() {\n return this._uiManager.isSelected(this);\n }\n\n #selectOnPointerEvent(event) {\n const { isMac } = FeatureTest.platform;\n if (\n (event.ctrlKey && !isMac) ||\n event.shiftKey ||\n (event.metaKey && isMac)\n ) {\n this.parent.toggleSelected(this);\n } else {\n this.parent.setSelected(this);\n }\n }\n\n #setUpDragSession(event) {\n const { isSelected } = this;\n this._uiManager.setUpDragSession();\n\n const ac = new AbortController();\n const signal = this._uiManager.combinedSignal(ac);\n const opts = { capture: true, passive: false, signal };\n const cancelDrag = e => {\n ac.abort();\n\n this.#dragPointerId = null;\n this.#hasBeenClicked = false;\n if (!this._uiManager.endDragSession()) {\n this.#selectOnPointerEvent(e);\n }\n };\n\n if (isSelected) {\n this.#prevDragX = event.clientX;\n this.#prevDragY = event.clientY;\n this.#dragPointerId = event.pointerId;\n this.#dragPointerType = event.pointerType;\n window.addEventListener(\n \"pointermove\",\n e => {\n const { clientX: x, clientY: y, pointerId } = e;\n if (pointerId !== this.#dragPointerId) {\n stopEvent(e);\n return;\n }\n const [tx, ty] = this.screenToPageTranslation(\n x - this.#prevDragX,\n y - this.#prevDragY\n );\n this.#prevDragX = x;\n this.#prevDragY = y;\n this._uiManager.dragSelectedEditors(tx, ty);\n },\n opts\n );\n window.addEventListener(\n \"touchmove\",\n stopEvent /* Prevent the page from scrolling */,\n opts\n );\n window.addEventListener(\n \"pointerdown\",\n // If the user drags with one finger and then clicks with another.\n e => {\n if (e.isPrimary && e.pointerType === this.#dragPointerType) {\n // We cannot have two primaries at the same time.\n // It's possible to be in this state with Firefox and Gnome when\n // trying to drag with three fingers (see bug 1933716).\n cancelDrag(e);\n }\n stopEvent(e);\n },\n opts\n );\n }\n\n this._onStartDragging();\n\n const pointerUpCallback = e => {\n if (!this.#dragPointerId || this.#dragPointerId === e.pointerId) {\n cancelDrag(e);\n this._onStopDragging();\n return;\n }\n stopEvent(e);\n };\n window.addEventListener(\"pointerup\", pointerUpCallback, { signal });\n // If the user is using alt+tab during the dragging session, the pointerup\n // event could be not fired, but a blur event is fired so we can use it in\n // order to interrupt the dragging session.\n window.addEventListener(\"blur\", pointerUpCallback, { signal });\n }\n\n _onStartDragging() {}\n\n _onStopDragging() {}\n\n moveInDOM() {\n // Moving the editor in the DOM can be expensive, so we wait a bit before.\n // It's important to not block the UI (for example when changing the font\n // size in a FreeText).\n if (this.#moveInDOMTimeout) {\n clearTimeout(this.#moveInDOMTimeout);\n }\n this.#moveInDOMTimeout = setTimeout(() => {\n this.#moveInDOMTimeout = null;\n this.parent?.moveEditorInDOM(this);\n }, 0);\n }\n\n _setParentAndPosition(parent, x, y) {\n parent.changeParent(this);\n this.x = x;\n this.y = y;\n this.fixAndSetPosition();\n this._onTranslated();\n }\n\n /**\n * Convert the current rect into a page one.\n * @param {number} tx - x-translation in screen coordinates.\n * @param {number} ty - y-translation in screen coordinates.\n * @param {number} [rotation] - the rotation of the page.\n */\n getRect(tx, ty, rotation = this.rotation) {\n const scale = this.parentScale;\n const [pageWidth, pageHeight] = this.pageDimensions;\n const [pageX, pageY] = this.pageTranslation;\n const shiftX = tx / scale;\n const shiftY = ty / scale;\n const x = this.x * pageWidth;\n const y = this.y * pageHeight;\n const width = this.width * pageWidth;\n const height = this.height * pageHeight;\n\n switch (rotation) {\n case 0:\n return [\n x + shiftX + pageX,\n pageHeight - y - shiftY - height + pageY,\n x + shiftX + width + pageX,\n pageHeight - y - shiftY + pageY,\n ];\n case 90:\n return [\n x + shiftY + pageX,\n pageHeight - y + shiftX + pageY,\n x + shiftY + height + pageX,\n pageHeight - y + shiftX + width + pageY,\n ];\n case 180:\n return [\n x - shiftX - width + pageX,\n pageHeight - y + shiftY + pageY,\n x - shiftX + pageX,\n pageHeight - y + shiftY + height + pageY,\n ];\n case 270:\n return [\n x - shiftY - height + pageX,\n pageHeight - y - shiftX - width + pageY,\n x - shiftY + pageX,\n pageHeight - y - shiftX + pageY,\n ];\n default:\n throw new Error(\"Invalid rotation\");\n }\n }\n\n getRectInCurrentCoords(rect, pageHeight) {\n const [x1, y1, x2, y2] = rect;\n\n const width = x2 - x1;\n const height = y2 - y1;\n\n switch (this.rotation) {\n case 0:\n return [x1, pageHeight - y2, width, height];\n case 90:\n return [x1, pageHeight - y1, height, width];\n case 180:\n return [x2, pageHeight - y1, width, height];\n case 270:\n return [x2, pageHeight - y2, height, width];\n default:\n throw new Error(\"Invalid rotation\");\n }\n }\n\n /**\n * Executed once this editor has been rendered.\n */\n onceAdded() {}\n\n /**\n * Check if the editor contains something.\n * @returns {boolean}\n */\n isEmpty() {\n return false;\n }\n\n /**\n * Enable edit mode.\n */\n enableEditMode() {\n this.#isInEditMode = true;\n }\n\n /**\n * Disable edit mode.\n */\n disableEditMode() {\n this.#isInEditMode = false;\n }\n\n /**\n * Check if the editor is edited.\n * @returns {boolean}\n */\n isInEditMode() {\n return this.#isInEditMode;\n }\n\n /**\n * If it returns true, then this editor handles the keyboard\n * events itself.\n * @returns {boolean}\n */\n shouldGetKeyboardEvents() {\n return this.#isResizerEnabledForKeyboard;\n }\n\n /**\n * Check if this editor needs to be rebuilt or not.\n * @returns {boolean}\n */\n needsToBeRebuilt() {\n return this.div && !this.isAttachedToDOM;\n }\n\n get isOnScreen() {\n const { top, left, bottom, right } = this.getClientDimensions();\n const { innerHeight, innerWidth } = window;\n return left < innerWidth && right > 0 && top < innerHeight && bottom > 0;\n }\n\n #addFocusListeners() {\n if (this.#focusAC || !this.div) {\n return;\n }\n this.#focusAC = new AbortController();\n const signal = this._uiManager.combinedSignal(this.#focusAC);\n\n this.div.addEventListener(\"focusin\", this.focusin.bind(this), { signal });\n this.div.addEventListener(\"focusout\", this.focusout.bind(this), { signal });\n }\n\n /**\n * Rebuild the editor in case it has been removed on undo.\n *\n * To implement in subclasses.\n */\n rebuild() {\n this.#addFocusListeners();\n }\n\n /**\n * Rotate the editor when the page is rotated.\n * @param {number} angle\n */\n rotate(_angle) {}\n\n /**\n * Resize the editor when the page is resized.\n */\n resize() {}\n\n /**\n * Serialize the editor when it has been deleted.\n * @returns {Object}\n */\n serializeDeleted() {\n return {\n id: this.annotationElementId,\n deleted: true,\n pageIndex: this.pageIndex,\n popupRef: this._initialData?.popupRef || \"\",\n };\n }\n\n /**\n * Serialize the editor.\n * The result of the serialization will be used to construct a\n * new annotation to add to the pdf document.\n *\n * To implement in subclasses.\n * @param {boolean} [isForCopying]\n * @param {Object | null} [context]\n * @returns {Object | null}\n */\n serialize(isForCopying = false, context = null) {\n unreachable(\"An editor must be serializable\");\n }\n\n /**\n * Deserialize the editor.\n * The result of the deserialization is a new editor.\n *\n * @param {Object} data\n * @param {AnnotationEditorLayer} parent\n * @param {AnnotationEditorUIManager} uiManager\n * @returns {Promise}\n */\n static async deserialize(data, parent, uiManager) {\n const editor = new this.prototype.constructor({\n parent,\n id: parent.getNextId(),\n uiManager,\n });\n editor.rotation = data.rotation;\n editor.#accessibilityData = data.accessibilityData;\n\n const [pageWidth, pageHeight] = editor.pageDimensions;\n const [x, y, width, height] = editor.getRectInCurrentCoords(\n data.rect,\n pageHeight\n );\n\n editor.x = x / pageWidth;\n editor.y = y / pageHeight;\n editor.width = width / pageWidth;\n editor.height = height / pageHeight;\n\n return editor;\n }\n\n /**\n * Check if an existing annotation associated with this editor has been\n * modified.\n * @returns {boolean}\n */\n get hasBeenModified() {\n return (\n !!this.annotationElementId && (this.deleted || this.serialize() !== null)\n );\n }\n\n /**\n * Remove this editor.\n * It's used on ctrl+backspace action.\n */\n remove() {\n this.#focusAC?.abort();\n this.#focusAC = null;\n\n if (!this.isEmpty()) {\n // The editor is removed but it can be back at some point thanks to\n // undo/redo so we must commit it before.\n this.commit();\n }\n if (this.parent) {\n this.parent.remove(this);\n } else {\n this._uiManager.removeEditor(this);\n }\n\n if (this.#moveInDOMTimeout) {\n clearTimeout(this.#moveInDOMTimeout);\n this.#moveInDOMTimeout = null;\n }\n this.#stopResizing();\n this.removeEditToolbar();\n if (this.#telemetryTimeouts) {\n for (const timeout of this.#telemetryTimeouts.values()) {\n clearTimeout(timeout);\n }\n this.#telemetryTimeouts = null;\n }\n this.parent = null;\n }\n\n /**\n * @returns {boolean} true if this editor can be resized.\n */\n get isResizable() {\n return false;\n }\n\n /**\n * Add the resizers to this editor.\n */\n makeResizable() {\n if (this.isResizable) {\n this.#createResizers();\n this.#resizersDiv.classList.remove(\"hidden\");\n bindEvents(this, this.div, [\"keydown\"]);\n }\n }\n\n get toolbarPosition() {\n return null;\n }\n\n /**\n * onkeydown callback.\n * @param {KeyboardEvent} event\n */\n keydown(event) {\n if (\n !this.isResizable ||\n event.target !== this.div ||\n event.key !== \"Enter\"\n ) {\n return;\n }\n this._uiManager.setSelected(this);\n this.#savedDimensions = {\n savedX: this.x,\n savedY: this.y,\n savedWidth: this.width,\n savedHeight: this.height,\n };\n const children = this.#resizersDiv.children;\n if (!this.#allResizerDivs) {\n this.#allResizerDivs = Array.from(children);\n const boundResizerKeydown = this.#resizerKeydown.bind(this);\n const boundResizerBlur = this.#resizerBlur.bind(this);\n const signal = this._uiManager._signal;\n for (const div of this.#allResizerDivs) {\n const name = div.getAttribute(\"data-resizer-name\");\n div.setAttribute(\"role\", \"spinbutton\");\n div.addEventListener(\"keydown\", boundResizerKeydown, { signal });\n div.addEventListener(\"blur\", boundResizerBlur, { signal });\n div.addEventListener(\"focus\", this.#resizerFocus.bind(this, name), {\n signal,\n });\n div.setAttribute(\"data-l10n-id\", AnnotationEditor._l10nResizer[name]);\n }\n }\n\n // We want to have the resizers in the visual order, so we move the first\n // (top-left) to the right place.\n const first = this.#allResizerDivs[0];\n let firstPosition = 0;\n for (const div of children) {\n if (div === first) {\n break;\n }\n firstPosition++;\n }\n const nextFirstPosition =\n (((360 - this.rotation + this.parentRotation) % 360) / 90) *\n (this.#allResizerDivs.length / 4);\n\n if (nextFirstPosition !== firstPosition) {\n // We need to reorder the resizers in the DOM in order to have the focus\n // on the top-left one.\n if (nextFirstPosition < firstPosition) {\n for (let i = 0; i < firstPosition - nextFirstPosition; i++) {\n this.#resizersDiv.append(this.#resizersDiv.firstChild);\n }\n } else if (nextFirstPosition > firstPosition) {\n for (let i = 0; i < nextFirstPosition - firstPosition; i++) {\n this.#resizersDiv.firstChild.before(this.#resizersDiv.lastChild);\n }\n }\n\n let i = 0;\n for (const child of children) {\n const div = this.#allResizerDivs[i++];\n const name = div.getAttribute(\"data-resizer-name\");\n child.setAttribute(\"data-l10n-id\", AnnotationEditor._l10nResizer[name]);\n }\n }\n\n this.#setResizerTabIndex(0);\n this.#isResizerEnabledForKeyboard = true;\n this.#resizersDiv.firstChild.focus({ focusVisible: true });\n event.preventDefault();\n event.stopImmediatePropagation();\n }\n\n #resizerKeydown(event) {\n AnnotationEditor._resizerKeyboardManager.exec(this, event);\n }\n\n #resizerBlur(event) {\n if (\n this.#isResizerEnabledForKeyboard &&\n event.relatedTarget?.parentNode !== this.#resizersDiv\n ) {\n this.#stopResizing();\n }\n }\n\n #resizerFocus(name) {\n this.#focusedResizerName = this.#isResizerEnabledForKeyboard ? name : \"\";\n }\n\n #setResizerTabIndex(value) {\n if (!this.#allResizerDivs) {\n return;\n }\n for (const div of this.#allResizerDivs) {\n div.tabIndex = value;\n }\n }\n\n _resizeWithKeyboard(x, y) {\n if (!this.#isResizerEnabledForKeyboard) {\n return;\n }\n this.#resizerPointermove(this.#focusedResizerName, {\n deltaX: x,\n deltaY: y,\n fromKeyboard: true,\n });\n }\n\n #stopResizing() {\n this.#isResizerEnabledForKeyboard = false;\n this.#setResizerTabIndex(-1);\n this.#addResizeToUndoStack();\n }\n\n _stopResizingWithKeyboard() {\n this.#stopResizing();\n this.div.focus();\n }\n\n /**\n * Select this editor.\n */\n select() {\n this.makeResizable();\n this.div?.classList.add(\"selectedEditor\");\n if (!this._editToolbar) {\n this.addEditToolbar().then(() => {\n if (this.div?.classList.contains(\"selectedEditor\")) {\n // The editor can have been unselected while we were waiting for the\n // edit toolbar to be created, hence we want to be sure that this\n // editor is still selected.\n this._editToolbar?.show();\n }\n });\n return;\n }\n this._editToolbar?.show();\n this.#altText?.toggleAltTextBadge(false);\n }\n\n /**\n * Unselect this editor.\n */\n unselect() {\n this.#resizersDiv?.classList.add(\"hidden\");\n this.div?.classList.remove(\"selectedEditor\");\n if (this.div?.contains(document.activeElement)) {\n // Don't use this.div.blur() because we don't know where the focus will\n // go.\n this._uiManager.currentLayer.div.focus({\n preventScroll: true,\n });\n }\n this._editToolbar?.hide();\n this.#altText?.toggleAltTextBadge(true);\n }\n\n /**\n * Update some parameters which have been changed through the UI.\n * @param {number} type\n * @param {*} value\n */\n updateParams(type, value) {}\n\n /**\n * When the user disables the editing mode some editors can change some of\n * their properties.\n */\n disableEditing() {}\n\n /**\n * When the user enables the editing mode some editors can change some of\n * their properties.\n */\n enableEditing() {}\n\n /**\n * The editor is about to be edited.\n */\n enterInEditMode() {}\n\n /**\n * @returns {HTMLElement | null} the element requiring an alt text.\n */\n getImageForAltText() {\n return null;\n }\n\n /**\n * Get the div which really contains the displayed content.\n * @returns {HTMLDivElement | undefined}\n */\n get contentDiv() {\n return this.div;\n }\n\n /**\n * If true then the editor is currently edited.\n * @type {boolean}\n */\n get isEditing() {\n return this.#isEditing;\n }\n\n /**\n * When set to true, it means that this editor is currently edited.\n * @param {boolean} value\n */\n set isEditing(value) {\n this.#isEditing = value;\n if (!this.parent) {\n return;\n }\n if (value) {\n this.parent.setSelected(this);\n this.parent.setActiveEditor(this);\n } else {\n this.parent.setActiveEditor(null);\n }\n }\n\n /**\n * Set the aspect ratio to use when resizing.\n * @param {number} width\n * @param {number} height\n */\n setAspectRatio(width, height) {\n this.#keepAspectRatio = true;\n const aspectRatio = width / height;\n const { style } = this.div;\n style.aspectRatio = aspectRatio;\n style.height = \"auto\";\n }\n\n static get MIN_SIZE() {\n return 16;\n }\n\n static canCreateNewEmptyEditor() {\n return true;\n }\n\n /**\n * Get the data to report to the telemetry when the editor is added.\n * @returns {Object}\n */\n get telemetryInitialData() {\n return { action: \"added\" };\n }\n\n /**\n * The telemetry data to use when saving/printing.\n * @returns {Object|null}\n */\n get telemetryFinalData() {\n return null;\n }\n\n _reportTelemetry(data, mustWait = false) {\n if (mustWait) {\n this.#telemetryTimeouts ||= new Map();\n const { action } = data;\n let timeout = this.#telemetryTimeouts.get(action);\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n this._reportTelemetry(data);\n this.#telemetryTimeouts.delete(action);\n if (this.#telemetryTimeouts.size === 0) {\n this.#telemetryTimeouts = null;\n }\n }, AnnotationEditor._telemetryTimeout);\n this.#telemetryTimeouts.set(action, timeout);\n return;\n }\n data.type ||= this.editorType;\n this._uiManager._eventBus.dispatch(\"reporttelemetry\", {\n source: this,\n details: {\n type: \"editing\",\n data,\n },\n });\n }\n\n /**\n * Show or hide this editor.\n * @param {boolean|undefined} visible\n */\n show(visible = this._isVisible) {\n this.div.classList.toggle(\"hidden\", !visible);\n this._isVisible = visible;\n }\n\n enable() {\n if (this.div) {\n this.div.tabIndex = 0;\n }\n this.#disabled = false;\n }\n\n disable() {\n if (this.div) {\n this.div.tabIndex = -1;\n }\n this.#disabled = true;\n }\n\n /**\n * Render an annotation in the annotation layer.\n * @param {Object} annotation\n * @returns {HTMLElement|null}\n */\n renderAnnotationElement(annotation) {\n let content = annotation.container.querySelector(\".annotationContent\");\n if (!content) {\n content = document.createElement(\"div\");\n content.classList.add(\"annotationContent\", this.editorType);\n annotation.container.prepend(content);\n } else if (content.nodeName === \"CANVAS\") {\n const canvas = content;\n content = document.createElement(\"div\");\n content.classList.add(\"annotationContent\", this.editorType);\n canvas.before(content);\n }\n\n return content;\n }\n\n resetAnnotationElement(annotation) {\n const { firstChild } = annotation.container;\n if (\n firstChild?.nodeName === \"DIV\" &&\n firstChild.classList.contains(\"annotationContent\")\n ) {\n firstChild.remove();\n }\n }\n}\n\n// This class is used to fake an editor which has been deleted.\nclass FakeEditor extends AnnotationEditor {\n constructor(params) {\n super(params);\n this.annotationElementId = params.annotationElementId;\n this.deleted = true;\n }\n\n serialize() {\n return this.serializeDeleted();\n }\n}\n\nexport { AnnotationEditor };\n","/* Copyright 2014 Opera Software ASA\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\n * Based on https://code.google.com/p/smhasher/wiki/MurmurHash3.\n * Hashes roughly 100 KB per millisecond on i7 3.4 GHz.\n */\n\nconst SEED = 0xc3d2e1f0;\n// Workaround for missing math precision in JS.\nconst MASK_HIGH = 0xffff0000;\nconst MASK_LOW = 0xffff;\n\nclass MurmurHash3_64 {\n constructor(seed) {\n this.h1 = seed ? seed & 0xffffffff : SEED;\n this.h2 = seed ? seed & 0xffffffff : SEED;\n }\n\n update(input) {\n let data, length;\n if (typeof input === \"string\") {\n data = new Uint8Array(input.length * 2);\n length = 0;\n for (let i = 0, ii = input.length; i < ii; i++) {\n const code = input.charCodeAt(i);\n if (code <= 0xff) {\n data[length++] = code;\n } else {\n data[length++] = code >>> 8;\n data[length++] = code & 0xff;\n }\n }\n } else if (ArrayBuffer.isView(input)) {\n data = input.slice();\n length = data.byteLength;\n } else {\n throw new Error(\"Invalid data format, must be a string or TypedArray.\");\n }\n\n const blockCounts = length >> 2;\n const tailLength = length - blockCounts * 4;\n // We don't care about endianness here.\n const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);\n let k1 = 0,\n k2 = 0;\n let h1 = this.h1,\n h2 = this.h2;\n const C1 = 0xcc9e2d51,\n C2 = 0x1b873593;\n const C1_LOW = C1 & MASK_LOW,\n C2_LOW = C2 & MASK_LOW;\n\n for (let i = 0; i < blockCounts; i++) {\n if (i & 1) {\n k1 = dataUint32[i];\n k1 = ((k1 * C1) & MASK_HIGH) | ((k1 * C1_LOW) & MASK_LOW);\n k1 = (k1 << 15) | (k1 >>> 17);\n k1 = ((k1 * C2) & MASK_HIGH) | ((k1 * C2_LOW) & MASK_LOW);\n h1 ^= k1;\n h1 = (h1 << 13) | (h1 >>> 19);\n h1 = h1 * 5 + 0xe6546b64;\n } else {\n k2 = dataUint32[i];\n k2 = ((k2 * C1) & MASK_HIGH) | ((k2 * C1_LOW) & MASK_LOW);\n k2 = (k2 << 15) | (k2 >>> 17);\n k2 = ((k2 * C2) & MASK_HIGH) | ((k2 * C2_LOW) & MASK_LOW);\n h2 ^= k2;\n h2 = (h2 << 13) | (h2 >>> 19);\n h2 = h2 * 5 + 0xe6546b64;\n }\n }\n\n k1 = 0;\n\n switch (tailLength) {\n case 3:\n k1 ^= data[blockCounts * 4 + 2] << 16;\n /* falls through */\n case 2:\n k1 ^= data[blockCounts * 4 + 1] << 8;\n /* falls through */\n case 1:\n k1 ^= data[blockCounts * 4];\n /* falls through */\n\n k1 = ((k1 * C1) & MASK_HIGH) | ((k1 * C1_LOW) & MASK_LOW);\n k1 = (k1 << 15) | (k1 >>> 17);\n k1 = ((k1 * C2) & MASK_HIGH) | ((k1 * C2_LOW) & MASK_LOW);\n if (blockCounts & 1) {\n h1 ^= k1;\n } else {\n h2 ^= k1;\n }\n }\n\n this.h1 = h1;\n this.h2 = h2;\n }\n\n hexdigest() {\n let h1 = this.h1,\n h2 = this.h2;\n\n h1 ^= h2 >>> 1;\n h1 = ((h1 * 0xed558ccd) & MASK_HIGH) | ((h1 * 0x8ccd) & MASK_LOW);\n h2 =\n ((h2 * 0xff51afd7) & MASK_HIGH) |\n (((((h2 << 16) | (h1 >>> 16)) * 0xafd7ed55) & MASK_HIGH) >>> 16);\n h1 ^= h2 >>> 1;\n h1 = ((h1 * 0x1a85ec53) & MASK_HIGH) | ((h1 * 0xec53) & MASK_LOW);\n h2 =\n ((h2 * 0xc4ceb9fe) & MASK_HIGH) |\n (((((h2 << 16) | (h1 >>> 16)) * 0xb9fe1a85) & MASK_HIGH) >>> 16);\n h1 ^= h2 >>> 1;\n\n return (\n (h1 >>> 0).toString(16).padStart(8, \"0\") +\n (h2 >>> 0).toString(16).padStart(8, \"0\")\n );\n }\n}\n\nexport { MurmurHash3_64 };\n","/* Copyright 2020 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { objectFromMap, shadow, unreachable } from \"../shared/util.js\";\nimport { AnnotationEditor } from \"./editor/editor.js\";\nimport { MurmurHash3_64 } from \"../shared/murmurhash3.js\";\n\nconst SerializableEmpty = Object.freeze({\n map: null,\n hash: \"\",\n transfer: undefined,\n});\n\n/**\n * Key/value storage for annotation data in forms.\n */\nclass AnnotationStorage {\n #modified = false;\n\n #modifiedIds = null;\n\n #storage = new Map();\n\n constructor() {\n // Callbacks to signal when the modification state is set or reset.\n // This is used by the viewer to only bind on `beforeunload` if forms\n // are actually edited to prevent doing so unconditionally since that\n // can have undesirable effects.\n this.onSetModified = null;\n this.onResetModified = null;\n this.onAnnotationEditor = null;\n }\n\n /**\n * Get the value for a given key if it exists, or return the default value.\n * @param {string} key\n * @param {Object} defaultValue\n * @returns {Object}\n */\n getValue(key, defaultValue) {\n const value = this.#storage.get(key);\n if (value === undefined) {\n return defaultValue;\n }\n\n return Object.assign(defaultValue, value);\n }\n\n /**\n * Get the value for a given key.\n * @param {string} key\n * @returns {Object}\n */\n getRawValue(key) {\n return this.#storage.get(key);\n }\n\n /**\n * Remove a value from the storage.\n * @param {string} key\n */\n remove(key) {\n this.#storage.delete(key);\n\n if (this.#storage.size === 0) {\n this.resetModified();\n }\n\n if (typeof this.onAnnotationEditor === \"function\") {\n for (const value of this.#storage.values()) {\n if (value instanceof AnnotationEditor) {\n return;\n }\n }\n this.onAnnotationEditor(null);\n }\n }\n\n /**\n * Set the value for a given key\n * @param {string} key\n * @param {Object} value\n */\n setValue(key, value) {\n const obj = this.#storage.get(key);\n let modified = false;\n if (obj !== undefined) {\n for (const [entry, val] of Object.entries(value)) {\n if (obj[entry] !== val) {\n modified = true;\n obj[entry] = val;\n }\n }\n } else {\n modified = true;\n this.#storage.set(key, value);\n }\n if (modified) {\n this.#setModified();\n }\n\n if (\n value instanceof AnnotationEditor &&\n typeof this.onAnnotationEditor === \"function\"\n ) {\n this.onAnnotationEditor(value.constructor._type);\n }\n }\n\n /**\n * Check if the storage contains the given key.\n * @param {string} key\n * @returns {boolean}\n */\n has(key) {\n return this.#storage.has(key);\n }\n\n /**\n * @returns {Object | null}\n */\n getAll() {\n return this.#storage.size > 0 ? objectFromMap(this.#storage) : null;\n }\n\n /**\n * @param {Object} obj\n */\n setAll(obj) {\n for (const [key, val] of Object.entries(obj)) {\n this.setValue(key, val);\n }\n }\n\n get size() {\n return this.#storage.size;\n }\n\n #setModified() {\n if (!this.#modified) {\n this.#modified = true;\n if (typeof this.onSetModified === \"function\") {\n this.onSetModified();\n }\n }\n }\n\n resetModified() {\n if (this.#modified) {\n this.#modified = false;\n if (typeof this.onResetModified === \"function\") {\n this.onResetModified();\n }\n }\n }\n\n /**\n * @returns {PrintAnnotationStorage}\n */\n get print() {\n return new PrintAnnotationStorage(this);\n }\n\n /**\n * PLEASE NOTE: Only intended for usage within the API itself.\n * @ignore\n */\n get serializable() {\n if (this.#storage.size === 0) {\n return SerializableEmpty;\n }\n const map = new Map(),\n hash = new MurmurHash3_64(),\n transfer = [];\n const context = Object.create(null);\n let hasBitmap = false;\n\n for (const [key, val] of this.#storage) {\n const serialized =\n val instanceof AnnotationEditor\n ? val.serialize(/* isForCopying = */ false, context)\n : val;\n if (serialized) {\n map.set(key, serialized);\n\n hash.update(`${key}:${JSON.stringify(serialized)}`);\n hasBitmap ||= !!serialized.bitmap;\n }\n }\n\n if (hasBitmap) {\n // We must transfer the bitmap data separately, since it can be changed\n // during serialization with SVG images.\n for (const value of map.values()) {\n if (value.bitmap) {\n transfer.push(value.bitmap);\n }\n }\n }\n\n return map.size > 0\n ? { map, hash: hash.hexdigest(), transfer }\n : SerializableEmpty;\n }\n\n get editorStats() {\n let stats = null;\n const typeToEditor = new Map();\n for (const value of this.#storage.values()) {\n if (!(value instanceof AnnotationEditor)) {\n continue;\n }\n const editorStats = value.telemetryFinalData;\n if (!editorStats) {\n continue;\n }\n const { type } = editorStats;\n if (!typeToEditor.has(type)) {\n typeToEditor.set(type, Object.getPrototypeOf(value).constructor);\n }\n stats ||= Object.create(null);\n const map = (stats[type] ||= new Map());\n for (const [key, val] of Object.entries(editorStats)) {\n if (key === \"type\") {\n continue;\n }\n let counters = map.get(key);\n if (!counters) {\n counters = new Map();\n map.set(key, counters);\n }\n const count = counters.get(val) ?? 0;\n counters.set(val, count + 1);\n }\n }\n for (const [type, editor] of typeToEditor) {\n stats[type] = editor.computeTelemetryFinalData(stats[type]);\n }\n return stats;\n }\n\n resetModifiedIds() {\n this.#modifiedIds = null;\n }\n\n /**\n * @returns {{ids: Set, hash: string}}\n */\n get modifiedIds() {\n if (this.#modifiedIds) {\n return this.#modifiedIds;\n }\n const ids = [];\n for (const value of this.#storage.values()) {\n if (\n !(value instanceof AnnotationEditor) ||\n !value.annotationElementId ||\n !value.serialize()\n ) {\n continue;\n }\n ids.push(value.annotationElementId);\n }\n return (this.#modifiedIds = {\n ids: new Set(ids),\n hash: ids.join(\",\"),\n });\n }\n}\n\n/**\n * A special `AnnotationStorage` for use during printing, where the serializable\n * data is *frozen* upon initialization, to prevent scripting from modifying its\n * contents. (Necessary since printing is triggered synchronously in browsers.)\n */\nclass PrintAnnotationStorage extends AnnotationStorage {\n #serializable;\n\n constructor(parent) {\n super();\n const { map, hash, transfer } = parent.serializable;\n // Create a *copy* of the data, since Objects are passed by reference in JS.\n const clone = structuredClone(map, transfer ? { transfer } : null);\n\n this.#serializable = { map: clone, hash, transfer };\n }\n\n /**\n * @returns {PrintAnnotationStorage}\n */\n // eslint-disable-next-line getter-return\n get print() {\n unreachable(\"Should not call PrintAnnotationStorage.print\");\n }\n\n /**\n * PLEASE NOTE: Only intended for usage within the API itself.\n * @ignore\n */\n get serializable() {\n return this.#serializable;\n }\n\n get modifiedIds() {\n return shadow(this, \"modifiedIds\", {\n ids: new Set(),\n hash: \"\",\n });\n }\n}\n\nexport { AnnotationStorage, PrintAnnotationStorage, SerializableEmpty };\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n FontRenderOps,\n isNodeJS,\n shadow,\n string32,\n toBase64Util,\n unreachable,\n warn,\n} from \"../shared/util.js\";\n\nclass FontLoader {\n #systemFonts = new Set();\n\n constructor({\n ownerDocument = globalThis.document,\n styleElement = null, // For testing only.\n }) {\n this._document = ownerDocument;\n\n this.nativeFontFaces = new Set();\n this.styleElement =\n typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")\n ? styleElement\n : null;\n\n if (typeof PDFJSDev === \"undefined\" || !PDFJSDev.test(\"MOZCENTRAL\")) {\n this.loadingRequests = [];\n this.loadTestFontId = 0;\n }\n }\n\n addNativeFontFace(nativeFontFace) {\n this.nativeFontFaces.add(nativeFontFace);\n this._document.fonts.add(nativeFontFace);\n }\n\n removeNativeFontFace(nativeFontFace) {\n this.nativeFontFaces.delete(nativeFontFace);\n this._document.fonts.delete(nativeFontFace);\n }\n\n insertRule(rule) {\n if (!this.styleElement) {\n this.styleElement = this._document.createElement(\"style\");\n this._document.documentElement\n .getElementsByTagName(\"head\")[0]\n .append(this.styleElement);\n }\n const styleSheet = this.styleElement.sheet;\n styleSheet.insertRule(rule, styleSheet.cssRules.length);\n }\n\n clear() {\n for (const nativeFontFace of this.nativeFontFaces) {\n this._document.fonts.delete(nativeFontFace);\n }\n this.nativeFontFaces.clear();\n this.#systemFonts.clear();\n\n if (this.styleElement) {\n // Note: ChildNode.remove doesn't throw if the parentNode is undefined.\n this.styleElement.remove();\n this.styleElement = null;\n }\n }\n\n async loadSystemFont({ systemFontInfo: info, _inspectFont }) {\n if (!info || this.#systemFonts.has(info.loadedName)) {\n return;\n }\n assert(\n !this.disableFontFace,\n \"loadSystemFont shouldn't be called when `disableFontFace` is set.\"\n );\n\n if (this.isFontLoadingAPISupported) {\n const { loadedName, src, style } = info;\n const fontFace = new FontFace(loadedName, src, style);\n this.addNativeFontFace(fontFace);\n try {\n await fontFace.load();\n this.#systemFonts.add(loadedName);\n _inspectFont?.(info);\n } catch {\n warn(\n `Cannot load system font: ${info.baseFontName}, installing it could help to improve PDF rendering.`\n );\n\n this.removeNativeFontFace(fontFace);\n }\n return;\n }\n\n unreachable(\n \"Not implemented: loadSystemFont without the Font Loading API.\"\n );\n }\n\n async bind(font) {\n // Add the font to the DOM only once; skip if the font is already loaded.\n if (font.attached || (font.missingFile && !font.systemFontInfo)) {\n return;\n }\n font.attached = true;\n\n if (font.systemFontInfo) {\n await this.loadSystemFont(font);\n return;\n }\n\n if (this.isFontLoadingAPISupported) {\n const nativeFontFace = font.createNativeFontFace();\n if (nativeFontFace) {\n this.addNativeFontFace(nativeFontFace);\n try {\n await nativeFontFace.loaded;\n } catch (ex) {\n warn(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);\n\n // When font loading failed, fall back to the built-in font renderer.\n font.disableFontFace = true;\n throw ex;\n }\n }\n return; // The font was, asynchronously, loaded.\n }\n\n // !this.isFontLoadingAPISupported\n const rule = font.createFontFaceRule();\n if (rule) {\n this.insertRule(rule);\n\n if (this.isSyncFontLoadingSupported) {\n return; // The font was, synchronously, loaded.\n }\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: async font loading\");\n }\n await new Promise(resolve => {\n const request = this._queueLoadingCallback(resolve);\n this._prepareFontLoadEvent(font, request);\n });\n // The font was, asynchronously, loaded.\n }\n }\n\n get isFontLoadingAPISupported() {\n const hasFonts = !!this._document?.fonts;\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n return shadow(\n this,\n \"isFontLoadingAPISupported\",\n hasFonts && !this.styleElement\n );\n }\n return shadow(this, \"isFontLoadingAPISupported\", hasFonts);\n }\n\n get isSyncFontLoadingSupported() {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n return shadow(this, \"isSyncFontLoadingSupported\", true);\n }\n\n let supported = false;\n if (typeof PDFJSDev === \"undefined\" || !PDFJSDev.test(\"CHROME\")) {\n if (isNodeJS) {\n // Node.js - we can pretend that sync font loading is supported.\n supported = true;\n } else if (\n typeof navigator !== \"undefined\" &&\n typeof navigator?.userAgent === \"string\" &&\n // User agent string sniffing is bad, but there is no reliable way to\n // tell if the font is fully loaded and ready to be used with canvas.\n /Mozilla\\/5.0.*?rv:\\d+.*? Gecko/.test(navigator.userAgent)\n ) {\n // Firefox, from version 14, supports synchronous font loading.\n supported = true;\n }\n }\n return shadow(this, \"isSyncFontLoadingSupported\", supported);\n }\n\n _queueLoadingCallback(callback) {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: _queueLoadingCallback\");\n }\n\n function completeRequest() {\n assert(!request.done, \"completeRequest() cannot be called twice.\");\n request.done = true;\n\n // Sending all completed requests in order of how they were queued.\n while (loadingRequests.length > 0 && loadingRequests[0].done) {\n const otherRequest = loadingRequests.shift();\n setTimeout(otherRequest.callback, 0);\n }\n }\n\n const { loadingRequests } = this;\n const request = {\n done: false,\n complete: completeRequest,\n callback,\n };\n loadingRequests.push(request);\n return request;\n }\n\n get _loadTestFont() {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: _loadTestFont\");\n }\n\n // This is a CFF font with 1 glyph for '.' that fills its entire width\n // and height.\n const testFont = atob(\n \"T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQA\" +\n \"FQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAA\" +\n \"ALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgA\" +\n \"AAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1\" +\n \"AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD\" +\n \"6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACM\" +\n \"AooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4D\" +\n \"IP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAA\" +\n \"AAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUA\" +\n \"AQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgAB\" +\n \"AAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABY\" +\n \"AAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAA\" +\n \"AC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" +\n \"AAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" +\n \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" +\n \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" +\n \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\" +\n \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAA\" +\n \"AAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQAC\" +\n \"AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3\" +\n \"Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj\" +\n \"FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==\"\n );\n return shadow(this, \"_loadTestFont\", testFont);\n }\n\n _prepareFontLoadEvent(font, request) {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: _prepareFontLoadEvent\");\n }\n\n /** Hack begin */\n // There's currently no event when a font has finished downloading so the\n // following code is a dirty hack to 'guess' when a font is ready.\n // It's assumed fonts are loaded in order, so add a known test font after\n // the desired fonts and then test for the loading of that test font.\n\n function int32(data, offset) {\n return (\n (data.charCodeAt(offset) << 24) |\n (data.charCodeAt(offset + 1) << 16) |\n (data.charCodeAt(offset + 2) << 8) |\n (data.charCodeAt(offset + 3) & 0xff)\n );\n }\n function spliceString(s, offset, remove, insert) {\n const chunk1 = s.substring(0, offset);\n const chunk2 = s.substring(offset + remove);\n return chunk1 + insert + chunk2;\n }\n let i, ii;\n\n // The temporary canvas is used to determine if fonts are loaded.\n const canvas = this._document.createElement(\"canvas\");\n canvas.width = 1;\n canvas.height = 1;\n const ctx = canvas.getContext(\"2d\");\n\n let called = 0;\n function isFontReady(name, callback) {\n // With setTimeout clamping this gives the font ~100ms to load.\n if (++called > 30) {\n warn(\"Load test font never loaded.\");\n callback();\n return;\n }\n ctx.font = \"30px \" + name;\n ctx.fillText(\".\", 0, 20);\n const imageData = ctx.getImageData(0, 0, 1, 1);\n if (imageData.data[3] > 0) {\n callback();\n return;\n }\n setTimeout(isFontReady.bind(null, name, callback));\n }\n\n const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;\n // Chromium seems to cache fonts based on a hash of the actual font data,\n // so the font must be modified for each load test else it will appear to\n // be loaded already.\n // TODO: This could maybe be made faster by avoiding the btoa of the full\n // font by splitting it in chunks before hand and padding the font id.\n let data = this._loadTestFont;\n const COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)\n data = spliceString(\n data,\n COMMENT_OFFSET,\n loadTestFontId.length,\n loadTestFontId\n );\n // CFF checksum is important for IE, adjusting it\n const CFF_CHECKSUM_OFFSET = 16;\n const XXXX_VALUE = 0x58585858; // the \"comment\" filled with 'X'\n let checksum = int32(data, CFF_CHECKSUM_OFFSET);\n for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {\n checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;\n }\n if (i < loadTestFontId.length) {\n // align to 4 bytes boundary\n checksum = (checksum - XXXX_VALUE + int32(loadTestFontId + \"XXX\", i)) | 0;\n }\n data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));\n\n const url = `url(data:font/opentype;base64,${btoa(data)});`;\n const rule = `@font-face {font-family:\"${loadTestFontId}\";src:${url}}`;\n this.insertRule(rule);\n\n const div = this._document.createElement(\"div\");\n div.style.visibility = \"hidden\";\n div.style.width = div.style.height = \"10px\";\n div.style.position = \"absolute\";\n div.style.top = div.style.left = \"0px\";\n\n for (const name of [font.loadedName, loadTestFontId]) {\n const span = this._document.createElement(\"span\");\n span.textContent = \"Hi\";\n span.style.fontFamily = name;\n div.append(span);\n }\n this._document.body.append(div);\n\n isFontReady(loadTestFontId, () => {\n div.remove();\n request.complete();\n });\n /** Hack end */\n }\n}\n\nclass FontFaceObject {\n constructor(translatedData, { disableFontFace = false, inspectFont = null }) {\n this.compiledGlyphs = Object.create(null);\n // importing translated data\n for (const i in translatedData) {\n this[i] = translatedData[i];\n }\n this.disableFontFace = disableFontFace === true;\n this._inspectFont = inspectFont;\n }\n\n createNativeFontFace() {\n if (!this.data || this.disableFontFace) {\n return null;\n }\n let nativeFontFace;\n if (!this.cssFontInfo) {\n nativeFontFace = new FontFace(this.loadedName, this.data, {});\n } else {\n const css = {\n weight: this.cssFontInfo.fontWeight,\n };\n if (this.cssFontInfo.italicAngle) {\n css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;\n }\n nativeFontFace = new FontFace(\n this.cssFontInfo.fontFamily,\n this.data,\n css\n );\n }\n\n this._inspectFont?.(this);\n return nativeFontFace;\n }\n\n createFontFaceRule() {\n if (!this.data || this.disableFontFace) {\n return null;\n }\n // Add the @font-face rule to the document.\n const url = `url(data:${this.mimetype};base64,${toBase64Util(this.data)});`;\n let rule;\n if (!this.cssFontInfo) {\n rule = `@font-face {font-family:\"${this.loadedName}\";src:${url}}`;\n } else {\n let css = `font-weight: ${this.cssFontInfo.fontWeight};`;\n if (this.cssFontInfo.italicAngle) {\n css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;\n }\n rule = `@font-face {font-family:\"${this.cssFontInfo.fontFamily}\";${css}src:${url}}`;\n }\n\n this._inspectFont?.(this, url);\n return rule;\n }\n\n getPathGenerator(objs, character) {\n if (this.compiledGlyphs[character] !== undefined) {\n return this.compiledGlyphs[character];\n }\n\n let cmds;\n try {\n cmds = objs.get(this.loadedName + \"_path_\" + character);\n } catch (ex) {\n warn(`getPathGenerator - ignoring character: \"${ex}\".`);\n }\n\n if (!Array.isArray(cmds) || cmds.length === 0) {\n return (this.compiledGlyphs[character] = function (c, size) {\n // No-op function, to allow rendering to continue.\n });\n }\n\n const commands = [];\n for (let i = 0, ii = cmds.length; i < ii; ) {\n switch (cmds[i++]) {\n case FontRenderOps.BEZIER_CURVE_TO:\n {\n const [a, b, c, d, e, f] = cmds.slice(i, i + 6);\n commands.push(ctx => ctx.bezierCurveTo(a, b, c, d, e, f));\n i += 6;\n }\n break;\n case FontRenderOps.MOVE_TO:\n {\n const [a, b] = cmds.slice(i, i + 2);\n commands.push(ctx => ctx.moveTo(a, b));\n i += 2;\n }\n break;\n case FontRenderOps.LINE_TO:\n {\n const [a, b] = cmds.slice(i, i + 2);\n commands.push(ctx => ctx.lineTo(a, b));\n i += 2;\n }\n break;\n case FontRenderOps.QUADRATIC_CURVE_TO:\n {\n const [a, b, c, d] = cmds.slice(i, i + 4);\n commands.push(ctx => ctx.quadraticCurveTo(a, b, c, d));\n i += 4;\n }\n break;\n case FontRenderOps.RESTORE:\n commands.push(ctx => ctx.restore());\n break;\n case FontRenderOps.SAVE:\n commands.push(ctx => ctx.save());\n break;\n case FontRenderOps.SCALE:\n // The scale command must be at the third position, after save and\n // transform (for the font matrix) commands (see also\n // font_renderer.js).\n // The goal is to just scale the canvas and then run the commands loop\n // without the need to pass the size parameter to each command.\n assert(\n commands.length === 2,\n \"Scale command is only valid at the third position.\"\n );\n break;\n case FontRenderOps.TRANSFORM:\n {\n const [a, b, c, d, e, f] = cmds.slice(i, i + 6);\n commands.push(ctx => ctx.transform(a, b, c, d, e, f));\n i += 6;\n }\n break;\n case FontRenderOps.TRANSLATE:\n {\n const [a, b] = cmds.slice(i, i + 2);\n commands.push(ctx => ctx.translate(a, b));\n i += 2;\n }\n break;\n }\n }\n // From https://learn.microsoft.com/en-us/typography/opentype/spec/cff2#paths\n // All contours must be closed with a lineto operation.\n commands.push(ctx => ctx.closePath());\n\n return (this.compiledGlyphs[character] = function glyphDrawer(ctx, size) {\n commands[0](ctx);\n commands[1](ctx);\n ctx.scale(size, -size);\n for (let i = 2, ii = commands.length; i < ii; i++) {\n commands[i](ctx);\n }\n });\n }\n}\n\nexport { FontFaceObject, FontLoader };\n","/* Copyright 2015 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { unreachable } from \"../shared/util.js\";\n\nclass BaseCanvasFactory {\n #enableHWA = false;\n\n constructor({ enableHWA = false }) {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === BaseCanvasFactory\n ) {\n unreachable(\"Cannot initialize BaseCanvasFactory.\");\n }\n this.#enableHWA = enableHWA;\n }\n\n create(width, height) {\n if (width <= 0 || height <= 0) {\n throw new Error(\"Invalid canvas size\");\n }\n const canvas = this._createCanvas(width, height);\n return {\n canvas,\n context: canvas.getContext(\"2d\", {\n willReadFrequently: !this.#enableHWA,\n }),\n };\n }\n\n reset(canvasAndContext, width, height) {\n if (!canvasAndContext.canvas) {\n throw new Error(\"Canvas is not specified\");\n }\n if (width <= 0 || height <= 0) {\n throw new Error(\"Invalid canvas size\");\n }\n canvasAndContext.canvas.width = width;\n canvasAndContext.canvas.height = height;\n }\n\n destroy(canvasAndContext) {\n if (!canvasAndContext.canvas) {\n throw new Error(\"Canvas is not specified\");\n }\n // Zeroing the width and height cause Firefox to release graphics\n // resources immediately, which can greatly reduce memory consumption.\n canvasAndContext.canvas.width = 0;\n canvasAndContext.canvas.height = 0;\n canvasAndContext.canvas = null;\n canvasAndContext.context = null;\n }\n\n /**\n * @ignore\n */\n _createCanvas(width, height) {\n unreachable(\"Abstract method `_createCanvas` called.\");\n }\n}\n\nclass DOMCanvasFactory extends BaseCanvasFactory {\n constructor({ ownerDocument = globalThis.document, enableHWA = false }) {\n super({ enableHWA });\n this._document = ownerDocument;\n }\n\n /**\n * @ignore\n */\n _createCanvas(width, height) {\n const canvas = this._document.createElement(\"canvas\");\n canvas.width = width;\n canvas.height = height;\n return canvas;\n }\n}\n\nexport { BaseCanvasFactory, DOMCanvasFactory };\n","/* Copyright 2015 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { stringToBytes, unreachable } from \"../shared/util.js\";\nimport { fetchData } from \"./display_utils.js\";\n\nclass BaseCMapReaderFactory {\n constructor({ baseUrl = null, isCompressed = true }) {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === BaseCMapReaderFactory\n ) {\n unreachable(\"Cannot initialize BaseCMapReaderFactory.\");\n }\n this.baseUrl = baseUrl;\n this.isCompressed = isCompressed;\n }\n\n async fetch({ name }) {\n if (!this.baseUrl) {\n throw new Error(\n \"Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.\"\n );\n }\n if (!name) {\n throw new Error(\"CMap name must be specified.\");\n }\n const url = this.baseUrl + name + (this.isCompressed ? \".bcmap\" : \"\");\n\n return this._fetch(url)\n .then(cMapData => ({ cMapData, isCompressed: this.isCompressed }))\n .catch(reason => {\n throw new Error(\n `Unable to load ${this.isCompressed ? \"binary \" : \"\"}CMap at: ${url}`\n );\n });\n }\n\n /**\n * @ignore\n * @returns {Promise}\n */\n async _fetch(url) {\n unreachable(\"Abstract method `_fetch` called.\");\n }\n}\n\nclass DOMCMapReaderFactory extends BaseCMapReaderFactory {\n /**\n * @ignore\n */\n async _fetch(url) {\n const data = await fetchData(\n url,\n /* type = */ this.isCompressed ? \"arraybuffer\" : \"text\"\n );\n return data instanceof ArrayBuffer\n ? new Uint8Array(data)\n : stringToBytes(data);\n }\n}\n\nexport { BaseCMapReaderFactory, DOMCMapReaderFactory };\n","/* Copyright 2015 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getRGB, isDataScheme, SVG_NS } from \"./display_utils.js\";\nimport { unreachable, Util, warn } from \"../shared/util.js\";\n\nclass BaseFilterFactory {\n constructor() {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === BaseFilterFactory\n ) {\n unreachable(\"Cannot initialize BaseFilterFactory.\");\n }\n }\n\n addFilter(maps) {\n return \"none\";\n }\n\n addHCMFilter(fgColor, bgColor) {\n return \"none\";\n }\n\n addAlphaFilter(map) {\n return \"none\";\n }\n\n addLuminosityFilter(map) {\n return \"none\";\n }\n\n addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {\n return \"none\";\n }\n\n destroy(keepHCM = false) {}\n}\n\n/**\n * FilterFactory aims to create some SVG filters we can use when drawing an\n * image (or whatever) on a canvas.\n * Filters aren't applied with ctx.putImageData because it just overwrites the\n * underlying pixels.\n * With these filters, it's possible for example to apply some transfer maps on\n * an image without the need to apply them on the pixel arrays: the renderer\n * does the magic for us.\n */\nclass DOMFilterFactory extends BaseFilterFactory {\n #baseUrl;\n\n #_cache;\n\n #_defs;\n\n #docId;\n\n #document;\n\n #_hcmCache;\n\n #id = 0;\n\n constructor({ docId, ownerDocument = globalThis.document }) {\n super();\n this.#docId = docId;\n this.#document = ownerDocument;\n }\n\n get #cache() {\n return (this.#_cache ||= new Map());\n }\n\n get #hcmCache() {\n return (this.#_hcmCache ||= new Map());\n }\n\n get #defs() {\n if (!this.#_defs) {\n const div = this.#document.createElement(\"div\");\n const { style } = div;\n style.visibility = \"hidden\";\n style.contain = \"strict\";\n style.width = style.height = 0;\n style.position = \"absolute\";\n style.top = style.left = 0;\n style.zIndex = -1;\n\n const svg = this.#document.createElementNS(SVG_NS, \"svg\");\n svg.setAttribute(\"width\", 0);\n svg.setAttribute(\"height\", 0);\n this.#_defs = this.#document.createElementNS(SVG_NS, \"defs\");\n div.append(svg);\n svg.append(this.#_defs);\n this.#document.body.append(div);\n }\n return this.#_defs;\n }\n\n #createTables(maps) {\n if (maps.length === 1) {\n const mapR = maps[0];\n const buffer = new Array(256);\n for (let i = 0; i < 256; i++) {\n buffer[i] = mapR[i] / 255;\n }\n\n const table = buffer.join(\",\");\n return [table, table, table];\n }\n\n const [mapR, mapG, mapB] = maps;\n const bufferR = new Array(256);\n const bufferG = new Array(256);\n const bufferB = new Array(256);\n for (let i = 0; i < 256; i++) {\n bufferR[i] = mapR[i] / 255;\n bufferG[i] = mapG[i] / 255;\n bufferB[i] = mapB[i] / 255;\n }\n return [bufferR.join(\",\"), bufferG.join(\",\"), bufferB.join(\",\")];\n }\n\n #createUrl(id) {\n if (this.#baseUrl === undefined) {\n // Unless a ``-element is present a relative URL should work.\n this.#baseUrl = \"\";\n\n const url = this.#document.URL;\n if (url !== this.#document.baseURI) {\n if (isDataScheme(url)) {\n warn('#createUrl: ignore \"data:\"-URL for performance reasons.');\n } else {\n this.#baseUrl = url.split(\"#\", 1)[0];\n }\n }\n }\n return `url(${this.#baseUrl}#${id})`;\n }\n\n addFilter(maps) {\n if (!maps) {\n return \"none\";\n }\n\n // When a page is zoomed the page is re-drawn but the maps are likely\n // the same.\n let value = this.#cache.get(maps);\n if (value) {\n return value;\n }\n\n const [tableR, tableG, tableB] = this.#createTables(maps);\n const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`;\n\n value = this.#cache.get(key);\n if (value) {\n this.#cache.set(maps, value);\n return value;\n }\n\n // We create a SVG filter: feComponentTransferElement\n // https://www.w3.org/TR/SVG11/filters.html#feComponentTransferElement\n\n const id = `g_${this.#docId}_transfer_map_${this.#id++}`;\n const url = this.#createUrl(id);\n this.#cache.set(maps, url);\n this.#cache.set(key, url);\n\n const filter = this.#createFilter(id);\n this.#addTransferMapConversion(tableR, tableG, tableB, filter);\n\n return url;\n }\n\n addHCMFilter(fgColor, bgColor) {\n const key = `${fgColor}-${bgColor}`;\n const filterName = \"base\";\n let info = this.#hcmCache.get(filterName);\n if (info?.key === key) {\n return info.url;\n }\n\n if (info) {\n info.filter?.remove();\n info.key = key;\n info.url = \"none\";\n info.filter = null;\n } else {\n info = {\n key,\n url: \"none\",\n filter: null,\n };\n this.#hcmCache.set(filterName, info);\n }\n\n if (!fgColor || !bgColor) {\n return info.url;\n }\n\n const fgRGB = this.#getRGB(fgColor);\n fgColor = Util.makeHexColor(...fgRGB);\n const bgRGB = this.#getRGB(bgColor);\n bgColor = Util.makeHexColor(...bgRGB);\n this.#defs.style.color = \"\";\n\n if (\n (fgColor === \"#000000\" && bgColor === \"#ffffff\") ||\n fgColor === bgColor\n ) {\n return info.url;\n }\n\n // https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_Colors_and_Luminance\n //\n // Relative luminance:\n // https://www.w3.org/TR/WCAG20/#relativeluminancedef\n //\n // We compute the rounded luminance of the default background color.\n // Then for every color in the pdf, if its rounded luminance is the\n // same as the background one then it's replaced by the new\n // background color else by the foreground one.\n const map = new Array(256);\n for (let i = 0; i <= 255; i++) {\n const x = i / 255;\n map[i] = x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;\n }\n const table = map.join(\",\");\n\n const id = `g_${this.#docId}_hcm_filter`;\n const filter = (info.filter = this.#createFilter(id));\n this.#addTransferMapConversion(table, table, table, filter);\n this.#addGrayConversion(filter);\n\n const getSteps = (c, n) => {\n const start = fgRGB[c] / 255;\n const end = bgRGB[c] / 255;\n const arr = new Array(n + 1);\n for (let i = 0; i <= n; i++) {\n arr[i] = start + (i / n) * (end - start);\n }\n return arr.join(\",\");\n };\n this.#addTransferMapConversion(\n getSteps(0, 5),\n getSteps(1, 5),\n getSteps(2, 5),\n filter\n );\n\n info.url = this.#createUrl(id);\n return info.url;\n }\n\n addAlphaFilter(map) {\n // When a page is zoomed the page is re-drawn but the maps are likely\n // the same.\n let value = this.#cache.get(map);\n if (value) {\n return value;\n }\n\n const [tableA] = this.#createTables([map]);\n const key = `alpha_${tableA}`;\n\n value = this.#cache.get(key);\n if (value) {\n this.#cache.set(map, value);\n return value;\n }\n\n const id = `g_${this.#docId}_alpha_map_${this.#id++}`;\n const url = this.#createUrl(id);\n this.#cache.set(map, url);\n this.#cache.set(key, url);\n\n const filter = this.#createFilter(id);\n this.#addTransferMapAlphaConversion(tableA, filter);\n\n return url;\n }\n\n addLuminosityFilter(map) {\n // When a page is zoomed the page is re-drawn but the maps are likely\n // the same.\n let value = this.#cache.get(map || \"luminosity\");\n if (value) {\n return value;\n }\n\n let tableA, key;\n if (map) {\n [tableA] = this.#createTables([map]);\n key = `luminosity_${tableA}`;\n } else {\n key = \"luminosity\";\n }\n\n value = this.#cache.get(key);\n if (value) {\n this.#cache.set(map, value);\n return value;\n }\n\n const id = `g_${this.#docId}_luminosity_map_${this.#id++}`;\n const url = this.#createUrl(id);\n this.#cache.set(map, url);\n this.#cache.set(key, url);\n\n const filter = this.#createFilter(id);\n this.#addLuminosityConversion(filter);\n if (map) {\n this.#addTransferMapAlphaConversion(tableA, filter);\n }\n\n return url;\n }\n\n addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) {\n const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`;\n let info = this.#hcmCache.get(filterName);\n if (info?.key === key) {\n return info.url;\n }\n\n if (info) {\n info.filter?.remove();\n info.key = key;\n info.url = \"none\";\n info.filter = null;\n } else {\n info = {\n key,\n url: \"none\",\n filter: null,\n };\n this.#hcmCache.set(filterName, info);\n }\n\n if (!fgColor || !bgColor) {\n return info.url;\n }\n\n const [fgRGB, bgRGB] = [fgColor, bgColor].map(this.#getRGB.bind(this));\n let fgGray = Math.round(\n 0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]\n );\n let bgGray = Math.round(\n 0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]\n );\n let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(\n this.#getRGB.bind(this)\n );\n if (bgGray < fgGray) {\n [fgGray, bgGray, newFgRGB, newBgRGB] = [\n bgGray,\n fgGray,\n newBgRGB,\n newFgRGB,\n ];\n }\n this.#defs.style.color = \"\";\n\n // Now we can create the filters to highlight some canvas parts.\n // The colors in the pdf will almost be Canvas and CanvasText, hence we\n // want to filter them to finally get Highlight and HighlightText.\n // Since we're in HCM the background color and the foreground color should\n // be really different when converted to grayscale (if they're not then it\n // means that we've a poor contrast). Once the canvas colors are converted\n // to grayscale we can easily map them on their new colors.\n // The grayscale step is important because if we've something like:\n // fgColor = #FF....\n // bgColor = #FF....\n // then we are enable to map the red component on the new red components\n // which can be different.\n\n const getSteps = (fg, bg, n) => {\n const arr = new Array(256);\n const step = (bgGray - fgGray) / n;\n const newStart = fg / 255;\n const newStep = (bg - fg) / (255 * n);\n let prev = 0;\n for (let i = 0; i <= n; i++) {\n const k = Math.round(fgGray + i * step);\n const value = newStart + i * newStep;\n for (let j = prev; j <= k; j++) {\n arr[j] = value;\n }\n prev = k + 1;\n }\n for (let i = prev; i < 256; i++) {\n arr[i] = arr[prev - 1];\n }\n return arr.join(\",\");\n };\n\n const id = `g_${this.#docId}_hcm_${filterName}_filter`;\n const filter = (info.filter = this.#createFilter(id));\n\n this.#addGrayConversion(filter);\n this.#addTransferMapConversion(\n getSteps(newFgRGB[0], newBgRGB[0], 5),\n getSteps(newFgRGB[1], newBgRGB[1], 5),\n getSteps(newFgRGB[2], newBgRGB[2], 5),\n filter\n );\n\n info.url = this.#createUrl(id);\n return info.url;\n }\n\n destroy(keepHCM = false) {\n if (keepHCM && this.#_hcmCache?.size) {\n return;\n }\n this.#_defs?.parentNode.parentNode.remove();\n this.#_defs = null;\n\n this.#_cache?.clear();\n this.#_cache = null;\n\n this.#_hcmCache?.clear();\n this.#_hcmCache = null;\n\n this.#id = 0;\n }\n\n #addLuminosityConversion(filter) {\n const feColorMatrix = this.#document.createElementNS(\n SVG_NS,\n \"feColorMatrix\"\n );\n feColorMatrix.setAttribute(\"type\", \"matrix\");\n feColorMatrix.setAttribute(\n \"values\",\n \"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0\"\n );\n filter.append(feColorMatrix);\n }\n\n #addGrayConversion(filter) {\n const feColorMatrix = this.#document.createElementNS(\n SVG_NS,\n \"feColorMatrix\"\n );\n feColorMatrix.setAttribute(\"type\", \"matrix\");\n feColorMatrix.setAttribute(\n \"values\",\n \"0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0\"\n );\n filter.append(feColorMatrix);\n }\n\n #createFilter(id) {\n const filter = this.#document.createElementNS(SVG_NS, \"filter\");\n filter.setAttribute(\"color-interpolation-filters\", \"sRGB\");\n filter.setAttribute(\"id\", id);\n this.#defs.append(filter);\n\n return filter;\n }\n\n #appendFeFunc(feComponentTransfer, func, table) {\n const feFunc = this.#document.createElementNS(SVG_NS, func);\n feFunc.setAttribute(\"type\", \"discrete\");\n feFunc.setAttribute(\"tableValues\", table);\n feComponentTransfer.append(feFunc);\n }\n\n #addTransferMapConversion(rTable, gTable, bTable, filter) {\n const feComponentTransfer = this.#document.createElementNS(\n SVG_NS,\n \"feComponentTransfer\"\n );\n filter.append(feComponentTransfer);\n this.#appendFeFunc(feComponentTransfer, \"feFuncR\", rTable);\n this.#appendFeFunc(feComponentTransfer, \"feFuncG\", gTable);\n this.#appendFeFunc(feComponentTransfer, \"feFuncB\", bTable);\n }\n\n #addTransferMapAlphaConversion(aTable, filter) {\n const feComponentTransfer = this.#document.createElementNS(\n SVG_NS,\n \"feComponentTransfer\"\n );\n filter.append(feComponentTransfer);\n this.#appendFeFunc(feComponentTransfer, \"feFuncA\", aTable);\n }\n\n #getRGB(color) {\n this.#defs.style.color = color;\n return getRGB(getComputedStyle(this.#defs).getPropertyValue(\"color\"));\n }\n}\n\nexport { BaseFilterFactory, DOMFilterFactory };\n","/* Copyright 2015 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fetchData } from \"./display_utils.js\";\nimport { unreachable } from \"../shared/util.js\";\n\nclass BaseStandardFontDataFactory {\n constructor({ baseUrl = null }) {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === BaseStandardFontDataFactory\n ) {\n unreachable(\"Cannot initialize BaseStandardFontDataFactory.\");\n }\n this.baseUrl = baseUrl;\n }\n\n async fetch({ filename }) {\n if (!this.baseUrl) {\n throw new Error(\n \"Ensure that the `standardFontDataUrl` API parameter is provided.\"\n );\n }\n if (!filename) {\n throw new Error(\"Font filename must be specified.\");\n }\n const url = `${this.baseUrl}${filename}`;\n\n return this._fetch(url).catch(reason => {\n throw new Error(`Unable to load font data at: ${url}`);\n });\n }\n\n /**\n * @ignore\n * @returns {Promise}\n */\n async _fetch(url) {\n unreachable(\"Abstract method `_fetch` called.\");\n }\n}\n\nclass DOMStandardFontDataFactory extends BaseStandardFontDataFactory {\n /**\n * @ignore\n */\n async _fetch(url) {\n const data = await fetchData(url, /* type = */ \"arraybuffer\");\n return new Uint8Array(data);\n }\n}\n\nexport { BaseStandardFontDataFactory, DOMStandardFontDataFactory };\n","/* Copyright 2020 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/* globals process */\n\nimport { isNodeJS, warn } from \"../shared/util.js\";\nimport { BaseCanvasFactory } from \"./canvas_factory.js\";\nimport { BaseCMapReaderFactory } from \"./cmap_reader_factory.js\";\nimport { BaseFilterFactory } from \"./filter_factory.js\";\nimport { BaseStandardFontDataFactory } from \"./standard_fontdata_factory.js\";\n\nif (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\n 'Module \"./node_utils.js\" shall not be used with MOZCENTRAL builds.'\n );\n}\n\nif (\n typeof PDFJSDev !== \"undefined\" &&\n !PDFJSDev.test(\"SKIP_BABEL\") &&\n isNodeJS\n) {\n let canvas;\n try {\n const require = process\n .getBuiltinModule(\"module\")\n .createRequire(import.meta.url);\n\n try {\n canvas = require(\"@napi-rs/canvas\");\n } catch (ex) {\n warn(`Cannot load \"@napi-rs/canvas\" package: \"${ex}\".`);\n }\n } catch {}\n\n if (!globalThis.DOMMatrix) {\n if (canvas?.DOMMatrix) {\n globalThis.DOMMatrix = canvas.DOMMatrix;\n } else {\n warn(\"Cannot polyfill `DOMMatrix`, rendering may be broken.\");\n }\n }\n if (!globalThis.ImageData) {\n if (canvas?.ImageData) {\n globalThis.ImageData = canvas.ImageData;\n } else {\n warn(\"Cannot polyfill `ImageData`, rendering may be broken.\");\n }\n }\n if (!globalThis.Path2D) {\n if (canvas?.Path2D) {\n globalThis.Path2D = canvas.Path2D;\n } else {\n warn(\"Cannot polyfill `Path2D`, rendering may be broken.\");\n }\n }\n}\n\nasync function fetchData(url) {\n const fs = process.getBuiltinModule(\"fs\");\n const data = await fs.promises.readFile(url);\n return new Uint8Array(data);\n}\n\nclass NodeFilterFactory extends BaseFilterFactory {}\n\nclass NodeCanvasFactory extends BaseCanvasFactory {\n /**\n * @ignore\n */\n _createCanvas(width, height) {\n const require = process\n .getBuiltinModule(\"module\")\n .createRequire(import.meta.url);\n const canvas = require(\"@napi-rs/canvas\");\n return canvas.createCanvas(width, height);\n }\n}\n\nclass NodeCMapReaderFactory extends BaseCMapReaderFactory {\n /**\n * @ignore\n */\n async _fetch(url) {\n return fetchData(url);\n }\n}\n\nclass NodeStandardFontDataFactory extends BaseStandardFontDataFactory {\n /**\n * @ignore\n */\n async _fetch(url) {\n return fetchData(url);\n }\n}\n\nexport {\n fetchData,\n NodeCanvasFactory,\n NodeCMapReaderFactory,\n NodeFilterFactory,\n NodeStandardFontDataFactory,\n};\n","/* Copyright 2014 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FormatError, info, unreachable, Util } from \"../shared/util.js\";\nimport { getCurrentTransform } from \"./display_utils.js\";\n\nconst PathType = {\n FILL: \"Fill\",\n STROKE: \"Stroke\",\n SHADING: \"Shading\",\n};\n\nfunction applyBoundingBox(ctx, bbox) {\n if (!bbox) {\n return;\n }\n const width = bbox[2] - bbox[0];\n const height = bbox[3] - bbox[1];\n const region = new Path2D();\n region.rect(bbox[0], bbox[1], width, height);\n ctx.clip(region);\n}\n\nclass BaseShadingPattern {\n constructor() {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === BaseShadingPattern\n ) {\n unreachable(\"Cannot initialize BaseShadingPattern.\");\n }\n }\n\n getPattern() {\n unreachable(\"Abstract method `getPattern` called.\");\n }\n}\n\nclass RadialAxialShadingPattern extends BaseShadingPattern {\n constructor(IR) {\n super();\n this._type = IR[1];\n this._bbox = IR[2];\n this._colorStops = IR[3];\n this._p0 = IR[4];\n this._p1 = IR[5];\n this._r0 = IR[6];\n this._r1 = IR[7];\n this.matrix = null;\n }\n\n _createGradient(ctx) {\n let grad;\n if (this._type === \"axial\") {\n grad = ctx.createLinearGradient(\n this._p0[0],\n this._p0[1],\n this._p1[0],\n this._p1[1]\n );\n } else if (this._type === \"radial\") {\n grad = ctx.createRadialGradient(\n this._p0[0],\n this._p0[1],\n this._r0,\n this._p1[0],\n this._p1[1],\n this._r1\n );\n }\n\n for (const colorStop of this._colorStops) {\n grad.addColorStop(colorStop[0], colorStop[1]);\n }\n return grad;\n }\n\n getPattern(ctx, owner, inverse, pathType) {\n let pattern;\n if (pathType === PathType.STROKE || pathType === PathType.FILL) {\n const ownerBBox = owner.current.getClippedPathBoundingBox(\n pathType,\n getCurrentTransform(ctx)\n ) || [0, 0, 0, 0];\n // Create a canvas that is only as big as the current path. This doesn't\n // allow us to cache the pattern, but it generally creates much smaller\n // canvases and saves memory use. See bug 1722807 for an example.\n const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;\n const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;\n\n const tmpCanvas = owner.cachedCanvases.getCanvas(\n \"pattern\",\n width,\n height\n );\n\n const tmpCtx = tmpCanvas.context;\n tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);\n tmpCtx.beginPath();\n tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);\n // Non shading fill patterns are positioned relative to the base transform\n // (usually the page's initial transform), but we may have created a\n // smaller canvas based on the path, so we must account for the shift.\n tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);\n inverse = Util.transform(inverse, [\n 1,\n 0,\n 0,\n 1,\n ownerBBox[0],\n ownerBBox[1],\n ]);\n\n tmpCtx.transform(...owner.baseTransform);\n if (this.matrix) {\n tmpCtx.transform(...this.matrix);\n }\n applyBoundingBox(tmpCtx, this._bbox);\n\n tmpCtx.fillStyle = this._createGradient(tmpCtx);\n tmpCtx.fill();\n\n pattern = ctx.createPattern(tmpCanvas.canvas, \"no-repeat\");\n const domMatrix = new DOMMatrix(inverse);\n pattern.setTransform(domMatrix);\n } else {\n // Shading fills are applied relative to the current matrix which is also\n // how canvas gradients work, so there's no need to do anything special\n // here.\n applyBoundingBox(ctx, this._bbox);\n pattern = this._createGradient(ctx);\n }\n return pattern;\n }\n}\n\nfunction drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {\n // Very basic Gouraud-shaded triangle rasterization algorithm.\n const coords = context.coords,\n colors = context.colors;\n const bytes = data.data,\n rowSize = data.width * 4;\n let tmp;\n if (coords[p1 + 1] > coords[p2 + 1]) {\n tmp = p1;\n p1 = p2;\n p2 = tmp;\n tmp = c1;\n c1 = c2;\n c2 = tmp;\n }\n if (coords[p2 + 1] > coords[p3 + 1]) {\n tmp = p2;\n p2 = p3;\n p3 = tmp;\n tmp = c2;\n c2 = c3;\n c3 = tmp;\n }\n if (coords[p1 + 1] > coords[p2 + 1]) {\n tmp = p1;\n p1 = p2;\n p2 = tmp;\n tmp = c1;\n c1 = c2;\n c2 = tmp;\n }\n const x1 = (coords[p1] + context.offsetX) * context.scaleX;\n const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;\n const x2 = (coords[p2] + context.offsetX) * context.scaleX;\n const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;\n const x3 = (coords[p3] + context.offsetX) * context.scaleX;\n const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;\n if (y1 >= y3) {\n return;\n }\n const c1r = colors[c1],\n c1g = colors[c1 + 1],\n c1b = colors[c1 + 2];\n const c2r = colors[c2],\n c2g = colors[c2 + 1],\n c2b = colors[c2 + 2];\n const c3r = colors[c3],\n c3g = colors[c3 + 1],\n c3b = colors[c3 + 2];\n\n const minY = Math.round(y1),\n maxY = Math.round(y3);\n let xa, car, cag, cab;\n let xb, cbr, cbg, cbb;\n for (let y = minY; y <= maxY; y++) {\n if (y < y2) {\n const k = y < y1 ? 0 : (y1 - y) / (y1 - y2);\n xa = x1 - (x1 - x2) * k;\n car = c1r - (c1r - c2r) * k;\n cag = c1g - (c1g - c2g) * k;\n cab = c1b - (c1b - c2b) * k;\n } else {\n let k;\n if (y > y3) {\n k = 1;\n } else if (y2 === y3) {\n k = 0;\n } else {\n k = (y2 - y) / (y2 - y3);\n }\n xa = x2 - (x2 - x3) * k;\n car = c2r - (c2r - c3r) * k;\n cag = c2g - (c2g - c3g) * k;\n cab = c2b - (c2b - c3b) * k;\n }\n\n let k;\n if (y < y1) {\n k = 0;\n } else if (y > y3) {\n k = 1;\n } else {\n k = (y1 - y) / (y1 - y3);\n }\n xb = x1 - (x1 - x3) * k;\n cbr = c1r - (c1r - c3r) * k;\n cbg = c1g - (c1g - c3g) * k;\n cbb = c1b - (c1b - c3b) * k;\n const x1_ = Math.round(Math.min(xa, xb));\n const x2_ = Math.round(Math.max(xa, xb));\n let j = rowSize * y + x1_ * 4;\n for (let x = x1_; x <= x2_; x++) {\n k = (xa - x) / (xa - xb);\n if (k < 0) {\n k = 0;\n } else if (k > 1) {\n k = 1;\n }\n bytes[j++] = (car - (car - cbr) * k) | 0;\n bytes[j++] = (cag - (cag - cbg) * k) | 0;\n bytes[j++] = (cab - (cab - cbb) * k) | 0;\n bytes[j++] = 255;\n }\n }\n}\n\nfunction drawFigure(data, figure, context) {\n const ps = figure.coords;\n const cs = figure.colors;\n let i, ii;\n switch (figure.type) {\n case \"lattice\":\n const verticesPerRow = figure.verticesPerRow;\n const rows = Math.floor(ps.length / verticesPerRow) - 1;\n const cols = verticesPerRow - 1;\n for (i = 0; i < rows; i++) {\n let q = i * verticesPerRow;\n for (let j = 0; j < cols; j++, q++) {\n drawTriangle(\n data,\n context,\n ps[q],\n ps[q + 1],\n ps[q + verticesPerRow],\n cs[q],\n cs[q + 1],\n cs[q + verticesPerRow]\n );\n drawTriangle(\n data,\n context,\n ps[q + verticesPerRow + 1],\n ps[q + 1],\n ps[q + verticesPerRow],\n cs[q + verticesPerRow + 1],\n cs[q + 1],\n cs[q + verticesPerRow]\n );\n }\n }\n break;\n case \"triangles\":\n for (i = 0, ii = ps.length; i < ii; i += 3) {\n drawTriangle(\n data,\n context,\n ps[i],\n ps[i + 1],\n ps[i + 2],\n cs[i],\n cs[i + 1],\n cs[i + 2]\n );\n }\n break;\n default:\n throw new Error(\"illegal figure\");\n }\n}\n\nclass MeshShadingPattern extends BaseShadingPattern {\n constructor(IR) {\n super();\n this._coords = IR[2];\n this._colors = IR[3];\n this._figures = IR[4];\n this._bounds = IR[5];\n this._bbox = IR[7];\n this._background = IR[8];\n this.matrix = null;\n }\n\n _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {\n // we will increase scale on some weird factor to let antialiasing take\n // care of \"rough\" edges\n const EXPECTED_SCALE = 1.1;\n // MAX_PATTERN_SIZE is used to avoid OOM situation.\n const MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough\n // We need to keep transparent border around our pattern for fill():\n // createPattern with 'no-repeat' will bleed edges across entire area.\n const BORDER_SIZE = 2;\n\n const offsetX = Math.floor(this._bounds[0]);\n const offsetY = Math.floor(this._bounds[1]);\n const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;\n const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;\n\n const width = Math.min(\n Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)),\n MAX_PATTERN_SIZE\n );\n const height = Math.min(\n Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)),\n MAX_PATTERN_SIZE\n );\n const scaleX = boundsWidth / width;\n const scaleY = boundsHeight / height;\n\n const context = {\n coords: this._coords,\n colors: this._colors,\n offsetX: -offsetX,\n offsetY: -offsetY,\n scaleX: 1 / scaleX,\n scaleY: 1 / scaleY,\n };\n\n const paddedWidth = width + BORDER_SIZE * 2;\n const paddedHeight = height + BORDER_SIZE * 2;\n\n const tmpCanvas = cachedCanvases.getCanvas(\n \"mesh\",\n paddedWidth,\n paddedHeight\n );\n const tmpCtx = tmpCanvas.context;\n\n const data = tmpCtx.createImageData(width, height);\n if (backgroundColor) {\n const bytes = data.data;\n for (let i = 0, ii = bytes.length; i < ii; i += 4) {\n bytes[i] = backgroundColor[0];\n bytes[i + 1] = backgroundColor[1];\n bytes[i + 2] = backgroundColor[2];\n bytes[i + 3] = 255;\n }\n }\n for (const figure of this._figures) {\n drawFigure(data, figure, context);\n }\n tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);\n const canvas = tmpCanvas.canvas;\n\n return {\n canvas,\n offsetX: offsetX - BORDER_SIZE * scaleX,\n offsetY: offsetY - BORDER_SIZE * scaleY,\n scaleX,\n scaleY,\n };\n }\n\n getPattern(ctx, owner, inverse, pathType) {\n applyBoundingBox(ctx, this._bbox);\n let scale;\n if (pathType === PathType.SHADING) {\n scale = Util.singularValueDecompose2dScale(getCurrentTransform(ctx));\n } else {\n // Obtain scale from matrix and current transformation matrix.\n scale = Util.singularValueDecompose2dScale(owner.baseTransform);\n if (this.matrix) {\n const matrixScale = Util.singularValueDecompose2dScale(this.matrix);\n scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];\n }\n }\n\n // Rasterizing on the main thread since sending/queue large canvases\n // might cause OOM.\n const temporaryPatternCanvas = this._createMeshCanvas(\n scale,\n pathType === PathType.SHADING ? null : this._background,\n owner.cachedCanvases\n );\n\n if (pathType !== PathType.SHADING) {\n ctx.setTransform(...owner.baseTransform);\n if (this.matrix) {\n ctx.transform(...this.matrix);\n }\n }\n\n ctx.translate(\n temporaryPatternCanvas.offsetX,\n temporaryPatternCanvas.offsetY\n );\n ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);\n\n return ctx.createPattern(temporaryPatternCanvas.canvas, \"no-repeat\");\n }\n}\n\nclass DummyShadingPattern extends BaseShadingPattern {\n getPattern() {\n return \"hotpink\";\n }\n}\n\nfunction getShadingPattern(IR) {\n switch (IR[0]) {\n case \"RadialAxial\":\n return new RadialAxialShadingPattern(IR);\n case \"Mesh\":\n return new MeshShadingPattern(IR);\n case \"Dummy\":\n return new DummyShadingPattern();\n }\n throw new Error(`Unknown IR type: ${IR[0]}`);\n}\n\nconst PaintType = {\n COLORED: 1,\n UNCOLORED: 2,\n};\n\nclass TilingPattern {\n // 10in @ 300dpi shall be enough.\n static MAX_PATTERN_SIZE = 3000;\n\n constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {\n this.operatorList = IR[2];\n this.matrix = IR[3];\n this.bbox = IR[4];\n this.xstep = IR[5];\n this.ystep = IR[6];\n this.paintType = IR[7];\n this.tilingType = IR[8];\n this.color = color;\n this.ctx = ctx;\n this.canvasGraphicsFactory = canvasGraphicsFactory;\n this.baseTransform = baseTransform;\n }\n\n createPatternCanvas(owner) {\n const {\n bbox,\n operatorList,\n paintType,\n tilingType,\n color,\n canvasGraphicsFactory,\n } = this;\n let { xstep, ystep } = this;\n xstep = Math.abs(xstep);\n ystep = Math.abs(ystep);\n\n info(\"TilingType: \" + tilingType);\n\n // A tiling pattern as defined by PDF spec 8.7.2 is a cell whose size is\n // described by bbox, and may repeat regularly by shifting the cell by\n // xstep and ystep.\n // Because the HTML5 canvas API does not support pattern repetition with\n // gaps in between, we use the xstep/ystep instead of the bbox's size.\n //\n // This has the following consequences (similarly for ystep):\n //\n // - If xstep is the same as bbox, then there is no observable difference.\n //\n // - If xstep is larger than bbox, then the pattern canvas is partially\n // empty: the area bounded by bbox is painted, the outside area is void.\n //\n // - If xstep is smaller than bbox, then the pixels between xstep and the\n // bbox boundary will be missing. This is INCORRECT behavior.\n // \"Figures on adjacent tiles should not overlap\" (PDF spec 8.7.3.1),\n // but overlapping cells without common pixels are still valid.\n\n const x0 = bbox[0],\n y0 = bbox[1],\n x1 = bbox[2],\n y1 = bbox[3];\n const width = x1 - x0;\n const height = y1 - y0;\n\n // Obtain scale from matrix and current transformation matrix.\n const matrixScale = Util.singularValueDecompose2dScale(this.matrix);\n const curMatrixScale = Util.singularValueDecompose2dScale(\n this.baseTransform\n );\n const combinedScaleX = matrixScale[0] * curMatrixScale[0];\n const combinedScaleY = matrixScale[1] * curMatrixScale[1];\n\n let canvasWidth = width,\n canvasHeight = height,\n redrawHorizontally = false,\n redrawVertically = false;\n\n const xScaledStep = Math.ceil(xstep * combinedScaleX);\n const yScaledStep = Math.ceil(ystep * combinedScaleY);\n const xScaledWidth = Math.ceil(width * combinedScaleX);\n const yScaledHeight = Math.ceil(height * combinedScaleY);\n\n if (xScaledStep >= xScaledWidth) {\n canvasWidth = xstep;\n } else {\n redrawHorizontally = true;\n }\n if (yScaledStep >= yScaledHeight) {\n canvasHeight = ystep;\n } else {\n redrawVertically = true;\n }\n\n // Use width and height values that are as close as possible to the end\n // result when the pattern is used. Too low value makes the pattern look\n // blurry. Too large value makes it look too crispy.\n const dimx = this.getSizeAndScale(\n canvasWidth,\n this.ctx.canvas.width,\n combinedScaleX\n );\n const dimy = this.getSizeAndScale(\n canvasHeight,\n this.ctx.canvas.height,\n combinedScaleY\n );\n\n const tmpCanvas = owner.cachedCanvases.getCanvas(\n \"pattern\",\n dimx.size,\n dimy.size\n );\n const tmpCtx = tmpCanvas.context;\n const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);\n graphics.groupLevel = owner.groupLevel;\n\n this.setFillAndStrokeStyleToContext(graphics, paintType, color);\n\n tmpCtx.translate(-dimx.scale * x0, -dimy.scale * y0);\n graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);\n\n // To match CanvasGraphics beginDrawing we must save the context here or\n // else we end up with unbalanced save/restores.\n tmpCtx.save();\n\n this.clipBbox(graphics, x0, y0, x1, y1);\n\n graphics.baseTransform = getCurrentTransform(graphics.ctx);\n\n graphics.executeOperatorList(operatorList);\n\n graphics.endDrawing();\n\n tmpCtx.restore();\n\n if (redrawHorizontally || redrawVertically) {\n // The tile is overlapping itself, so we create a new tile with\n // dimensions xstep * ystep.\n // Then we draw the overlapping parts of the original tile on the new\n // tile.\n // Just as a side note, the code here works correctly even if we don't\n // have to redraw the tile horizontally or vertically. In that case, the\n // original tile is drawn on the new tile only once, but it's useless.\n const image = tmpCanvas.canvas;\n if (redrawHorizontally) {\n canvasWidth = xstep;\n }\n if (redrawVertically) {\n canvasHeight = ystep;\n }\n\n const dimx2 = this.getSizeAndScale(\n canvasWidth,\n this.ctx.canvas.width,\n combinedScaleX\n );\n const dimy2 = this.getSizeAndScale(\n canvasHeight,\n this.ctx.canvas.height,\n combinedScaleY\n );\n\n const xSize = dimx2.size;\n const ySize = dimy2.size;\n const tmpCanvas2 = owner.cachedCanvases.getCanvas(\n \"pattern-workaround\",\n xSize,\n ySize\n );\n const tmpCtx2 = tmpCanvas2.context;\n const ii = redrawHorizontally ? Math.floor(width / xstep) : 0;\n const jj = redrawVertically ? Math.floor(height / ystep) : 0;\n\n // Draw the overlapping parts of the original tile on the new tile.\n for (let i = 0; i <= ii; i++) {\n for (let j = 0; j <= jj; j++) {\n tmpCtx2.drawImage(\n image,\n xSize * i,\n ySize * j,\n xSize,\n ySize,\n 0,\n 0,\n xSize,\n ySize\n );\n }\n }\n return {\n canvas: tmpCanvas2.canvas,\n scaleX: dimx2.scale,\n scaleY: dimy2.scale,\n offsetX: x0,\n offsetY: y0,\n };\n }\n\n return {\n canvas: tmpCanvas.canvas,\n scaleX: dimx.scale,\n scaleY: dimy.scale,\n offsetX: x0,\n offsetY: y0,\n };\n }\n\n getSizeAndScale(step, realOutputSize, scale) {\n // MAX_PATTERN_SIZE is used to avoid OOM situation.\n // Use the destination canvas's size if it is bigger than the hard-coded\n // limit of MAX_PATTERN_SIZE to avoid clipping patterns that cover the\n // whole canvas.\n const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);\n let size = Math.ceil(step * scale);\n if (size >= maxSize) {\n size = maxSize;\n } else {\n scale = size / step;\n }\n return { scale, size };\n }\n\n clipBbox(graphics, x0, y0, x1, y1) {\n const bboxWidth = x1 - x0;\n const bboxHeight = y1 - y0;\n graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);\n graphics.current.updateRectMinMax(getCurrentTransform(graphics.ctx), [\n x0,\n y0,\n x1,\n y1,\n ]);\n graphics.clip();\n graphics.endPath();\n }\n\n setFillAndStrokeStyleToContext(graphics, paintType, color) {\n const context = graphics.ctx,\n current = graphics.current;\n switch (paintType) {\n case PaintType.COLORED:\n const ctx = this.ctx;\n context.fillStyle = ctx.fillStyle;\n context.strokeStyle = ctx.strokeStyle;\n current.fillColor = ctx.fillStyle;\n current.strokeColor = ctx.strokeStyle;\n break;\n case PaintType.UNCOLORED:\n const cssColor = Util.makeHexColor(color[0], color[1], color[2]);\n context.fillStyle = cssColor;\n context.strokeStyle = cssColor;\n // Set color needed by image masks (fixes issues 3226 and 8741).\n current.fillColor = cssColor;\n current.strokeColor = cssColor;\n break;\n default:\n throw new FormatError(`Unsupported paint type: ${paintType}`);\n }\n }\n\n getPattern(ctx, owner, inverse, pathType) {\n // PDF spec 8.7.2 NOTE 1: pattern's matrix is relative to initial matrix.\n let matrix = inverse;\n if (pathType !== PathType.SHADING) {\n matrix = Util.transform(matrix, owner.baseTransform);\n if (this.matrix) {\n matrix = Util.transform(matrix, this.matrix);\n }\n }\n\n const temporaryPatternCanvas = this.createPatternCanvas(owner);\n\n let domMatrix = new DOMMatrix(matrix);\n // Rescale and so that the ctx.createPattern call generates a pattern with\n // the desired size.\n domMatrix = domMatrix.translate(\n temporaryPatternCanvas.offsetX,\n temporaryPatternCanvas.offsetY\n );\n domMatrix = domMatrix.scale(\n 1 / temporaryPatternCanvas.scaleX,\n 1 / temporaryPatternCanvas.scaleY\n );\n\n const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, \"repeat\");\n pattern.setTransform(domMatrix);\n\n return pattern;\n }\n}\n\nexport { getShadingPattern, PathType, TilingPattern };\n","/* Copyright 2022 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FeatureTest, ImageKind } from \"./util.js\";\n\nfunction convertToRGBA(params) {\n switch (params.kind) {\n case ImageKind.GRAYSCALE_1BPP:\n return convertBlackAndWhiteToRGBA(params);\n case ImageKind.RGB_24BPP:\n return convertRGBToRGBA(params);\n }\n\n return null;\n}\n\nfunction convertBlackAndWhiteToRGBA({\n src,\n srcPos = 0,\n dest,\n width,\n height,\n nonBlackColor = 0xffffffff,\n inverseDecode = false,\n}) {\n const black = FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;\n const [zeroMapping, oneMapping] = inverseDecode\n ? [nonBlackColor, black]\n : [black, nonBlackColor];\n const widthInSource = width >> 3;\n const widthRemainder = width & 7;\n const srcLength = src.length;\n dest = new Uint32Array(dest.buffer);\n let destPos = 0;\n\n for (let i = 0; i < height; i++) {\n for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {\n const elem = srcPos < srcLength ? src[srcPos] : 255;\n dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;\n dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;\n dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;\n dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;\n dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;\n dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;\n dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;\n dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;\n }\n if (widthRemainder === 0) {\n continue;\n }\n const elem = srcPos < srcLength ? src[srcPos++] : 255;\n for (let j = 0; j < widthRemainder; j++) {\n dest[destPos++] = elem & (1 << (7 - j)) ? oneMapping : zeroMapping;\n }\n }\n return { srcPos, destPos };\n}\n\nfunction convertRGBToRGBA({\n src,\n srcPos = 0,\n dest,\n destPos = 0,\n width,\n height,\n}) {\n let i = 0;\n const len = width * height * 3;\n const len32 = len >> 2;\n const src32 = new Uint32Array(src.buffer, srcPos, len32);\n\n if (FeatureTest.isLittleEndian) {\n // It's a way faster to do the shuffle manually instead of working\n // component by component with some Uint8 arrays.\n for (; i < len32 - 2; i += 3, destPos += 4) {\n const s1 = src32[i]; // R2B1G1R1\n const s2 = src32[i + 1]; // G3R3B2G2\n const s3 = src32[i + 2]; // B4G4R4B3\n\n dest[destPos] = s1 | 0xff000000;\n dest[destPos + 1] = (s1 >>> 24) | (s2 << 8) | 0xff000000;\n dest[destPos + 2] = (s2 >>> 16) | (s3 << 16) | 0xff000000;\n dest[destPos + 3] = (s3 >>> 8) | 0xff000000;\n }\n\n for (let j = i * 4, jj = srcPos + len; j < jj; j += 3) {\n dest[destPos++] =\n src[j] | (src[j + 1] << 8) | (src[j + 2] << 16) | 0xff000000;\n }\n } else {\n for (; i < len32 - 2; i += 3, destPos += 4) {\n const s1 = src32[i]; // R1G1B1R2\n const s2 = src32[i + 1]; // G2B2R3G3\n const s3 = src32[i + 2]; // B3R4G4B4\n\n dest[destPos] = s1 | 0xff;\n dest[destPos + 1] = (s1 << 24) | (s2 >>> 8) | 0xff;\n dest[destPos + 2] = (s2 << 16) | (s3 >>> 16) | 0xff;\n dest[destPos + 3] = (s3 << 8) | 0xff;\n }\n\n for (let j = i * 4, jj = srcPos + len; j < jj; j += 3) {\n dest[destPos++] =\n (src[j] << 24) | (src[j + 1] << 16) | (src[j + 2] << 8) | 0xff;\n }\n }\n\n return { srcPos: srcPos + len, destPos };\n}\n\nfunction grayToRGBA(src, dest) {\n if (FeatureTest.isLittleEndian) {\n for (let i = 0, ii = src.length; i < ii; i++) {\n dest[i] = (src[i] * 0x10101) | 0xff000000;\n }\n } else {\n for (let i = 0, ii = src.length; i < ii; i++) {\n dest[i] = (src[i] * 0x1010100) | 0x000000ff;\n }\n }\n}\n\nexport { convertBlackAndWhiteToRGBA, convertToRGBA, grayToRGBA };\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FeatureTest,\n FONT_IDENTITY_MATRIX,\n IDENTITY_MATRIX,\n ImageKind,\n info,\n isNodeJS,\n OPS,\n shadow,\n TextRenderingMode,\n unreachable,\n Util,\n warn,\n} from \"../shared/util.js\";\nimport {\n getCurrentTransform,\n getCurrentTransformInverse,\n PixelsPerInch,\n} from \"./display_utils.js\";\nimport {\n getShadingPattern,\n PathType,\n TilingPattern,\n} from \"./pattern_helper.js\";\nimport { convertBlackAndWhiteToRGBA } from \"../shared/image_utils.js\";\n\n// contexts store most of the state we need natively.\n// However, PDF needs a bit more state, which we store here.\n// Minimal font size that would be used during canvas fillText operations.\nconst MIN_FONT_SIZE = 16;\n// Maximum font size that would be used during canvas fillText operations.\nconst MAX_FONT_SIZE = 100;\n\n// Defines the time the `executeOperatorList`-method is going to be executing\n// before it stops and schedules a continue of execution.\nconst EXECUTION_TIME = 15; // ms\n// Defines the number of steps before checking the execution time.\nconst EXECUTION_STEPS = 10;\n\n// To disable Type3 compilation, set the value to `-1`.\nconst MAX_SIZE_TO_COMPILE = 1000;\n\nconst FULL_CHUNK_HEIGHT = 16;\n\n/**\n * Overrides certain methods on a 2d ctx so that when they are called they\n * will also call the same method on the destCtx. The methods that are\n * overridden are all the transformation state modifiers, path creation, and\n * save/restore. We only forward these specific methods because they are the\n * only state modifiers that we cannot copy over when we switch contexts.\n *\n * To remove mirroring call `ctx._removeMirroring()`.\n *\n * @param {Object} ctx - The 2d canvas context that will duplicate its calls on\n * the destCtx.\n * @param {Object} destCtx - The 2d canvas context that will receive the\n * forwarded calls.\n */\nfunction mirrorContextOperations(ctx, destCtx) {\n if (ctx._removeMirroring) {\n throw new Error(\"Context is already forwarding operations.\");\n }\n ctx.__originalSave = ctx.save;\n ctx.__originalRestore = ctx.restore;\n ctx.__originalRotate = ctx.rotate;\n ctx.__originalScale = ctx.scale;\n ctx.__originalTranslate = ctx.translate;\n ctx.__originalTransform = ctx.transform;\n ctx.__originalSetTransform = ctx.setTransform;\n ctx.__originalResetTransform = ctx.resetTransform;\n ctx.__originalClip = ctx.clip;\n ctx.__originalMoveTo = ctx.moveTo;\n ctx.__originalLineTo = ctx.lineTo;\n ctx.__originalBezierCurveTo = ctx.bezierCurveTo;\n ctx.__originalRect = ctx.rect;\n ctx.__originalClosePath = ctx.closePath;\n ctx.__originalBeginPath = ctx.beginPath;\n\n ctx._removeMirroring = () => {\n ctx.save = ctx.__originalSave;\n ctx.restore = ctx.__originalRestore;\n ctx.rotate = ctx.__originalRotate;\n ctx.scale = ctx.__originalScale;\n ctx.translate = ctx.__originalTranslate;\n ctx.transform = ctx.__originalTransform;\n ctx.setTransform = ctx.__originalSetTransform;\n ctx.resetTransform = ctx.__originalResetTransform;\n\n ctx.clip = ctx.__originalClip;\n ctx.moveTo = ctx.__originalMoveTo;\n ctx.lineTo = ctx.__originalLineTo;\n ctx.bezierCurveTo = ctx.__originalBezierCurveTo;\n ctx.rect = ctx.__originalRect;\n ctx.closePath = ctx.__originalClosePath;\n ctx.beginPath = ctx.__originalBeginPath;\n delete ctx._removeMirroring;\n };\n\n ctx.save = function ctxSave() {\n destCtx.save();\n this.__originalSave();\n };\n\n ctx.restore = function ctxRestore() {\n destCtx.restore();\n this.__originalRestore();\n };\n\n ctx.translate = function ctxTranslate(x, y) {\n destCtx.translate(x, y);\n this.__originalTranslate(x, y);\n };\n\n ctx.scale = function ctxScale(x, y) {\n destCtx.scale(x, y);\n this.__originalScale(x, y);\n };\n\n ctx.transform = function ctxTransform(a, b, c, d, e, f) {\n destCtx.transform(a, b, c, d, e, f);\n this.__originalTransform(a, b, c, d, e, f);\n };\n\n ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {\n destCtx.setTransform(a, b, c, d, e, f);\n this.__originalSetTransform(a, b, c, d, e, f);\n };\n\n ctx.resetTransform = function ctxResetTransform() {\n destCtx.resetTransform();\n this.__originalResetTransform();\n };\n\n ctx.rotate = function ctxRotate(angle) {\n destCtx.rotate(angle);\n this.__originalRotate(angle);\n };\n\n ctx.clip = function ctxRotate(rule) {\n destCtx.clip(rule);\n this.__originalClip(rule);\n };\n\n ctx.moveTo = function (x, y) {\n destCtx.moveTo(x, y);\n this.__originalMoveTo(x, y);\n };\n\n ctx.lineTo = function (x, y) {\n destCtx.lineTo(x, y);\n this.__originalLineTo(x, y);\n };\n\n ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {\n destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);\n this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);\n };\n\n ctx.rect = function (x, y, width, height) {\n destCtx.rect(x, y, width, height);\n this.__originalRect(x, y, width, height);\n };\n\n ctx.closePath = function () {\n destCtx.closePath();\n this.__originalClosePath();\n };\n\n ctx.beginPath = function () {\n destCtx.beginPath();\n this.__originalBeginPath();\n };\n}\n\nclass CachedCanvases {\n constructor(canvasFactory) {\n this.canvasFactory = canvasFactory;\n this.cache = Object.create(null);\n }\n\n getCanvas(id, width, height) {\n let canvasEntry;\n if (this.cache[id] !== undefined) {\n canvasEntry = this.cache[id];\n this.canvasFactory.reset(canvasEntry, width, height);\n } else {\n canvasEntry = this.canvasFactory.create(width, height);\n this.cache[id] = canvasEntry;\n }\n return canvasEntry;\n }\n\n delete(id) {\n delete this.cache[id];\n }\n\n clear() {\n for (const id in this.cache) {\n const canvasEntry = this.cache[id];\n this.canvasFactory.destroy(canvasEntry);\n delete this.cache[id];\n }\n }\n}\n\nfunction drawImageAtIntegerCoords(\n ctx,\n srcImg,\n srcX,\n srcY,\n srcW,\n srcH,\n destX,\n destY,\n destW,\n destH\n) {\n const [a, b, c, d, tx, ty] = getCurrentTransform(ctx);\n if (b === 0 && c === 0) {\n // top-left corner is at (X, Y) and\n // bottom-right one is at (X + width, Y + height).\n\n // If leftX is 4.321 then it's rounded to 4.\n // If width is 10.432 then it's rounded to 11 because\n // rightX = leftX + width = 14.753 which is rounded to 15\n // so after rounding the total width is 11 (15 - 4).\n // It's why we can't just floor/ceil uniformly, it just depends\n // on the values we've.\n\n const tlX = destX * a + tx;\n const rTlX = Math.round(tlX);\n const tlY = destY * d + ty;\n const rTlY = Math.round(tlY);\n const brX = (destX + destW) * a + tx;\n\n // Some pdf contains images with 1x1 images so in case of 0-width after\n // scaling we must fallback on 1 to be sure there is something.\n const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;\n const brY = (destY + destH) * d + ty;\n const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;\n\n // We must apply a transformation in order to apply it on the image itself.\n // For example if a == 1 && d == -1, it means that the image itself is\n // mirrored w.r.t. the x-axis.\n ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);\n ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);\n ctx.setTransform(a, b, c, d, tx, ty);\n\n return [rWidth, rHeight];\n }\n\n if (a === 0 && d === 0) {\n // This path is taken in issue9462.pdf (page 3).\n const tlX = destY * c + tx;\n const rTlX = Math.round(tlX);\n const tlY = destX * b + ty;\n const rTlY = Math.round(tlY);\n const brX = (destY + destH) * c + tx;\n const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;\n const brY = (destX + destW) * b + ty;\n const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;\n\n ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);\n ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);\n ctx.setTransform(a, b, c, d, tx, ty);\n\n return [rHeight, rWidth];\n }\n\n // Not a scale matrix so let the render handle the case without rounding.\n ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);\n\n const scaleX = Math.hypot(a, b);\n const scaleY = Math.hypot(c, d);\n return [scaleX * destW, scaleY * destH];\n}\n\nfunction compileType3Glyph(imgData) {\n const { width, height } = imgData;\n if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {\n return null;\n }\n\n const POINT_TO_PROCESS_LIMIT = 1000;\n const POINT_TYPES = new Uint8Array([\n 0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0,\n ]);\n\n const width1 = width + 1;\n let points = new Uint8Array(width1 * (height + 1));\n let i, j, j0;\n\n // decodes bit-packed mask data\n const lineSize = (width + 7) & ~7;\n let data = new Uint8Array(lineSize * height),\n pos = 0;\n for (const elem of imgData.data) {\n let mask = 128;\n while (mask > 0) {\n data[pos++] = elem & mask ? 0 : 255;\n mask >>= 1;\n }\n }\n\n // finding interesting points: every point is located between mask pixels,\n // so there will be points of the (width + 1)x(height + 1) grid. Every point\n // will have flags assigned based on neighboring mask pixels:\n // 4 | 8\n // --P--\n // 2 | 1\n // We are interested only in points with the flags:\n // - outside corners: 1, 2, 4, 8;\n // - inside corners: 7, 11, 13, 14;\n // - and, intersections: 5, 10.\n let count = 0;\n pos = 0;\n if (data[pos] !== 0) {\n points[0] = 1;\n ++count;\n }\n for (j = 1; j < width; j++) {\n if (data[pos] !== data[pos + 1]) {\n points[j] = data[pos] ? 2 : 1;\n ++count;\n }\n pos++;\n }\n if (data[pos] !== 0) {\n points[j] = 2;\n ++count;\n }\n for (i = 1; i < height; i++) {\n pos = i * lineSize;\n j0 = i * width1;\n if (data[pos - lineSize] !== data[pos]) {\n points[j0] = data[pos] ? 1 : 8;\n ++count;\n }\n // 'sum' is the position of the current pixel configuration in the 'TYPES'\n // array (in order 8-1-2-4, so we can use '>>2' to shift the column).\n let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);\n for (j = 1; j < width; j++) {\n sum =\n (sum >> 2) +\n (data[pos + 1] ? 4 : 0) +\n (data[pos - lineSize + 1] ? 8 : 0);\n if (POINT_TYPES[sum]) {\n points[j0 + j] = POINT_TYPES[sum];\n ++count;\n }\n pos++;\n }\n if (data[pos - lineSize] !== data[pos]) {\n points[j0 + j] = data[pos] ? 2 : 4;\n ++count;\n }\n\n if (count > POINT_TO_PROCESS_LIMIT) {\n return null;\n }\n }\n\n pos = lineSize * (height - 1);\n j0 = i * width1;\n if (data[pos] !== 0) {\n points[j0] = 8;\n ++count;\n }\n for (j = 1; j < width; j++) {\n if (data[pos] !== data[pos + 1]) {\n points[j0 + j] = data[pos] ? 4 : 8;\n ++count;\n }\n pos++;\n }\n if (data[pos] !== 0) {\n points[j0 + j] = 4;\n ++count;\n }\n if (count > POINT_TO_PROCESS_LIMIT) {\n return null;\n }\n\n // building outlines\n const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);\n const path = new Path2D();\n\n for (i = 0; count && i <= height; i++) {\n let p = i * width1;\n const end = p + width;\n while (p < end && !points[p]) {\n p++;\n }\n if (p === end) {\n continue;\n }\n path.moveTo(p % width1, i);\n\n const p0 = p;\n let type = points[p];\n do {\n const step = steps[type];\n do {\n p += step;\n } while (!points[p]);\n\n const pp = points[p];\n if (pp !== 5 && pp !== 10) {\n // set new direction\n type = pp;\n // delete mark\n points[p] = 0;\n } else {\n // type is 5 or 10, ie, a crossing\n // set new direction\n type = pp & ((0x33 * type) >> 4);\n // set new type for \"future hit\"\n points[p] &= (type >> 2) | (type << 2);\n }\n path.lineTo(p % width1, (p / width1) | 0);\n\n if (!points[p]) {\n --count;\n }\n } while (p0 !== p);\n --i;\n }\n\n // Immediately release the, potentially large, `Uint8Array`s after parsing.\n data = null;\n points = null;\n\n const drawOutline = function (c) {\n c.save();\n // the path shall be painted in [0..1]x[0..1] space\n c.scale(1 / width, -1 / height);\n c.translate(0, -height);\n c.fill(path);\n c.beginPath();\n c.restore();\n };\n\n return drawOutline;\n}\n\nclass CanvasExtraState {\n constructor(width, height) {\n // Are soft masks and alpha values shapes or opacities?\n this.alphaIsShape = false;\n this.fontSize = 0;\n this.fontSizeScale = 1;\n this.textMatrix = IDENTITY_MATRIX;\n this.textMatrixScale = 1;\n this.fontMatrix = FONT_IDENTITY_MATRIX;\n this.leading = 0;\n // Current point (in user coordinates)\n this.x = 0;\n this.y = 0;\n // Start of text line (in text coordinates)\n this.lineX = 0;\n this.lineY = 0;\n // Character and word spacing\n this.charSpacing = 0;\n this.wordSpacing = 0;\n this.textHScale = 1;\n this.textRenderingMode = TextRenderingMode.FILL;\n this.textRise = 0;\n // Default fore and background colors\n this.fillColor = \"#000000\";\n this.strokeColor = \"#000000\";\n this.patternFill = false;\n this.patternStroke = false;\n // Note: fill alpha applies to all non-stroking operations\n this.fillAlpha = 1;\n this.strokeAlpha = 1;\n this.lineWidth = 1;\n this.activeSMask = null;\n this.transferMaps = \"none\";\n\n this.startNewPathAndClipBox([0, 0, width, height]);\n }\n\n clone() {\n const clone = Object.create(this);\n clone.clipBox = this.clipBox.slice();\n return clone;\n }\n\n setCurrentPoint(x, y) {\n this.x = x;\n this.y = y;\n }\n\n updatePathMinMax(transform, x, y) {\n [x, y] = Util.applyTransform([x, y], transform);\n this.minX = Math.min(this.minX, x);\n this.minY = Math.min(this.minY, y);\n this.maxX = Math.max(this.maxX, x);\n this.maxY = Math.max(this.maxY, y);\n }\n\n updateRectMinMax(transform, rect) {\n const p1 = Util.applyTransform(rect, transform);\n const p2 = Util.applyTransform(rect.slice(2), transform);\n const p3 = Util.applyTransform([rect[0], rect[3]], transform);\n const p4 = Util.applyTransform([rect[2], rect[1]], transform);\n\n this.minX = Math.min(this.minX, p1[0], p2[0], p3[0], p4[0]);\n this.minY = Math.min(this.minY, p1[1], p2[1], p3[1], p4[1]);\n this.maxX = Math.max(this.maxX, p1[0], p2[0], p3[0], p4[0]);\n this.maxY = Math.max(this.maxY, p1[1], p2[1], p3[1], p4[1]);\n }\n\n updateScalingPathMinMax(transform, minMax) {\n Util.scaleMinMax(transform, minMax);\n this.minX = Math.min(this.minX, minMax[0]);\n this.minY = Math.min(this.minY, minMax[1]);\n this.maxX = Math.max(this.maxX, minMax[2]);\n this.maxY = Math.max(this.maxY, minMax[3]);\n }\n\n updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {\n const box = Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax);\n if (minMax) {\n return;\n }\n this.updateRectMinMax(transform, box);\n }\n\n getPathBoundingBox(pathType = PathType.FILL, transform = null) {\n const box = [this.minX, this.minY, this.maxX, this.maxY];\n if (pathType === PathType.STROKE) {\n if (!transform) {\n unreachable(\"Stroke bounding box must include transform.\");\n }\n // Stroked paths can be outside of the path bounding box by 1/2 the line\n // width.\n const scale = Util.singularValueDecompose2dScale(transform);\n const xStrokePad = (scale[0] * this.lineWidth) / 2;\n const yStrokePad = (scale[1] * this.lineWidth) / 2;\n box[0] -= xStrokePad;\n box[1] -= yStrokePad;\n box[2] += xStrokePad;\n box[3] += yStrokePad;\n }\n return box;\n }\n\n updateClipFromPath() {\n const intersect = Util.intersect(this.clipBox, this.getPathBoundingBox());\n this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);\n }\n\n isEmptyClip() {\n return this.minX === Infinity;\n }\n\n startNewPathAndClipBox(box) {\n this.clipBox = box;\n this.minX = Infinity;\n this.minY = Infinity;\n this.maxX = 0;\n this.maxY = 0;\n }\n\n getClippedPathBoundingBox(pathType = PathType.FILL, transform = null) {\n return Util.intersect(\n this.clipBox,\n this.getPathBoundingBox(pathType, transform)\n );\n }\n}\n\nfunction putBinaryImageData(ctx, imgData) {\n if (imgData instanceof ImageData) {\n ctx.putImageData(imgData, 0, 0);\n return;\n }\n\n // Put the image data to the canvas in chunks, rather than putting the\n // whole image at once. This saves JS memory, because the ImageData object\n // is smaller. It also possibly saves C++ memory within the implementation\n // of putImageData(). (E.g. in Firefox we make two short-lived copies of\n // the data passed to putImageData()). |n| shouldn't be too small, however,\n // because too many putImageData() calls will slow things down.\n //\n // Note: as written, if the last chunk is partial, the putImageData() call\n // will (conceptually) put pixels past the bounds of the canvas. But\n // that's ok; any such pixels are ignored.\n\n const height = imgData.height,\n width = imgData.width;\n const partialChunkHeight = height % FULL_CHUNK_HEIGHT;\n const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;\n const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;\n\n const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);\n let srcPos = 0,\n destPos;\n const src = imgData.data;\n const dest = chunkImgData.data;\n let i, j, thisChunkHeight, elemsInThisChunk;\n\n // There are multiple forms in which the pixel data can be passed, and\n // imgData.kind tells us which one this is.\n if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {\n // Grayscale, 1 bit per pixel (i.e. black-and-white).\n const srcLength = src.byteLength;\n const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);\n const dest32DataLength = dest32.length;\n const fullSrcDiff = (width + 7) >> 3;\n const white = 0xffffffff;\n const black = FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;\n\n for (i = 0; i < totalChunks; i++) {\n thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;\n destPos = 0;\n for (j = 0; j < thisChunkHeight; j++) {\n const srcDiff = srcLength - srcPos;\n let k = 0;\n const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;\n const kEndUnrolled = kEnd & ~7;\n let mask = 0;\n let srcByte = 0;\n for (; k < kEndUnrolled; k += 8) {\n srcByte = src[srcPos++];\n dest32[destPos++] = srcByte & 128 ? white : black;\n dest32[destPos++] = srcByte & 64 ? white : black;\n dest32[destPos++] = srcByte & 32 ? white : black;\n dest32[destPos++] = srcByte & 16 ? white : black;\n dest32[destPos++] = srcByte & 8 ? white : black;\n dest32[destPos++] = srcByte & 4 ? white : black;\n dest32[destPos++] = srcByte & 2 ? white : black;\n dest32[destPos++] = srcByte & 1 ? white : black;\n }\n for (; k < kEnd; k++) {\n if (mask === 0) {\n srcByte = src[srcPos++];\n mask = 128;\n }\n\n dest32[destPos++] = srcByte & mask ? white : black;\n mask >>= 1;\n }\n }\n // We ran out of input. Make all remaining pixels transparent.\n while (destPos < dest32DataLength) {\n dest32[destPos++] = 0;\n }\n\n ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);\n }\n } else if (imgData.kind === ImageKind.RGBA_32BPP) {\n // RGBA, 32-bits per pixel.\n j = 0;\n elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;\n for (i = 0; i < fullChunks; i++) {\n dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));\n srcPos += elemsInThisChunk;\n\n ctx.putImageData(chunkImgData, 0, j);\n j += FULL_CHUNK_HEIGHT;\n }\n if (i < totalChunks) {\n elemsInThisChunk = width * partialChunkHeight * 4;\n dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));\n\n ctx.putImageData(chunkImgData, 0, j);\n }\n } else if (imgData.kind === ImageKind.RGB_24BPP) {\n // RGB, 24-bits per pixel.\n thisChunkHeight = FULL_CHUNK_HEIGHT;\n elemsInThisChunk = width * thisChunkHeight;\n for (i = 0; i < totalChunks; i++) {\n if (i >= fullChunks) {\n thisChunkHeight = partialChunkHeight;\n elemsInThisChunk = width * thisChunkHeight;\n }\n\n destPos = 0;\n for (j = elemsInThisChunk; j--; ) {\n dest[destPos++] = src[srcPos++];\n dest[destPos++] = src[srcPos++];\n dest[destPos++] = src[srcPos++];\n dest[destPos++] = 255;\n }\n\n ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);\n }\n } else {\n throw new Error(`bad image kind: ${imgData.kind}`);\n }\n}\n\nfunction putBinaryImageMask(ctx, imgData) {\n if (imgData.bitmap) {\n // The bitmap has been created in the worker.\n ctx.drawImage(imgData.bitmap, 0, 0);\n return;\n }\n\n // Slow path: OffscreenCanvas isn't available in the worker.\n const height = imgData.height,\n width = imgData.width;\n const partialChunkHeight = height % FULL_CHUNK_HEIGHT;\n const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;\n const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;\n\n const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);\n let srcPos = 0;\n const src = imgData.data;\n const dest = chunkImgData.data;\n\n for (let i = 0; i < totalChunks; i++) {\n const thisChunkHeight =\n i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;\n\n // Expand the mask so it can be used by the canvas. Any required\n // inversion has already been handled.\n\n ({ srcPos } = convertBlackAndWhiteToRGBA({\n src,\n srcPos,\n dest,\n width,\n height: thisChunkHeight,\n nonBlackColor: 0,\n }));\n\n ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);\n }\n}\n\nfunction copyCtxState(sourceCtx, destCtx) {\n const properties = [\n \"strokeStyle\",\n \"fillStyle\",\n \"fillRule\",\n \"globalAlpha\",\n \"lineWidth\",\n \"lineCap\",\n \"lineJoin\",\n \"miterLimit\",\n \"globalCompositeOperation\",\n \"font\",\n \"filter\",\n ];\n for (const property of properties) {\n if (sourceCtx[property] !== undefined) {\n destCtx[property] = sourceCtx[property];\n }\n }\n if (sourceCtx.setLineDash !== undefined) {\n destCtx.setLineDash(sourceCtx.getLineDash());\n destCtx.lineDashOffset = sourceCtx.lineDashOffset;\n }\n}\n\nfunction resetCtxToDefault(ctx) {\n ctx.strokeStyle = ctx.fillStyle = \"#000000\";\n ctx.fillRule = \"nonzero\";\n ctx.globalAlpha = 1;\n ctx.lineWidth = 1;\n ctx.lineCap = \"butt\";\n ctx.lineJoin = \"miter\";\n ctx.miterLimit = 10;\n ctx.globalCompositeOperation = \"source-over\";\n ctx.font = \"10px sans-serif\";\n if (ctx.setLineDash !== undefined) {\n ctx.setLineDash([]);\n ctx.lineDashOffset = 0;\n }\n if (\n (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) ||\n !isNodeJS\n ) {\n const { filter } = ctx;\n if (filter !== \"none\" && filter !== \"\") {\n ctx.filter = \"none\";\n }\n }\n}\n\nfunction getImageSmoothingEnabled(transform, interpolate) {\n // In section 8.9.5.3 of the PDF spec, it's mentioned that the interpolate\n // flag should be used when the image is upscaled.\n // In Firefox, smoothing is always used when downscaling images (bug 1360415).\n\n if (interpolate) {\n return true;\n }\n\n const scale = Util.singularValueDecompose2dScale(transform);\n // Round to a 32bit float so that `<=` check below will pass for numbers that\n // are very close, but not exactly the same 64bit floats.\n scale[0] = Math.fround(scale[0]);\n scale[1] = Math.fround(scale[1]);\n const actualScale = Math.fround(\n (globalThis.devicePixelRatio || 1) * PixelsPerInch.PDF_TO_CSS_UNITS\n );\n return scale[0] <= actualScale && scale[1] <= actualScale;\n}\n\nconst LINE_CAP_STYLES = [\"butt\", \"round\", \"square\"];\nconst LINE_JOIN_STYLES = [\"miter\", \"round\", \"bevel\"];\nconst NORMAL_CLIP = {};\nconst EO_CLIP = {};\n\nclass CanvasGraphics {\n constructor(\n canvasCtx,\n commonObjs,\n objs,\n canvasFactory,\n filterFactory,\n { optionalContentConfig, markedContentStack = null },\n annotationCanvasMap,\n pageColors\n ) {\n this.ctx = canvasCtx;\n this.current = new CanvasExtraState(\n this.ctx.canvas.width,\n this.ctx.canvas.height\n );\n this.stateStack = [];\n this.pendingClip = null;\n this.pendingEOFill = false;\n this.res = null;\n this.xobjs = null;\n this.commonObjs = commonObjs;\n this.objs = objs;\n this.canvasFactory = canvasFactory;\n this.filterFactory = filterFactory;\n this.groupStack = [];\n this.processingType3 = null;\n // Patterns are painted relative to the initial page/form transform, see\n // PDF spec 8.7.2 NOTE 1.\n this.baseTransform = null;\n this.baseTransformStack = [];\n this.groupLevel = 0;\n this.smaskStack = [];\n this.smaskCounter = 0;\n this.tempSMask = null;\n this.suspendedCtx = null;\n this.contentVisible = true;\n this.markedContentStack = markedContentStack || [];\n this.optionalContentConfig = optionalContentConfig;\n this.cachedCanvases = new CachedCanvases(this.canvasFactory);\n this.cachedPatterns = new Map();\n this.annotationCanvasMap = annotationCanvasMap;\n this.viewportScale = 1;\n this.outputScaleX = 1;\n this.outputScaleY = 1;\n this.pageColors = pageColors;\n\n this._cachedScaleForStroking = [-1, 0];\n this._cachedGetSinglePixelWidth = null;\n this._cachedBitmapsMap = new Map();\n }\n\n getObject(data, fallback = null) {\n if (typeof data === \"string\") {\n return data.startsWith(\"g_\")\n ? this.commonObjs.get(data)\n : this.objs.get(data);\n }\n return fallback;\n }\n\n beginDrawing({\n transform,\n viewport,\n transparency = false,\n background = null,\n }) {\n // For pdfs that use blend modes we have to clear the canvas else certain\n // blend modes can look wrong since we'd be blending with a white\n // backdrop. The problem with a transparent backdrop though is we then\n // don't get sub pixel anti aliasing on text, creating temporary\n // transparent canvas when we have blend modes.\n const width = this.ctx.canvas.width;\n const height = this.ctx.canvas.height;\n\n const savedFillStyle = this.ctx.fillStyle;\n this.ctx.fillStyle = background || \"#ffffff\";\n this.ctx.fillRect(0, 0, width, height);\n this.ctx.fillStyle = savedFillStyle;\n\n if (transparency) {\n const transparentCanvas = this.cachedCanvases.getCanvas(\n \"transparent\",\n width,\n height\n );\n this.compositeCtx = this.ctx;\n this.transparentCanvas = transparentCanvas.canvas;\n this.ctx = transparentCanvas.context;\n this.ctx.save();\n // The transform can be applied before rendering, transferring it to\n // the new canvas.\n this.ctx.transform(...getCurrentTransform(this.compositeCtx));\n }\n\n this.ctx.save();\n resetCtxToDefault(this.ctx);\n if (transform) {\n this.ctx.transform(...transform);\n this.outputScaleX = transform[0];\n this.outputScaleY = transform[0];\n }\n this.ctx.transform(...viewport.transform);\n this.viewportScale = viewport.scale;\n\n this.baseTransform = getCurrentTransform(this.ctx);\n }\n\n executeOperatorList(\n operatorList,\n executionStartIdx,\n continueCallback,\n stepper\n ) {\n const argsArray = operatorList.argsArray;\n const fnArray = operatorList.fnArray;\n let i = executionStartIdx || 0;\n const argsArrayLen = argsArray.length;\n\n // Sometimes the OperatorList to execute is empty.\n if (argsArrayLen === i) {\n return i;\n }\n\n const chunkOperations =\n argsArrayLen - i > EXECUTION_STEPS &&\n typeof continueCallback === \"function\";\n const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;\n let steps = 0;\n\n const commonObjs = this.commonObjs;\n const objs = this.objs;\n let fnId;\n\n while (true) {\n if (stepper !== undefined && i === stepper.nextBreakPoint) {\n stepper.breakIt(i, continueCallback);\n return i;\n }\n\n fnId = fnArray[i];\n\n if (fnId !== OPS.dependency) {\n // eslint-disable-next-line prefer-spread\n this[fnId].apply(this, argsArray[i]);\n } else {\n for (const depObjId of argsArray[i]) {\n const objsPool = depObjId.startsWith(\"g_\") ? commonObjs : objs;\n\n // If the promise isn't resolved yet, add the continueCallback\n // to the promise and bail out.\n if (!objsPool.has(depObjId)) {\n objsPool.get(depObjId, continueCallback);\n return i;\n }\n }\n }\n\n i++;\n\n // If the entire operatorList was executed, stop as were done.\n if (i === argsArrayLen) {\n return i;\n }\n\n // If the execution took longer then a certain amount of time and\n // `continueCallback` is specified, interrupt the execution.\n if (chunkOperations && ++steps > EXECUTION_STEPS) {\n if (Date.now() > endTime) {\n continueCallback();\n return i;\n }\n steps = 0;\n }\n\n // If the operatorList isn't executed completely yet OR the execution\n // time was short enough, do another execution round.\n }\n }\n\n #restoreInitialState() {\n // Finishing all opened operations such as SMask group painting.\n while (this.stateStack.length || this.inSMaskMode) {\n this.restore();\n }\n\n this.current.activeSMask = null;\n this.ctx.restore();\n\n if (this.transparentCanvas) {\n this.ctx = this.compositeCtx;\n this.ctx.save();\n this.ctx.setTransform(1, 0, 0, 1, 0, 0); // Avoid apply transform twice\n this.ctx.drawImage(this.transparentCanvas, 0, 0);\n this.ctx.restore();\n this.transparentCanvas = null;\n }\n }\n\n endDrawing() {\n this.#restoreInitialState();\n\n this.cachedCanvases.clear();\n this.cachedPatterns.clear();\n\n for (const cache of this._cachedBitmapsMap.values()) {\n for (const canvas of cache.values()) {\n if (\n typeof HTMLCanvasElement !== \"undefined\" &&\n canvas instanceof HTMLCanvasElement\n ) {\n canvas.width = canvas.height = 0;\n }\n }\n cache.clear();\n }\n this._cachedBitmapsMap.clear();\n this.#drawFilter();\n }\n\n #drawFilter() {\n if (this.pageColors) {\n const hcmFilterId = this.filterFactory.addHCMFilter(\n this.pageColors.foreground,\n this.pageColors.background\n );\n if (hcmFilterId !== \"none\") {\n const savedFilter = this.ctx.filter;\n this.ctx.filter = hcmFilterId;\n this.ctx.drawImage(this.ctx.canvas, 0, 0);\n this.ctx.filter = savedFilter;\n }\n }\n }\n\n _scaleImage(img, inverseTransform) {\n // Vertical or horizontal scaling shall not be more than 2 to not lose the\n // pixels during drawImage operation, painting on the temporary canvas(es)\n // that are twice smaller in size.\n\n // displayWidth and displayHeight are used for VideoFrame.\n const width = img.width ?? img.displayWidth;\n const height = img.height ?? img.displayHeight;\n let widthScale = Math.max(\n Math.hypot(inverseTransform[0], inverseTransform[1]),\n 1\n );\n let heightScale = Math.max(\n Math.hypot(inverseTransform[2], inverseTransform[3]),\n 1\n );\n\n let paintWidth = width,\n paintHeight = height;\n let tmpCanvasId = \"prescale1\";\n let tmpCanvas, tmpCtx;\n while (\n (widthScale > 2 && paintWidth > 1) ||\n (heightScale > 2 && paintHeight > 1)\n ) {\n let newWidth = paintWidth,\n newHeight = paintHeight;\n if (widthScale > 2 && paintWidth > 1) {\n // See bug 1820511 (Windows specific bug).\n // TODO: once the above bug is fixed we could revert to:\n // newWidth = Math.ceil(paintWidth / 2);\n newWidth =\n paintWidth >= 16384\n ? Math.floor(paintWidth / 2) - 1 || 1\n : Math.ceil(paintWidth / 2);\n widthScale /= paintWidth / newWidth;\n }\n if (heightScale > 2 && paintHeight > 1) {\n // TODO: see the comment above.\n newHeight =\n paintHeight >= 16384\n ? Math.floor(paintHeight / 2) - 1 || 1\n : Math.ceil(paintHeight) / 2;\n heightScale /= paintHeight / newHeight;\n }\n tmpCanvas = this.cachedCanvases.getCanvas(\n tmpCanvasId,\n newWidth,\n newHeight\n );\n tmpCtx = tmpCanvas.context;\n tmpCtx.clearRect(0, 0, newWidth, newHeight);\n tmpCtx.drawImage(\n img,\n 0,\n 0,\n paintWidth,\n paintHeight,\n 0,\n 0,\n newWidth,\n newHeight\n );\n img = tmpCanvas.canvas;\n paintWidth = newWidth;\n paintHeight = newHeight;\n tmpCanvasId = tmpCanvasId === \"prescale1\" ? \"prescale2\" : \"prescale1\";\n }\n return {\n img,\n paintWidth,\n paintHeight,\n };\n }\n\n _createMaskCanvas(img) {\n const ctx = this.ctx;\n const { width, height } = img;\n const fillColor = this.current.fillColor;\n const isPatternFill = this.current.patternFill;\n const currentTransform = getCurrentTransform(ctx);\n\n let cache, cacheKey, scaled, maskCanvas;\n if ((img.bitmap || img.data) && img.count > 1) {\n const mainKey = img.bitmap || img.data.buffer;\n // We're reusing the same image several times, so we can cache it.\n // In case we've a pattern fill we just keep the scaled version of\n // the image.\n // Only the scaling part matters, the translation part is just used\n // to compute offsets (but not when filling patterns see #15573).\n // TODO: handle the case of a pattern fill if it's possible.\n cacheKey = JSON.stringify(\n isPatternFill\n ? currentTransform\n : [currentTransform.slice(0, 4), fillColor]\n );\n\n cache = this._cachedBitmapsMap.get(mainKey);\n if (!cache) {\n cache = new Map();\n this._cachedBitmapsMap.set(mainKey, cache);\n }\n const cachedImage = cache.get(cacheKey);\n if (cachedImage && !isPatternFill) {\n const offsetX = Math.round(\n Math.min(currentTransform[0], currentTransform[2]) +\n currentTransform[4]\n );\n const offsetY = Math.round(\n Math.min(currentTransform[1], currentTransform[3]) +\n currentTransform[5]\n );\n return {\n canvas: cachedImage,\n offsetX,\n offsetY,\n };\n }\n scaled = cachedImage;\n }\n\n if (!scaled) {\n maskCanvas = this.cachedCanvases.getCanvas(\"maskCanvas\", width, height);\n putBinaryImageMask(maskCanvas.context, img);\n }\n\n // Create the mask canvas at the size it will be drawn at and also set\n // its transform to match the current transform so if there are any\n // patterns applied they will be applied relative to the correct\n // transform.\n\n let maskToCanvas = Util.transform(currentTransform, [\n 1 / width,\n 0,\n 0,\n -1 / height,\n 0,\n 0,\n ]);\n maskToCanvas = Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);\n const [minX, minY, maxX, maxY] = Util.getAxialAlignedBoundingBox(\n [0, 0, width, height],\n maskToCanvas\n );\n const drawnWidth = Math.round(maxX - minX) || 1;\n const drawnHeight = Math.round(maxY - minY) || 1;\n const fillCanvas = this.cachedCanvases.getCanvas(\n \"fillCanvas\",\n drawnWidth,\n drawnHeight\n );\n const fillCtx = fillCanvas.context;\n\n // The offset will be the top-left cordinate mask.\n // If objToCanvas is [a,b,c,d,e,f] then:\n // - offsetX = min(a, c) + e\n // - offsetY = min(b, d) + f\n const offsetX = minX;\n const offsetY = minY;\n fillCtx.translate(-offsetX, -offsetY);\n fillCtx.transform(...maskToCanvas);\n\n if (!scaled) {\n // Pre-scale if needed to improve image smoothing.\n scaled = this._scaleImage(\n maskCanvas.canvas,\n getCurrentTransformInverse(fillCtx)\n );\n scaled = scaled.img;\n if (cache && isPatternFill) {\n cache.set(cacheKey, scaled);\n }\n }\n\n fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(\n getCurrentTransform(fillCtx),\n img.interpolate\n );\n\n drawImageAtIntegerCoords(\n fillCtx,\n scaled,\n 0,\n 0,\n scaled.width,\n scaled.height,\n 0,\n 0,\n width,\n height\n );\n fillCtx.globalCompositeOperation = \"source-in\";\n\n const inverse = Util.transform(getCurrentTransformInverse(fillCtx), [\n 1,\n 0,\n 0,\n 1,\n -offsetX,\n -offsetY,\n ]);\n fillCtx.fillStyle = isPatternFill\n ? fillColor.getPattern(ctx, this, inverse, PathType.FILL)\n : fillColor;\n\n fillCtx.fillRect(0, 0, width, height);\n\n if (cache && !isPatternFill) {\n // The fill canvas is put in the cache associated to the mask image\n // so we must remove from the cached canvas: it mustn't be used again.\n this.cachedCanvases.delete(\"fillCanvas\");\n cache.set(cacheKey, fillCanvas.canvas);\n }\n\n // Round the offsets to avoid drawing fractional pixels.\n return {\n canvas: fillCanvas.canvas,\n offsetX: Math.round(offsetX),\n offsetY: Math.round(offsetY),\n };\n }\n\n // Graphics state\n setLineWidth(width) {\n if (width !== this.current.lineWidth) {\n this._cachedScaleForStroking[0] = -1;\n }\n this.current.lineWidth = width;\n this.ctx.lineWidth = width;\n }\n\n setLineCap(style) {\n this.ctx.lineCap = LINE_CAP_STYLES[style];\n }\n\n setLineJoin(style) {\n this.ctx.lineJoin = LINE_JOIN_STYLES[style];\n }\n\n setMiterLimit(limit) {\n this.ctx.miterLimit = limit;\n }\n\n setDash(dashArray, dashPhase) {\n const ctx = this.ctx;\n if (ctx.setLineDash !== undefined) {\n ctx.setLineDash(dashArray);\n ctx.lineDashOffset = dashPhase;\n }\n }\n\n setRenderingIntent(intent) {\n // This operation is ignored since we haven't found a use case for it yet.\n }\n\n setFlatness(flatness) {\n // This operation is ignored since we haven't found a use case for it yet.\n }\n\n setGState(states) {\n for (const [key, value] of states) {\n switch (key) {\n case \"LW\":\n this.setLineWidth(value);\n break;\n case \"LC\":\n this.setLineCap(value);\n break;\n case \"LJ\":\n this.setLineJoin(value);\n break;\n case \"ML\":\n this.setMiterLimit(value);\n break;\n case \"D\":\n this.setDash(value[0], value[1]);\n break;\n case \"RI\":\n this.setRenderingIntent(value);\n break;\n case \"FL\":\n this.setFlatness(value);\n break;\n case \"Font\":\n this.setFont(value[0], value[1]);\n break;\n case \"CA\":\n this.current.strokeAlpha = value;\n break;\n case \"ca\":\n this.current.fillAlpha = value;\n this.ctx.globalAlpha = value;\n break;\n case \"BM\":\n this.ctx.globalCompositeOperation = value;\n break;\n case \"SMask\":\n this.current.activeSMask = value ? this.tempSMask : null;\n this.tempSMask = null;\n this.checkSMaskState();\n break;\n case \"TR\":\n this.ctx.filter = this.current.transferMaps =\n this.filterFactory.addFilter(value);\n break;\n }\n }\n }\n\n get inSMaskMode() {\n return !!this.suspendedCtx;\n }\n\n checkSMaskState() {\n const inSMaskMode = this.inSMaskMode;\n if (this.current.activeSMask && !inSMaskMode) {\n this.beginSMaskMode();\n } else if (!this.current.activeSMask && inSMaskMode) {\n this.endSMaskMode();\n }\n // Else, the state is okay and nothing needs to be done.\n }\n\n /**\n * Soft mask mode takes the current main drawing canvas and replaces it with\n * a temporary canvas. Any drawing operations that happen on the temporary\n * canvas need to be composed with the main canvas that was suspended (see\n * `compose()`). The temporary canvas also duplicates many of its operations\n * on the suspended canvas to keep them in sync, so that when the soft mask\n * mode ends any clipping paths or transformations will still be active and in\n * the right order on the canvas' graphics state stack.\n */\n beginSMaskMode() {\n if (this.inSMaskMode) {\n throw new Error(\"beginSMaskMode called while already in smask mode\");\n }\n const drawnWidth = this.ctx.canvas.width;\n const drawnHeight = this.ctx.canvas.height;\n const cacheId = \"smaskGroupAt\" + this.groupLevel;\n const scratchCanvas = this.cachedCanvases.getCanvas(\n cacheId,\n drawnWidth,\n drawnHeight\n );\n this.suspendedCtx = this.ctx;\n this.ctx = scratchCanvas.context;\n const ctx = this.ctx;\n ctx.setTransform(...getCurrentTransform(this.suspendedCtx));\n copyCtxState(this.suspendedCtx, ctx);\n mirrorContextOperations(ctx, this.suspendedCtx);\n\n this.setGState([\n [\"BM\", \"source-over\"],\n [\"ca\", 1],\n [\"CA\", 1],\n ]);\n }\n\n endSMaskMode() {\n if (!this.inSMaskMode) {\n throw new Error(\"endSMaskMode called while not in smask mode\");\n }\n // The soft mask is done, now restore the suspended canvas as the main\n // drawing canvas.\n this.ctx._removeMirroring();\n copyCtxState(this.ctx, this.suspendedCtx);\n this.ctx = this.suspendedCtx;\n\n this.suspendedCtx = null;\n }\n\n compose(dirtyBox) {\n if (!this.current.activeSMask) {\n return;\n }\n\n if (!dirtyBox) {\n dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];\n } else {\n dirtyBox[0] = Math.floor(dirtyBox[0]);\n dirtyBox[1] = Math.floor(dirtyBox[1]);\n dirtyBox[2] = Math.ceil(dirtyBox[2]);\n dirtyBox[3] = Math.ceil(dirtyBox[3]);\n }\n const smask = this.current.activeSMask;\n const suspendedCtx = this.suspendedCtx;\n\n this.composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);\n // Whatever was drawn has been moved to the suspended canvas, now clear it\n // out of the current canvas.\n this.ctx.save();\n this.ctx.setTransform(1, 0, 0, 1, 0, 0);\n this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);\n this.ctx.restore();\n }\n\n composeSMask(ctx, smask, layerCtx, layerBox) {\n const layerOffsetX = layerBox[0];\n const layerOffsetY = layerBox[1];\n const layerWidth = layerBox[2] - layerOffsetX;\n const layerHeight = layerBox[3] - layerOffsetY;\n if (layerWidth === 0 || layerHeight === 0) {\n return;\n }\n this.genericComposeSMask(\n smask.context,\n layerCtx,\n layerWidth,\n layerHeight,\n smask.subtype,\n smask.backdrop,\n smask.transferMap,\n layerOffsetX,\n layerOffsetY,\n smask.offsetX,\n smask.offsetY\n );\n ctx.save();\n ctx.globalAlpha = 1;\n ctx.globalCompositeOperation = \"source-over\";\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.drawImage(layerCtx.canvas, 0, 0);\n ctx.restore();\n }\n\n genericComposeSMask(\n maskCtx,\n layerCtx,\n width,\n height,\n subtype,\n backdrop,\n transferMap,\n layerOffsetX,\n layerOffsetY,\n maskOffsetX,\n maskOffsetY\n ) {\n let maskCanvas = maskCtx.canvas;\n let maskX = layerOffsetX - maskOffsetX;\n let maskY = layerOffsetY - maskOffsetY;\n\n if (backdrop) {\n const backdropRGB = Util.makeHexColor(...backdrop);\n if (\n maskX < 0 ||\n maskY < 0 ||\n maskX + width > maskCanvas.width ||\n maskY + height > maskCanvas.height\n ) {\n const canvas = this.cachedCanvases.getCanvas(\n \"maskExtension\",\n width,\n height\n );\n const ctx = canvas.context;\n ctx.drawImage(maskCanvas, -maskX, -maskY);\n ctx.globalCompositeOperation = \"destination-atop\";\n ctx.fillStyle = backdropRGB;\n ctx.fillRect(0, 0, width, height);\n ctx.globalCompositeOperation = \"source-over\";\n\n maskCanvas = canvas.canvas;\n maskX = maskY = 0;\n } else {\n maskCtx.save();\n maskCtx.globalAlpha = 1;\n maskCtx.setTransform(1, 0, 0, 1, 0, 0);\n const clip = new Path2D();\n clip.rect(maskX, maskY, width, height);\n maskCtx.clip(clip);\n maskCtx.globalCompositeOperation = \"destination-atop\";\n maskCtx.fillStyle = backdropRGB;\n maskCtx.fillRect(maskX, maskY, width, height);\n maskCtx.restore();\n }\n }\n\n layerCtx.save();\n layerCtx.globalAlpha = 1;\n layerCtx.setTransform(1, 0, 0, 1, 0, 0);\n\n if (subtype === \"Alpha\" && transferMap) {\n layerCtx.filter = this.filterFactory.addAlphaFilter(transferMap);\n } else if (subtype === \"Luminosity\") {\n layerCtx.filter = this.filterFactory.addLuminosityFilter(transferMap);\n }\n\n const clip = new Path2D();\n clip.rect(layerOffsetX, layerOffsetY, width, height);\n layerCtx.clip(clip);\n layerCtx.globalCompositeOperation = \"destination-in\";\n layerCtx.drawImage(\n maskCanvas,\n maskX,\n maskY,\n width,\n height,\n layerOffsetX,\n layerOffsetY,\n width,\n height\n );\n layerCtx.restore();\n }\n\n save() {\n if (this.inSMaskMode) {\n // SMask mode may be turned on/off causing us to lose graphics state.\n // Copy the temporary canvas state to the main(suspended) canvas to keep\n // it in sync.\n copyCtxState(this.ctx, this.suspendedCtx);\n // Don't bother calling save on the temporary canvas since state is not\n // saved there.\n this.suspendedCtx.save();\n } else {\n this.ctx.save();\n }\n const old = this.current;\n this.stateStack.push(old);\n this.current = old.clone();\n }\n\n restore() {\n if (this.stateStack.length === 0 && this.inSMaskMode) {\n this.endSMaskMode();\n }\n if (this.stateStack.length !== 0) {\n this.current = this.stateStack.pop();\n if (this.inSMaskMode) {\n // Graphics state is stored on the main(suspended) canvas. Restore its\n // state then copy it over to the temporary canvas.\n this.suspendedCtx.restore();\n copyCtxState(this.suspendedCtx, this.ctx);\n } else {\n this.ctx.restore();\n }\n this.checkSMaskState();\n\n // Ensure that the clipping path is reset (fixes issue6413.pdf).\n this.pendingClip = null;\n\n this._cachedScaleForStroking[0] = -1;\n this._cachedGetSinglePixelWidth = null;\n }\n }\n\n transform(a, b, c, d, e, f) {\n this.ctx.transform(a, b, c, d, e, f);\n\n this._cachedScaleForStroking[0] = -1;\n this._cachedGetSinglePixelWidth = null;\n }\n\n // Path\n constructPath(ops, args, minMax) {\n const ctx = this.ctx;\n const current = this.current;\n let x = current.x,\n y = current.y;\n let startX, startY;\n const currentTransform = getCurrentTransform(ctx);\n\n // Most of the time the current transform is a scaling matrix\n // so we don't need to transform points before computing min/max:\n // we can compute min/max first and then smartly \"apply\" the\n // transform (see Util.scaleMinMax).\n // For rectangle, moveTo and lineTo, min/max are computed in the\n // worker (see evaluator.js).\n const isScalingMatrix =\n (currentTransform[0] === 0 && currentTransform[3] === 0) ||\n (currentTransform[1] === 0 && currentTransform[2] === 0);\n const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;\n\n for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {\n switch (ops[i] | 0) {\n case OPS.rectangle:\n x = args[j++];\n y = args[j++];\n const width = args[j++];\n const height = args[j++];\n\n const xw = x + width;\n const yh = y + height;\n ctx.moveTo(x, y);\n if (width === 0 || height === 0) {\n ctx.lineTo(xw, yh);\n } else {\n ctx.lineTo(xw, y);\n ctx.lineTo(xw, yh);\n ctx.lineTo(x, yh);\n }\n if (!isScalingMatrix) {\n current.updateRectMinMax(currentTransform, [x, y, xw, yh]);\n }\n ctx.closePath();\n break;\n case OPS.moveTo:\n x = args[j++];\n y = args[j++];\n ctx.moveTo(x, y);\n if (!isScalingMatrix) {\n current.updatePathMinMax(currentTransform, x, y);\n }\n break;\n case OPS.lineTo:\n x = args[j++];\n y = args[j++];\n ctx.lineTo(x, y);\n if (!isScalingMatrix) {\n current.updatePathMinMax(currentTransform, x, y);\n }\n break;\n case OPS.curveTo:\n startX = x;\n startY = y;\n x = args[j + 4];\n y = args[j + 5];\n ctx.bezierCurveTo(\n args[j],\n args[j + 1],\n args[j + 2],\n args[j + 3],\n x,\n y\n );\n current.updateCurvePathMinMax(\n currentTransform,\n startX,\n startY,\n args[j],\n args[j + 1],\n args[j + 2],\n args[j + 3],\n x,\n y,\n minMaxForBezier\n );\n j += 6;\n break;\n case OPS.curveTo2:\n startX = x;\n startY = y;\n ctx.bezierCurveTo(\n x,\n y,\n args[j],\n args[j + 1],\n args[j + 2],\n args[j + 3]\n );\n current.updateCurvePathMinMax(\n currentTransform,\n startX,\n startY,\n x,\n y,\n args[j],\n args[j + 1],\n args[j + 2],\n args[j + 3],\n minMaxForBezier\n );\n x = args[j + 2];\n y = args[j + 3];\n j += 4;\n break;\n case OPS.curveTo3:\n startX = x;\n startY = y;\n x = args[j + 2];\n y = args[j + 3];\n ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);\n current.updateCurvePathMinMax(\n currentTransform,\n startX,\n startY,\n args[j],\n args[j + 1],\n x,\n y,\n x,\n y,\n minMaxForBezier\n );\n j += 4;\n break;\n case OPS.closePath:\n ctx.closePath();\n break;\n }\n }\n\n if (isScalingMatrix) {\n current.updateScalingPathMinMax(currentTransform, minMaxForBezier);\n }\n\n current.setCurrentPoint(x, y);\n }\n\n closePath() {\n this.ctx.closePath();\n }\n\n stroke(consumePath = true) {\n const ctx = this.ctx;\n const strokeColor = this.current.strokeColor;\n // For stroke we want to temporarily change the global alpha to the\n // stroking alpha.\n ctx.globalAlpha = this.current.strokeAlpha;\n if (this.contentVisible) {\n if (typeof strokeColor === \"object\" && strokeColor?.getPattern) {\n ctx.save();\n ctx.strokeStyle = strokeColor.getPattern(\n ctx,\n this,\n getCurrentTransformInverse(ctx),\n PathType.STROKE\n );\n this.rescaleAndStroke(/* saveRestore */ false);\n ctx.restore();\n } else {\n this.rescaleAndStroke(/* saveRestore */ true);\n }\n }\n if (consumePath) {\n this.consumePath(this.current.getClippedPathBoundingBox());\n }\n // Restore the global alpha to the fill alpha\n ctx.globalAlpha = this.current.fillAlpha;\n }\n\n closeStroke() {\n this.closePath();\n this.stroke();\n }\n\n fill(consumePath = true) {\n const ctx = this.ctx;\n const fillColor = this.current.fillColor;\n const isPatternFill = this.current.patternFill;\n let needRestore = false;\n\n if (isPatternFill) {\n ctx.save();\n ctx.fillStyle = fillColor.getPattern(\n ctx,\n this,\n getCurrentTransformInverse(ctx),\n PathType.FILL\n );\n needRestore = true;\n }\n\n const intersect = this.current.getClippedPathBoundingBox();\n if (this.contentVisible && intersect !== null) {\n if (this.pendingEOFill) {\n ctx.fill(\"evenodd\");\n this.pendingEOFill = false;\n } else {\n ctx.fill();\n }\n }\n\n if (needRestore) {\n ctx.restore();\n }\n if (consumePath) {\n this.consumePath(intersect);\n }\n }\n\n eoFill() {\n this.pendingEOFill = true;\n this.fill();\n }\n\n fillStroke() {\n this.fill(false);\n this.stroke(false);\n\n this.consumePath();\n }\n\n eoFillStroke() {\n this.pendingEOFill = true;\n this.fillStroke();\n }\n\n closeFillStroke() {\n this.closePath();\n this.fillStroke();\n }\n\n closeEOFillStroke() {\n this.pendingEOFill = true;\n this.closePath();\n this.fillStroke();\n }\n\n endPath() {\n this.consumePath();\n }\n\n // Clipping\n clip() {\n this.pendingClip = NORMAL_CLIP;\n }\n\n eoClip() {\n this.pendingClip = EO_CLIP;\n }\n\n // Text\n beginText() {\n this.current.textMatrix = IDENTITY_MATRIX;\n this.current.textMatrixScale = 1;\n this.current.x = this.current.lineX = 0;\n this.current.y = this.current.lineY = 0;\n }\n\n endText() {\n const paths = this.pendingTextPaths;\n const ctx = this.ctx;\n if (paths === undefined) {\n ctx.beginPath();\n return;\n }\n\n ctx.save();\n ctx.beginPath();\n for (const path of paths) {\n ctx.setTransform(...path.transform);\n ctx.translate(path.x, path.y);\n path.addToPath(ctx, path.fontSize);\n }\n ctx.restore();\n ctx.clip();\n ctx.beginPath();\n delete this.pendingTextPaths;\n }\n\n setCharSpacing(spacing) {\n this.current.charSpacing = spacing;\n }\n\n setWordSpacing(spacing) {\n this.current.wordSpacing = spacing;\n }\n\n setHScale(scale) {\n this.current.textHScale = scale / 100;\n }\n\n setLeading(leading) {\n this.current.leading = -leading;\n }\n\n setFont(fontRefName, size) {\n const fontObj = this.commonObjs.get(fontRefName);\n const current = this.current;\n\n if (!fontObj) {\n throw new Error(`Can't find font for ${fontRefName}`);\n }\n current.fontMatrix = fontObj.fontMatrix || FONT_IDENTITY_MATRIX;\n\n // A valid matrix needs all main diagonal elements to be non-zero\n // This also ensures we bypass FF bugzilla bug #719844.\n if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {\n warn(\"Invalid font matrix for font \" + fontRefName);\n }\n\n // The spec for Tf (setFont) says that 'size' specifies the font 'scale',\n // and in some docs this can be negative (inverted x-y axes).\n if (size < 0) {\n size = -size;\n current.fontDirection = -1;\n } else {\n current.fontDirection = 1;\n }\n\n this.current.font = fontObj;\n this.current.fontSize = size;\n\n if (fontObj.isType3Font) {\n return; // we don't need ctx.font for Type3 fonts\n }\n\n const name = fontObj.loadedName || \"sans-serif\";\n const typeface =\n fontObj.systemFontInfo?.css || `\"${name}\", ${fontObj.fallbackName}`;\n\n let bold = \"normal\";\n if (fontObj.black) {\n bold = \"900\";\n } else if (fontObj.bold) {\n bold = \"bold\";\n }\n const italic = fontObj.italic ? \"italic\" : \"normal\";\n\n // Some font backends cannot handle fonts below certain size.\n // Keeping the font at minimal size and using the fontSizeScale to change\n // the current transformation matrix before the fillText/strokeText.\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227\n let browserFontSize = size;\n if (size < MIN_FONT_SIZE) {\n browserFontSize = MIN_FONT_SIZE;\n } else if (size > MAX_FONT_SIZE) {\n browserFontSize = MAX_FONT_SIZE;\n }\n this.current.fontSizeScale = size / browserFontSize;\n\n this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;\n }\n\n setTextRenderingMode(mode) {\n this.current.textRenderingMode = mode;\n }\n\n setTextRise(rise) {\n this.current.textRise = rise;\n }\n\n moveText(x, y) {\n this.current.x = this.current.lineX += x;\n this.current.y = this.current.lineY += y;\n }\n\n setLeadingMoveText(x, y) {\n this.setLeading(-y);\n this.moveText(x, y);\n }\n\n setTextMatrix(a, b, c, d, e, f) {\n this.current.textMatrix = [a, b, c, d, e, f];\n this.current.textMatrixScale = Math.hypot(a, b);\n\n this.current.x = this.current.lineX = 0;\n this.current.y = this.current.lineY = 0;\n }\n\n nextLine() {\n this.moveText(0, this.current.leading);\n }\n\n paintChar(character, x, y, patternFillTransform, patternStrokeTransform) {\n const ctx = this.ctx;\n const current = this.current;\n const font = current.font;\n const textRenderingMode = current.textRenderingMode;\n const fontSize = current.fontSize / current.fontSizeScale;\n const fillStrokeMode =\n textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;\n const isAddToPathSet = !!(\n textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG\n );\n const patternFill = current.patternFill && !font.missingFile;\n const patternStroke = current.patternStroke && !font.missingFile;\n\n let addToPath;\n if (\n font.disableFontFace ||\n isAddToPathSet ||\n patternFill ||\n patternStroke\n ) {\n addToPath = font.getPathGenerator(this.commonObjs, character);\n }\n\n if (font.disableFontFace || patternFill || patternStroke) {\n ctx.save();\n ctx.translate(x, y);\n ctx.beginPath();\n addToPath(ctx, fontSize);\n if (\n fillStrokeMode === TextRenderingMode.FILL ||\n fillStrokeMode === TextRenderingMode.FILL_STROKE\n ) {\n if (patternFillTransform) {\n ctx.setTransform(...patternFillTransform);\n }\n ctx.fill();\n }\n if (\n fillStrokeMode === TextRenderingMode.STROKE ||\n fillStrokeMode === TextRenderingMode.FILL_STROKE\n ) {\n if (patternStrokeTransform) {\n ctx.setTransform(...patternStrokeTransform);\n }\n ctx.stroke();\n }\n ctx.restore();\n } else {\n if (\n fillStrokeMode === TextRenderingMode.FILL ||\n fillStrokeMode === TextRenderingMode.FILL_STROKE\n ) {\n ctx.fillText(character, x, y);\n }\n if (\n fillStrokeMode === TextRenderingMode.STROKE ||\n fillStrokeMode === TextRenderingMode.FILL_STROKE\n ) {\n ctx.strokeText(character, x, y);\n }\n }\n\n if (isAddToPathSet) {\n const paths = (this.pendingTextPaths ||= []);\n paths.push({\n transform: getCurrentTransform(ctx),\n x,\n y,\n fontSize,\n addToPath,\n });\n }\n }\n\n get isFontSubpixelAAEnabled() {\n // Checks if anti-aliasing is enabled when scaled text is painted.\n // On Windows GDI scaled fonts looks bad.\n const { context: ctx } = this.cachedCanvases.getCanvas(\n \"isFontSubpixelAAEnabled\",\n 10,\n 10\n );\n ctx.scale(1.5, 1);\n ctx.fillText(\"I\", 0, 10);\n const data = ctx.getImageData(0, 0, 10, 10).data;\n let enabled = false;\n for (let i = 3; i < data.length; i += 4) {\n if (data[i] > 0 && data[i] < 255) {\n enabled = true;\n break;\n }\n }\n return shadow(this, \"isFontSubpixelAAEnabled\", enabled);\n }\n\n showText(glyphs) {\n const current = this.current;\n const font = current.font;\n if (font.isType3Font) {\n return this.showType3Text(glyphs);\n }\n\n const fontSize = current.fontSize;\n if (fontSize === 0) {\n return undefined;\n }\n\n const ctx = this.ctx;\n const fontSizeScale = current.fontSizeScale;\n const charSpacing = current.charSpacing;\n const wordSpacing = current.wordSpacing;\n const fontDirection = current.fontDirection;\n const textHScale = current.textHScale * fontDirection;\n const glyphsLength = glyphs.length;\n const vertical = font.vertical;\n const spacingDir = vertical ? 1 : -1;\n const defaultVMetrics = font.defaultVMetrics;\n const widthAdvanceScale = fontSize * current.fontMatrix[0];\n\n const simpleFillText =\n current.textRenderingMode === TextRenderingMode.FILL &&\n !font.disableFontFace &&\n !current.patternFill;\n\n ctx.save();\n ctx.transform(...current.textMatrix);\n ctx.translate(current.x, current.y + current.textRise);\n\n if (fontDirection > 0) {\n ctx.scale(textHScale, -1);\n } else {\n ctx.scale(textHScale, 1);\n }\n\n let patternFillTransform, patternStrokeTransform;\n if (current.patternFill) {\n ctx.save();\n const pattern = current.fillColor.getPattern(\n ctx,\n this,\n getCurrentTransformInverse(ctx),\n PathType.FILL\n );\n patternFillTransform = getCurrentTransform(ctx);\n ctx.restore();\n ctx.fillStyle = pattern;\n }\n\n if (current.patternStroke) {\n ctx.save();\n const pattern = current.strokeColor.getPattern(\n ctx,\n this,\n getCurrentTransformInverse(ctx),\n PathType.STROKE\n );\n patternStrokeTransform = getCurrentTransform(ctx);\n ctx.restore();\n ctx.strokeStyle = pattern;\n }\n\n let lineWidth = current.lineWidth;\n const scale = current.textMatrixScale;\n if (scale === 0 || lineWidth === 0) {\n const fillStrokeMode =\n current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;\n if (\n fillStrokeMode === TextRenderingMode.STROKE ||\n fillStrokeMode === TextRenderingMode.FILL_STROKE\n ) {\n lineWidth = this.getSinglePixelWidth();\n }\n } else {\n lineWidth /= scale;\n }\n\n if (fontSizeScale !== 1.0) {\n ctx.scale(fontSizeScale, fontSizeScale);\n lineWidth /= fontSizeScale;\n }\n\n ctx.lineWidth = lineWidth;\n\n if (font.isInvalidPDFjsFont) {\n const chars = [];\n let width = 0;\n for (const glyph of glyphs) {\n chars.push(glyph.unicode);\n width += glyph.width;\n }\n ctx.fillText(chars.join(\"\"), 0, 0);\n current.x += width * widthAdvanceScale * textHScale;\n ctx.restore();\n this.compose();\n\n return undefined;\n }\n\n let x = 0,\n i;\n for (i = 0; i < glyphsLength; ++i) {\n const glyph = glyphs[i];\n if (typeof glyph === \"number\") {\n x += (spacingDir * glyph * fontSize) / 1000;\n continue;\n }\n\n let restoreNeeded = false;\n const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;\n const character = glyph.fontChar;\n const accent = glyph.accent;\n let scaledX, scaledY;\n let width = glyph.width;\n if (vertical) {\n const vmetric = glyph.vmetric || defaultVMetrics;\n const vx =\n -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;\n const vy = vmetric[2] * widthAdvanceScale;\n\n width = vmetric ? -vmetric[0] : width;\n scaledX = vx / fontSizeScale;\n scaledY = (x + vy) / fontSizeScale;\n } else {\n scaledX = x / fontSizeScale;\n scaledY = 0;\n }\n\n if (font.remeasure && width > 0) {\n // Some standard fonts may not have the exact width: rescale per\n // character if measured width is greater than expected glyph width\n // and subpixel-aa is enabled, otherwise just center the glyph.\n const measuredWidth =\n ((ctx.measureText(character).width * 1000) / fontSize) *\n fontSizeScale;\n if (width < measuredWidth && this.isFontSubpixelAAEnabled) {\n const characterScaleX = width / measuredWidth;\n restoreNeeded = true;\n ctx.save();\n ctx.scale(characterScaleX, 1);\n scaledX /= characterScaleX;\n } else if (width !== measuredWidth) {\n scaledX +=\n (((width - measuredWidth) / 2000) * fontSize) / fontSizeScale;\n }\n }\n\n // Only attempt to draw the glyph if it is actually in the embedded font\n // file or if there isn't a font file so the fallback font is shown.\n if (this.contentVisible && (glyph.isInFont || font.missingFile)) {\n if (simpleFillText && !accent) {\n // common case\n ctx.fillText(character, scaledX, scaledY);\n } else {\n this.paintChar(\n character,\n scaledX,\n scaledY,\n patternFillTransform,\n patternStrokeTransform\n );\n if (accent) {\n const scaledAccentX =\n scaledX + (fontSize * accent.offset.x) / fontSizeScale;\n const scaledAccentY =\n scaledY - (fontSize * accent.offset.y) / fontSizeScale;\n this.paintChar(\n accent.fontChar,\n scaledAccentX,\n scaledAccentY,\n patternFillTransform,\n patternStrokeTransform\n );\n }\n }\n }\n\n const charWidth = vertical\n ? width * widthAdvanceScale - spacing * fontDirection\n : width * widthAdvanceScale + spacing * fontDirection;\n x += charWidth;\n\n if (restoreNeeded) {\n ctx.restore();\n }\n }\n if (vertical) {\n current.y -= x;\n } else {\n current.x += x * textHScale;\n }\n ctx.restore();\n this.compose();\n\n return undefined;\n }\n\n showType3Text(glyphs) {\n // Type3 fonts - each glyph is a \"mini-PDF\"\n const ctx = this.ctx;\n const current = this.current;\n const font = current.font;\n const fontSize = current.fontSize;\n const fontDirection = current.fontDirection;\n const spacingDir = font.vertical ? 1 : -1;\n const charSpacing = current.charSpacing;\n const wordSpacing = current.wordSpacing;\n const textHScale = current.textHScale * fontDirection;\n const fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;\n const glyphsLength = glyphs.length;\n const isTextInvisible =\n current.textRenderingMode === TextRenderingMode.INVISIBLE;\n let i, glyph, width, spacingLength;\n\n if (isTextInvisible || fontSize === 0) {\n return;\n }\n this._cachedScaleForStroking[0] = -1;\n this._cachedGetSinglePixelWidth = null;\n\n ctx.save();\n ctx.transform(...current.textMatrix);\n ctx.translate(current.x, current.y);\n\n ctx.scale(textHScale, fontDirection);\n\n for (i = 0; i < glyphsLength; ++i) {\n glyph = glyphs[i];\n if (typeof glyph === \"number\") {\n spacingLength = (spacingDir * glyph * fontSize) / 1000;\n this.ctx.translate(spacingLength, 0);\n current.x += spacingLength * textHScale;\n continue;\n }\n\n const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;\n const operatorList = font.charProcOperatorList[glyph.operatorListId];\n if (!operatorList) {\n warn(`Type3 character \"${glyph.operatorListId}\" is not available.`);\n continue;\n }\n if (this.contentVisible) {\n this.processingType3 = glyph;\n this.save();\n ctx.scale(fontSize, fontSize);\n ctx.transform(...fontMatrix);\n this.executeOperatorList(operatorList);\n this.restore();\n }\n\n const transformed = Util.applyTransform([glyph.width, 0], fontMatrix);\n width = transformed[0] * fontSize + spacing;\n\n ctx.translate(width, 0);\n current.x += width * textHScale;\n }\n ctx.restore();\n this.processingType3 = null;\n }\n\n // Type3 fonts\n setCharWidth(xWidth, yWidth) {\n // We can safely ignore this since the width should be the same\n // as the width in the Widths array.\n }\n\n setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {\n this.ctx.rect(llx, lly, urx - llx, ury - lly);\n this.ctx.clip();\n this.endPath();\n }\n\n // Color\n getColorN_Pattern(IR) {\n let pattern;\n if (IR[0] === \"TilingPattern\") {\n const color = IR[1];\n const baseTransform = this.baseTransform || getCurrentTransform(this.ctx);\n const canvasGraphicsFactory = {\n createCanvasGraphics: ctx =>\n new CanvasGraphics(\n ctx,\n this.commonObjs,\n this.objs,\n this.canvasFactory,\n this.filterFactory,\n {\n optionalContentConfig: this.optionalContentConfig,\n markedContentStack: this.markedContentStack,\n }\n ),\n };\n pattern = new TilingPattern(\n IR,\n color,\n this.ctx,\n canvasGraphicsFactory,\n baseTransform\n );\n } else {\n pattern = this._getPattern(IR[1], IR[2]);\n }\n return pattern;\n }\n\n setStrokeColorN() {\n this.current.strokeColor = this.getColorN_Pattern(arguments);\n this.current.patternStroke = true;\n }\n\n setFillColorN() {\n this.current.fillColor = this.getColorN_Pattern(arguments);\n this.current.patternFill = true;\n }\n\n setStrokeRGBColor(r, g, b) {\n this.ctx.strokeStyle = this.current.strokeColor = Util.makeHexColor(\n r,\n g,\n b\n );\n this.current.patternStroke = false;\n }\n\n setStrokeTransparent() {\n this.ctx.strokeStyle = this.current.strokeColor = \"transparent\";\n this.current.patternStroke = false;\n }\n\n setFillRGBColor(r, g, b) {\n this.ctx.fillStyle = this.current.fillColor = Util.makeHexColor(r, g, b);\n this.current.patternFill = false;\n }\n\n setFillTransparent() {\n this.ctx.fillStyle = this.current.fillColor = \"transparent\";\n this.current.patternFill = false;\n }\n\n _getPattern(objId, matrix = null) {\n let pattern;\n if (this.cachedPatterns.has(objId)) {\n pattern = this.cachedPatterns.get(objId);\n } else {\n pattern = getShadingPattern(this.getObject(objId));\n this.cachedPatterns.set(objId, pattern);\n }\n if (matrix) {\n pattern.matrix = matrix;\n }\n return pattern;\n }\n\n shadingFill(objId) {\n if (!this.contentVisible) {\n return;\n }\n const ctx = this.ctx;\n\n this.save();\n const pattern = this._getPattern(objId);\n ctx.fillStyle = pattern.getPattern(\n ctx,\n this,\n getCurrentTransformInverse(ctx),\n PathType.SHADING\n );\n\n const inv = getCurrentTransformInverse(ctx);\n if (inv) {\n const { width, height } = ctx.canvas;\n const [x0, y0, x1, y1] = Util.getAxialAlignedBoundingBox(\n [0, 0, width, height],\n inv\n );\n\n this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);\n } else {\n // HACK to draw the gradient onto an infinite rectangle.\n // PDF gradients are drawn across the entire image while\n // Canvas only allows gradients to be drawn in a rectangle\n // The following bug should allow us to remove this.\n // https://bugzilla.mozilla.org/show_bug.cgi?id=664884\n\n this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);\n }\n\n this.compose(this.current.getClippedPathBoundingBox());\n this.restore();\n }\n\n // Images\n beginInlineImage() {\n unreachable(\"Should not call beginInlineImage\");\n }\n\n beginImageData() {\n unreachable(\"Should not call beginImageData\");\n }\n\n paintFormXObjectBegin(matrix, bbox) {\n if (!this.contentVisible) {\n return;\n }\n this.save();\n this.baseTransformStack.push(this.baseTransform);\n\n if (matrix) {\n this.transform(...matrix);\n }\n this.baseTransform = getCurrentTransform(this.ctx);\n\n if (bbox) {\n const width = bbox[2] - bbox[0];\n const height = bbox[3] - bbox[1];\n this.ctx.rect(bbox[0], bbox[1], width, height);\n this.current.updateRectMinMax(getCurrentTransform(this.ctx), bbox);\n this.clip();\n this.endPath();\n }\n }\n\n paintFormXObjectEnd() {\n if (!this.contentVisible) {\n return;\n }\n this.restore();\n this.baseTransform = this.baseTransformStack.pop();\n }\n\n beginGroup(group) {\n if (!this.contentVisible) {\n return;\n }\n\n this.save();\n // If there's an active soft mask we don't want it enabled for the group, so\n // clear it out. The mask and suspended canvas will be restored in endGroup.\n if (this.inSMaskMode) {\n this.endSMaskMode();\n this.current.activeSMask = null;\n }\n\n const currentCtx = this.ctx;\n // TODO non-isolated groups - according to Rik at adobe non-isolated\n // group results aren't usually that different and they even have tools\n // that ignore this setting. Notes from Rik on implementing:\n // - When you encounter an transparency group, create a new canvas with\n // the dimensions of the bbox\n // - copy the content from the previous canvas to the new canvas\n // - draw as usual\n // - remove the backdrop alpha:\n // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha\n // value of your transparency group and 'alphaBackdrop' the alpha of the\n // backdrop\n // - remove background color:\n // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)\n if (!group.isolated) {\n info(\"TODO: Support non-isolated groups.\");\n }\n\n // TODO knockout - supposedly possible with the clever use of compositing\n // modes.\n if (group.knockout) {\n warn(\"Knockout groups not supported.\");\n }\n\n const currentTransform = getCurrentTransform(currentCtx);\n if (group.matrix) {\n currentCtx.transform(...group.matrix);\n }\n if (!group.bbox) {\n throw new Error(\"Bounding box is required.\");\n }\n\n // Based on the current transform figure out how big the bounding box\n // will actually be.\n let bounds = Util.getAxialAlignedBoundingBox(\n group.bbox,\n getCurrentTransform(currentCtx)\n );\n // Clip the bounding box to the current canvas.\n const canvasBounds = [\n 0,\n 0,\n currentCtx.canvas.width,\n currentCtx.canvas.height,\n ];\n bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];\n // Use ceil in case we're between sizes so we don't create canvas that is\n // too small and make the canvas at least 1x1 pixels.\n const offsetX = Math.floor(bounds[0]);\n const offsetY = Math.floor(bounds[1]);\n const drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);\n const drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);\n\n this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);\n\n let cacheId = \"groupAt\" + this.groupLevel;\n if (group.smask) {\n // Using two cache entries is case if masks are used one after another.\n cacheId += \"_smask_\" + (this.smaskCounter++ % 2);\n }\n const scratchCanvas = this.cachedCanvases.getCanvas(\n cacheId,\n drawnWidth,\n drawnHeight\n );\n const groupCtx = scratchCanvas.context;\n\n // Since we created a new canvas that is just the size of the bounding box\n // we have to translate the group ctx.\n groupCtx.translate(-offsetX, -offsetY);\n groupCtx.transform(...currentTransform);\n\n if (group.smask) {\n // Saving state and cached mask to be used in setGState.\n this.smaskStack.push({\n canvas: scratchCanvas.canvas,\n context: groupCtx,\n offsetX,\n offsetY,\n subtype: group.smask.subtype,\n backdrop: group.smask.backdrop,\n transferMap: group.smask.transferMap || null,\n startTransformInverse: null, // used during suspend operation\n });\n } else {\n // Setup the current ctx so when the group is popped we draw it at the\n // right location.\n currentCtx.setTransform(1, 0, 0, 1, 0, 0);\n currentCtx.translate(offsetX, offsetY);\n currentCtx.save();\n }\n // The transparency group inherits all off the current graphics state\n // except the blend mode, soft mask, and alpha constants.\n copyCtxState(currentCtx, groupCtx);\n this.ctx = groupCtx;\n this.setGState([\n [\"BM\", \"source-over\"],\n [\"ca\", 1],\n [\"CA\", 1],\n ]);\n this.groupStack.push(currentCtx);\n this.groupLevel++;\n }\n\n endGroup(group) {\n if (!this.contentVisible) {\n return;\n }\n this.groupLevel--;\n const groupCtx = this.ctx;\n const ctx = this.groupStack.pop();\n this.ctx = ctx;\n // Turn off image smoothing to avoid sub pixel interpolation which can\n // look kind of blurry for some pdfs.\n this.ctx.imageSmoothingEnabled = false;\n\n if (group.smask) {\n this.tempSMask = this.smaskStack.pop();\n this.restore();\n } else {\n this.ctx.restore();\n const currentMtx = getCurrentTransform(this.ctx);\n this.restore();\n this.ctx.save();\n this.ctx.setTransform(...currentMtx);\n const dirtyBox = Util.getAxialAlignedBoundingBox(\n [0, 0, groupCtx.canvas.width, groupCtx.canvas.height],\n currentMtx\n );\n this.ctx.drawImage(groupCtx.canvas, 0, 0);\n this.ctx.restore();\n this.compose(dirtyBox);\n }\n }\n\n beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {\n // The annotations are drawn just after the page content.\n // The page content drawing can potentially have set a transform,\n // a clipping path, whatever...\n // So in order to have something clean, we restore the initial state.\n this.#restoreInitialState();\n resetCtxToDefault(this.ctx);\n\n this.ctx.save();\n this.save();\n\n if (this.baseTransform) {\n this.ctx.setTransform(...this.baseTransform);\n }\n\n if (rect) {\n const width = rect[2] - rect[0];\n const height = rect[3] - rect[1];\n\n if (hasOwnCanvas && this.annotationCanvasMap) {\n transform = transform.slice();\n transform[4] -= rect[0];\n transform[5] -= rect[1];\n\n rect = rect.slice();\n rect[0] = rect[1] = 0;\n rect[2] = width;\n rect[3] = height;\n\n const [scaleX, scaleY] = Util.singularValueDecompose2dScale(\n getCurrentTransform(this.ctx)\n );\n const { viewportScale } = this;\n const canvasWidth = Math.ceil(\n width * this.outputScaleX * viewportScale\n );\n const canvasHeight = Math.ceil(\n height * this.outputScaleY * viewportScale\n );\n\n this.annotationCanvas = this.canvasFactory.create(\n canvasWidth,\n canvasHeight\n );\n const { canvas, context } = this.annotationCanvas;\n this.annotationCanvasMap.set(id, canvas);\n this.annotationCanvas.savedCtx = this.ctx;\n this.ctx = context;\n this.ctx.save();\n this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);\n\n resetCtxToDefault(this.ctx);\n } else {\n resetCtxToDefault(this.ctx);\n\n // Consume a potential path before clipping.\n this.endPath();\n\n this.ctx.rect(rect[0], rect[1], width, height);\n this.ctx.clip();\n this.ctx.beginPath();\n }\n }\n\n this.current = new CanvasExtraState(\n this.ctx.canvas.width,\n this.ctx.canvas.height\n );\n\n this.transform(...transform);\n this.transform(...matrix);\n }\n\n endAnnotation() {\n if (this.annotationCanvas) {\n this.ctx.restore();\n this.#drawFilter();\n\n this.ctx = this.annotationCanvas.savedCtx;\n delete this.annotationCanvas.savedCtx;\n delete this.annotationCanvas;\n }\n }\n\n paintImageMaskXObject(img) {\n if (!this.contentVisible) {\n return;\n }\n const count = img.count;\n img = this.getObject(img.data, img);\n img.count = count;\n\n const ctx = this.ctx;\n const glyph = this.processingType3;\n\n if (glyph) {\n if (glyph.compiled === undefined) {\n glyph.compiled = compileType3Glyph(img);\n }\n\n if (glyph.compiled) {\n glyph.compiled(ctx);\n return;\n }\n }\n const mask = this._createMaskCanvas(img);\n const maskCanvas = mask.canvas;\n\n ctx.save();\n // The mask is drawn with the transform applied. Reset the current\n // transform to draw to the identity.\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);\n ctx.restore();\n this.compose();\n }\n\n paintImageMaskXObjectRepeat(\n img,\n scaleX,\n skewX = 0,\n skewY = 0,\n scaleY,\n positions\n ) {\n if (!this.contentVisible) {\n return;\n }\n\n img = this.getObject(img.data, img);\n\n const ctx = this.ctx;\n ctx.save();\n const currentTransform = getCurrentTransform(ctx);\n ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);\n const mask = this._createMaskCanvas(img);\n\n ctx.setTransform(\n 1,\n 0,\n 0,\n 1,\n mask.offsetX - currentTransform[4],\n mask.offsetY - currentTransform[5]\n );\n for (let i = 0, ii = positions.length; i < ii; i += 2) {\n const trans = Util.transform(currentTransform, [\n scaleX,\n skewX,\n skewY,\n scaleY,\n positions[i],\n positions[i + 1],\n ]);\n\n const [x, y] = Util.applyTransform([0, 0], trans);\n ctx.drawImage(mask.canvas, x, y);\n }\n ctx.restore();\n this.compose();\n }\n\n paintImageMaskXObjectGroup(images) {\n if (!this.contentVisible) {\n return;\n }\n const ctx = this.ctx;\n\n const fillColor = this.current.fillColor;\n const isPatternFill = this.current.patternFill;\n\n for (const image of images) {\n const { data, width, height, transform } = image;\n\n const maskCanvas = this.cachedCanvases.getCanvas(\n \"maskCanvas\",\n width,\n height\n );\n const maskCtx = maskCanvas.context;\n maskCtx.save();\n\n const img = this.getObject(data, image);\n putBinaryImageMask(maskCtx, img);\n\n maskCtx.globalCompositeOperation = \"source-in\";\n\n maskCtx.fillStyle = isPatternFill\n ? fillColor.getPattern(\n maskCtx,\n this,\n getCurrentTransformInverse(ctx),\n PathType.FILL\n )\n : fillColor;\n maskCtx.fillRect(0, 0, width, height);\n\n maskCtx.restore();\n\n ctx.save();\n ctx.transform(...transform);\n ctx.scale(1, -1);\n drawImageAtIntegerCoords(\n ctx,\n maskCanvas.canvas,\n 0,\n 0,\n width,\n height,\n 0,\n -1,\n 1,\n 1\n );\n ctx.restore();\n }\n this.compose();\n }\n\n paintImageXObject(objId) {\n if (!this.contentVisible) {\n return;\n }\n const imgData = this.getObject(objId);\n if (!imgData) {\n warn(\"Dependent image isn't ready yet\");\n return;\n }\n\n this.paintInlineImageXObject(imgData);\n }\n\n paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {\n if (!this.contentVisible) {\n return;\n }\n const imgData = this.getObject(objId);\n if (!imgData) {\n warn(\"Dependent image isn't ready yet\");\n return;\n }\n\n const width = imgData.width;\n const height = imgData.height;\n const map = [];\n for (let i = 0, ii = positions.length; i < ii; i += 2) {\n map.push({\n transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],\n x: 0,\n y: 0,\n w: width,\n h: height,\n });\n }\n this.paintInlineImageXObjectGroup(imgData, map);\n }\n\n applyTransferMapsToCanvas(ctx) {\n if (this.current.transferMaps !== \"none\") {\n ctx.filter = this.current.transferMaps;\n ctx.drawImage(ctx.canvas, 0, 0);\n ctx.filter = \"none\";\n }\n return ctx.canvas;\n }\n\n applyTransferMapsToBitmap(imgData) {\n if (this.current.transferMaps === \"none\") {\n return imgData.bitmap;\n }\n const { bitmap, width, height } = imgData;\n const tmpCanvas = this.cachedCanvases.getCanvas(\n \"inlineImage\",\n width,\n height\n );\n const tmpCtx = tmpCanvas.context;\n tmpCtx.filter = this.current.transferMaps;\n tmpCtx.drawImage(bitmap, 0, 0);\n tmpCtx.filter = \"none\";\n\n return tmpCanvas.canvas;\n }\n\n paintInlineImageXObject(imgData) {\n if (!this.contentVisible) {\n return;\n }\n const width = imgData.width;\n const height = imgData.height;\n const ctx = this.ctx;\n\n this.save();\n\n if (\n (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) ||\n !isNodeJS\n ) {\n // The filter, if any, will be applied in applyTransferMapsToBitmap.\n // It must be applied to the image before rescaling else some artifacts\n // could appear.\n // The final restore will reset it to its value.\n const { filter } = ctx;\n if (filter !== \"none\" && filter !== \"\") {\n ctx.filter = \"none\";\n }\n }\n\n // scale the image to the unit square\n ctx.scale(1 / width, -1 / height);\n\n let imgToPaint;\n if (imgData.bitmap) {\n imgToPaint = this.applyTransferMapsToBitmap(imgData);\n } else if (\n (typeof HTMLElement === \"function\" && imgData instanceof HTMLElement) ||\n !imgData.data\n ) {\n // typeof check is needed due to node.js support, see issue #8489\n imgToPaint = imgData;\n } else {\n const tmpCanvas = this.cachedCanvases.getCanvas(\n \"inlineImage\",\n width,\n height\n );\n const tmpCtx = tmpCanvas.context;\n putBinaryImageData(tmpCtx, imgData);\n imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);\n }\n\n const scaled = this._scaleImage(\n imgToPaint,\n getCurrentTransformInverse(ctx)\n );\n ctx.imageSmoothingEnabled = getImageSmoothingEnabled(\n getCurrentTransform(ctx),\n imgData.interpolate\n );\n\n drawImageAtIntegerCoords(\n ctx,\n scaled.img,\n 0,\n 0,\n scaled.paintWidth,\n scaled.paintHeight,\n 0,\n -height,\n width,\n height\n );\n this.compose();\n this.restore();\n }\n\n paintInlineImageXObjectGroup(imgData, map) {\n if (!this.contentVisible) {\n return;\n }\n const ctx = this.ctx;\n let imgToPaint;\n if (imgData.bitmap) {\n imgToPaint = imgData.bitmap;\n } else {\n const w = imgData.width;\n const h = imgData.height;\n\n const tmpCanvas = this.cachedCanvases.getCanvas(\"inlineImage\", w, h);\n const tmpCtx = tmpCanvas.context;\n putBinaryImageData(tmpCtx, imgData);\n imgToPaint = this.applyTransferMapsToCanvas(tmpCtx);\n }\n\n for (const entry of map) {\n ctx.save();\n ctx.transform(...entry.transform);\n ctx.scale(1, -1);\n drawImageAtIntegerCoords(\n ctx,\n imgToPaint,\n entry.x,\n entry.y,\n entry.w,\n entry.h,\n 0,\n -1,\n 1,\n 1\n );\n ctx.restore();\n }\n this.compose();\n }\n\n paintSolidColorImageMask() {\n if (!this.contentVisible) {\n return;\n }\n this.ctx.fillRect(0, 0, 1, 1);\n this.compose();\n }\n\n // Marked content\n\n markPoint(tag) {\n // TODO Marked content.\n }\n\n markPointProps(tag, properties) {\n // TODO Marked content.\n }\n\n beginMarkedContent(tag) {\n this.markedContentStack.push({\n visible: true,\n });\n }\n\n beginMarkedContentProps(tag, properties) {\n if (tag === \"OC\") {\n this.markedContentStack.push({\n visible: this.optionalContentConfig.isVisible(properties),\n });\n } else {\n this.markedContentStack.push({\n visible: true,\n });\n }\n this.contentVisible = this.isContentVisible();\n }\n\n endMarkedContent() {\n this.markedContentStack.pop();\n this.contentVisible = this.isContentVisible();\n }\n\n // Compatibility\n\n beginCompat() {\n // TODO ignore undefined operators (should we do that anyway?)\n }\n\n endCompat() {\n // TODO stop ignoring undefined operators\n }\n\n // Helper functions\n\n consumePath(clipBox) {\n const isEmpty = this.current.isEmptyClip();\n if (this.pendingClip) {\n this.current.updateClipFromPath();\n }\n if (!this.pendingClip) {\n this.compose(clipBox);\n }\n const ctx = this.ctx;\n if (this.pendingClip) {\n if (!isEmpty) {\n if (this.pendingClip === EO_CLIP) {\n ctx.clip(\"evenodd\");\n } else {\n ctx.clip();\n }\n }\n this.pendingClip = null;\n }\n this.current.startNewPathAndClipBox(this.current.clipBox);\n ctx.beginPath();\n }\n\n getSinglePixelWidth() {\n if (!this._cachedGetSinglePixelWidth) {\n const m = getCurrentTransform(this.ctx);\n if (m[1] === 0 && m[2] === 0) {\n // Fast path\n this._cachedGetSinglePixelWidth =\n 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));\n } else {\n const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);\n const normX = Math.hypot(m[0], m[2]);\n const normY = Math.hypot(m[1], m[3]);\n this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;\n }\n }\n return this._cachedGetSinglePixelWidth;\n }\n\n getScaleForStroking() {\n // A pixel has thicknessX = thicknessY = 1;\n // A transformed pixel is a parallelogram and the thicknesses\n // corresponds to the heights.\n // The goal of this function is to rescale before setting the\n // lineWidth in order to have both thicknesses greater or equal\n // to 1 after transform.\n if (this._cachedScaleForStroking[0] === -1) {\n const { lineWidth } = this.current;\n const { a, b, c, d } = this.ctx.getTransform();\n let scaleX, scaleY;\n\n if (b === 0 && c === 0) {\n // Fast path\n const normX = Math.abs(a);\n const normY = Math.abs(d);\n if (normX === normY) {\n if (lineWidth === 0) {\n scaleX = scaleY = 1 / normX;\n } else {\n const scaledLineWidth = normX * lineWidth;\n scaleX = scaleY = scaledLineWidth < 1 ? 1 / scaledLineWidth : 1;\n }\n } else if (lineWidth === 0) {\n scaleX = 1 / normX;\n scaleY = 1 / normY;\n } else {\n const scaledXLineWidth = normX * lineWidth;\n const scaledYLineWidth = normY * lineWidth;\n scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;\n scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;\n }\n } else {\n // A pixel (base (x, y)) is transformed by M into a parallelogram:\n // - its area is |det(M)|;\n // - heightY (orthogonal to Mx) has a length: |det(M)| / norm(Mx);\n // - heightX (orthogonal to My) has a length: |det(M)| / norm(My).\n // heightX and heightY are the thicknesses of the transformed pixel\n // and they must be both greater or equal to 1.\n const absDet = Math.abs(a * d - b * c);\n const normX = Math.hypot(a, b);\n const normY = Math.hypot(c, d);\n if (lineWidth === 0) {\n scaleX = normY / absDet;\n scaleY = normX / absDet;\n } else {\n const baseArea = lineWidth * absDet;\n scaleX = normY > baseArea ? normY / baseArea : 1;\n scaleY = normX > baseArea ? normX / baseArea : 1;\n }\n }\n this._cachedScaleForStroking[0] = scaleX;\n this._cachedScaleForStroking[1] = scaleY;\n }\n return this._cachedScaleForStroking;\n }\n\n // Rescale before stroking in order to have a final lineWidth\n // with both thicknesses greater or equal to 1.\n rescaleAndStroke(saveRestore) {\n const { ctx } = this;\n const { lineWidth } = this.current;\n const [scaleX, scaleY] = this.getScaleForStroking();\n\n ctx.lineWidth = lineWidth || 1;\n\n if (scaleX === 1 && scaleY === 1) {\n ctx.stroke();\n return;\n }\n\n const dashes = ctx.getLineDash();\n if (saveRestore) {\n ctx.save();\n }\n\n ctx.scale(scaleX, scaleY);\n\n // How the dashed line is rendered depends on the current transform...\n // so we added a rescale to handle too thin lines and consequently\n // the way the line is dashed will be modified.\n // If scaleX === scaleY, the dashed lines will be rendered correctly\n // else we'll have some bugs (but only with too thin lines).\n // Here we take the max... why not taking the min... or something else.\n // Anyway, as said it's buggy when scaleX !== scaleY.\n if (dashes.length > 0) {\n const scale = Math.max(scaleX, scaleY);\n ctx.setLineDash(dashes.map(x => x / scale));\n ctx.lineDashOffset /= scale;\n }\n\n ctx.stroke();\n\n if (saveRestore) {\n ctx.restore();\n }\n }\n\n isContentVisible() {\n for (let i = this.markedContentStack.length - 1; i >= 0; i--) {\n if (!this.markedContentStack[i].visible) {\n return false;\n }\n }\n return true;\n }\n}\n\nfor (const op in OPS) {\n if (CanvasGraphics.prototype[op] !== undefined) {\n CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];\n }\n}\n\nexport { CanvasGraphics };\n","/* Copyright 2018 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nclass GlobalWorkerOptions {\n static #port = null;\n\n static #src = \"\";\n\n /**\n * @type {Worker | null}\n */\n static get workerPort() {\n return this.#port;\n }\n\n /**\n * @param {Worker | null} workerPort - Defines global port for worker process.\n * Overrides the `workerSrc` option.\n */\n static set workerPort(val) {\n if (\n !(typeof Worker !== \"undefined\" && val instanceof Worker) &&\n val !== null\n ) {\n throw new Error(\"Invalid `workerPort` type.\");\n }\n this.#port = val;\n }\n\n /**\n * @type {string}\n */\n static get workerSrc() {\n return this.#src;\n }\n\n /**\n * @param {string} workerSrc - A string containing the path and filename of\n * the worker file.\n *\n * NOTE: The `workerSrc` option should always be set, in order to prevent\n * any issues when using the PDF.js library.\n */\n static set workerSrc(val) {\n if (typeof val !== \"string\") {\n throw new Error(\"Invalid `workerSrc` type.\");\n }\n this.#src = val;\n }\n}\n\nexport { GlobalWorkerOptions };\n","/* Copyright 2018 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AbortException,\n assert,\n MissingPDFException,\n PasswordException,\n UnexpectedResponseException,\n UnknownErrorException,\n unreachable,\n} from \"./util.js\";\n\nconst CallbackKind = {\n UNKNOWN: 0,\n DATA: 1,\n ERROR: 2,\n};\n\nconst StreamKind = {\n UNKNOWN: 0,\n CANCEL: 1,\n CANCEL_COMPLETE: 2,\n CLOSE: 3,\n ENQUEUE: 4,\n ERROR: 5,\n PULL: 6,\n PULL_COMPLETE: 7,\n START_COMPLETE: 8,\n};\n\nfunction onFn() {}\n\nfunction wrapReason(reason) {\n if (\n !(\n reason instanceof Error ||\n (typeof reason === \"object\" && reason !== null)\n )\n ) {\n unreachable(\n 'wrapReason: Expected \"reason\" to be a (possibly cloned) Error.'\n );\n }\n switch (reason.name) {\n case \"AbortException\":\n return new AbortException(reason.message);\n case \"MissingPDFException\":\n return new MissingPDFException(reason.message);\n case \"PasswordException\":\n return new PasswordException(reason.message, reason.code);\n case \"UnexpectedResponseException\":\n return new UnexpectedResponseException(reason.message, reason.status);\n case \"UnknownErrorException\":\n return new UnknownErrorException(reason.message, reason.details);\n default:\n return new UnknownErrorException(reason.message, reason.toString());\n }\n}\n\nclass MessageHandler {\n #messageAC = new AbortController();\n\n constructor(sourceName, targetName, comObj) {\n this.sourceName = sourceName;\n this.targetName = targetName;\n this.comObj = comObj;\n this.callbackId = 1;\n this.streamId = 1;\n this.streamSinks = Object.create(null);\n this.streamControllers = Object.create(null);\n this.callbackCapabilities = Object.create(null);\n this.actionHandler = Object.create(null);\n\n comObj.addEventListener(\"message\", this.#onMessage.bind(this), {\n signal: this.#messageAC.signal,\n });\n }\n\n #onMessage({ data }) {\n if (data.targetName !== this.sourceName) {\n return;\n }\n if (data.stream) {\n this.#processStreamMessage(data);\n return;\n }\n if (data.callback) {\n const callbackId = data.callbackId;\n const capability = this.callbackCapabilities[callbackId];\n if (!capability) {\n throw new Error(`Cannot resolve callback ${callbackId}`);\n }\n delete this.callbackCapabilities[callbackId];\n\n if (data.callback === CallbackKind.DATA) {\n capability.resolve(data.data);\n } else if (data.callback === CallbackKind.ERROR) {\n capability.reject(wrapReason(data.reason));\n } else {\n throw new Error(\"Unexpected callback case\");\n }\n return;\n }\n const action = this.actionHandler[data.action];\n if (!action) {\n throw new Error(`Unknown action from worker: ${data.action}`);\n }\n if (data.callbackId) {\n const sourceName = this.sourceName,\n targetName = data.sourceName,\n comObj = this.comObj;\n\n Promise.try(action, data.data).then(\n function (result) {\n comObj.postMessage({\n sourceName,\n targetName,\n callback: CallbackKind.DATA,\n callbackId: data.callbackId,\n data: result,\n });\n },\n function (reason) {\n comObj.postMessage({\n sourceName,\n targetName,\n callback: CallbackKind.ERROR,\n callbackId: data.callbackId,\n reason: wrapReason(reason),\n });\n }\n );\n return;\n }\n if (data.streamId) {\n this.#createStreamSink(data);\n return;\n }\n action(data.data);\n }\n\n on(actionName, handler) {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n assert(\n typeof handler === \"function\",\n 'MessageHandler.on: Expected \"handler\" to be a function.'\n );\n }\n const ah = this.actionHandler;\n if (ah[actionName]) {\n throw new Error(`There is already an actionName called \"${actionName}\"`);\n }\n ah[actionName] = handler;\n }\n\n /**\n * Sends a message to the comObj to invoke the action with the supplied data.\n * @param {string} actionName - Action to call.\n * @param {JSON} data - JSON data to send.\n * @param {Array} [transfers] - List of transfers/ArrayBuffers.\n */\n send(actionName, data, transfers) {\n this.comObj.postMessage(\n {\n sourceName: this.sourceName,\n targetName: this.targetName,\n action: actionName,\n data,\n },\n transfers\n );\n }\n\n /**\n * Sends a message to the comObj to invoke the action with the supplied data.\n * Expects that the other side will callback with the response.\n * @param {string} actionName - Action to call.\n * @param {JSON} data - JSON data to send.\n * @param {Array} [transfers] - List of transfers/ArrayBuffers.\n * @returns {Promise} Promise to be resolved with response data.\n */\n sendWithPromise(actionName, data, transfers) {\n const callbackId = this.callbackId++;\n const capability = Promise.withResolvers();\n this.callbackCapabilities[callbackId] = capability;\n try {\n this.comObj.postMessage(\n {\n sourceName: this.sourceName,\n targetName: this.targetName,\n action: actionName,\n callbackId,\n data,\n },\n transfers\n );\n } catch (ex) {\n capability.reject(ex);\n }\n return capability.promise;\n }\n\n /**\n * Sends a message to the comObj to invoke the action with the supplied data.\n * Expect that the other side will callback to signal 'start_complete'.\n * @param {string} actionName - Action to call.\n * @param {JSON} data - JSON data to send.\n * @param {Object} queueingStrategy - Strategy to signal backpressure based on\n * internal queue.\n * @param {Array} [transfers] - List of transfers/ArrayBuffers.\n * @returns {ReadableStream} ReadableStream to read data in chunks.\n */\n sendWithStream(actionName, data, queueingStrategy, transfers) {\n const streamId = this.streamId++,\n sourceName = this.sourceName,\n targetName = this.targetName,\n comObj = this.comObj;\n\n return new ReadableStream(\n {\n start: controller => {\n const startCapability = Promise.withResolvers();\n this.streamControllers[streamId] = {\n controller,\n startCall: startCapability,\n pullCall: null,\n cancelCall: null,\n isClosed: false,\n };\n comObj.postMessage(\n {\n sourceName,\n targetName,\n action: actionName,\n streamId,\n data,\n desiredSize: controller.desiredSize,\n },\n transfers\n );\n // Return Promise for Async process, to signal success/failure.\n return startCapability.promise;\n },\n\n pull: controller => {\n const pullCapability = Promise.withResolvers();\n this.streamControllers[streamId].pullCall = pullCapability;\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.PULL,\n streamId,\n desiredSize: controller.desiredSize,\n });\n // Returning Promise will not call \"pull\"\n // again until current pull is resolved.\n return pullCapability.promise;\n },\n\n cancel: reason => {\n assert(reason instanceof Error, \"cancel must have a valid reason\");\n const cancelCapability = Promise.withResolvers();\n this.streamControllers[streamId].cancelCall = cancelCapability;\n this.streamControllers[streamId].isClosed = true;\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.CANCEL,\n streamId,\n reason: wrapReason(reason),\n });\n // Return Promise to signal success or failure.\n return cancelCapability.promise;\n },\n },\n queueingStrategy\n );\n }\n\n #createStreamSink(data) {\n const streamId = data.streamId,\n sourceName = this.sourceName,\n targetName = data.sourceName,\n comObj = this.comObj;\n const self = this,\n action = this.actionHandler[data.action];\n\n const streamSink = {\n enqueue(chunk, size = 1, transfers) {\n if (this.isCancelled) {\n return;\n }\n const lastDesiredSize = this.desiredSize;\n this.desiredSize -= size;\n // Enqueue decreases the desiredSize property of sink,\n // so when it changes from positive to negative,\n // set ready as unresolved promise.\n if (lastDesiredSize > 0 && this.desiredSize <= 0) {\n this.sinkCapability = Promise.withResolvers();\n this.ready = this.sinkCapability.promise;\n }\n comObj.postMessage(\n {\n sourceName,\n targetName,\n stream: StreamKind.ENQUEUE,\n streamId,\n chunk,\n },\n transfers\n );\n },\n\n close() {\n if (this.isCancelled) {\n return;\n }\n this.isCancelled = true;\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.CLOSE,\n streamId,\n });\n delete self.streamSinks[streamId];\n },\n\n error(reason) {\n assert(reason instanceof Error, \"error must have a valid reason\");\n if (this.isCancelled) {\n return;\n }\n this.isCancelled = true;\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.ERROR,\n streamId,\n reason: wrapReason(reason),\n });\n },\n\n sinkCapability: Promise.withResolvers(),\n onPull: null,\n onCancel: null,\n isCancelled: false,\n desiredSize: data.desiredSize,\n ready: null,\n };\n\n streamSink.sinkCapability.resolve();\n streamSink.ready = streamSink.sinkCapability.promise;\n this.streamSinks[streamId] = streamSink;\n\n Promise.try(action, data.data, streamSink).then(\n function () {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.START_COMPLETE,\n streamId,\n success: true,\n });\n },\n function (reason) {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.START_COMPLETE,\n streamId,\n reason: wrapReason(reason),\n });\n }\n );\n }\n\n #processStreamMessage(data) {\n const streamId = data.streamId,\n sourceName = this.sourceName,\n targetName = data.sourceName,\n comObj = this.comObj;\n const streamController = this.streamControllers[streamId],\n streamSink = this.streamSinks[streamId];\n\n switch (data.stream) {\n case StreamKind.START_COMPLETE:\n if (data.success) {\n streamController.startCall.resolve();\n } else {\n streamController.startCall.reject(wrapReason(data.reason));\n }\n break;\n case StreamKind.PULL_COMPLETE:\n if (data.success) {\n streamController.pullCall.resolve();\n } else {\n streamController.pullCall.reject(wrapReason(data.reason));\n }\n break;\n case StreamKind.PULL:\n // Ignore any pull after close is called.\n if (!streamSink) {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.PULL_COMPLETE,\n streamId,\n success: true,\n });\n break;\n }\n // Pull increases the desiredSize property of sink, so when it changes\n // from negative to positive, set ready property as resolved promise.\n if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {\n streamSink.sinkCapability.resolve();\n }\n // Reset desiredSize property of sink on every pull.\n streamSink.desiredSize = data.desiredSize;\n\n Promise.try(streamSink.onPull || onFn).then(\n function () {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.PULL_COMPLETE,\n streamId,\n success: true,\n });\n },\n function (reason) {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.PULL_COMPLETE,\n streamId,\n reason: wrapReason(reason),\n });\n }\n );\n break;\n case StreamKind.ENQUEUE:\n assert(streamController, \"enqueue should have stream controller\");\n if (streamController.isClosed) {\n break;\n }\n streamController.controller.enqueue(data.chunk);\n break;\n case StreamKind.CLOSE:\n assert(streamController, \"close should have stream controller\");\n if (streamController.isClosed) {\n break;\n }\n streamController.isClosed = true;\n streamController.controller.close();\n this.#deleteStreamController(streamController, streamId);\n break;\n case StreamKind.ERROR:\n assert(streamController, \"error should have stream controller\");\n streamController.controller.error(wrapReason(data.reason));\n this.#deleteStreamController(streamController, streamId);\n break;\n case StreamKind.CANCEL_COMPLETE:\n if (data.success) {\n streamController.cancelCall.resolve();\n } else {\n streamController.cancelCall.reject(wrapReason(data.reason));\n }\n this.#deleteStreamController(streamController, streamId);\n break;\n case StreamKind.CANCEL:\n if (!streamSink) {\n break;\n }\n const dataReason = wrapReason(data.reason);\n\n Promise.try(streamSink.onCancel || onFn, dataReason).then(\n function () {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.CANCEL_COMPLETE,\n streamId,\n success: true,\n });\n },\n function (reason) {\n comObj.postMessage({\n sourceName,\n targetName,\n stream: StreamKind.CANCEL_COMPLETE,\n streamId,\n reason: wrapReason(reason),\n });\n }\n );\n streamSink.sinkCapability.reject(dataReason);\n streamSink.isCancelled = true;\n delete this.streamSinks[streamId];\n break;\n default:\n throw new Error(\"Unexpected stream case\");\n }\n }\n\n async #deleteStreamController(streamController, streamId) {\n // Delete the `streamController` only when the start, pull, and cancel\n // capabilities have settled, to prevent `TypeError`s.\n await Promise.allSettled([\n streamController.startCall?.promise,\n streamController.pullCall?.promise,\n streamController.cancelCall?.promise,\n ]);\n delete this.streamControllers[streamId];\n }\n\n destroy() {\n this.#messageAC?.abort();\n this.#messageAC = null;\n }\n}\n\nexport { MessageHandler };\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { objectFromMap } from \"../shared/util.js\";\n\nclass Metadata {\n #metadataMap;\n\n #data;\n\n constructor({ parsedData, rawData }) {\n this.#metadataMap = parsedData;\n this.#data = rawData;\n }\n\n getRaw() {\n return this.#data;\n }\n\n get(name) {\n return this.#metadataMap.get(name) ?? null;\n }\n\n getAll() {\n return objectFromMap(this.#metadataMap);\n }\n\n has(name) {\n return this.#metadataMap.has(name);\n }\n}\n\nexport { Metadata };\n","/* Copyright 2020 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n info,\n objectFromMap,\n RenderingIntentFlag,\n unreachable,\n warn,\n} from \"../shared/util.js\";\nimport { MurmurHash3_64 } from \"../shared/murmurhash3.js\";\n\nconst INTERNAL = Symbol(\"INTERNAL\");\n\nclass OptionalContentGroup {\n #isDisplay = false;\n\n #isPrint = false;\n\n #userSet = false;\n\n #visible = true;\n\n constructor(renderingIntent, { name, intent, usage, rbGroups }) {\n this.#isDisplay = !!(renderingIntent & RenderingIntentFlag.DISPLAY);\n this.#isPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);\n\n this.name = name;\n this.intent = intent;\n this.usage = usage;\n this.rbGroups = rbGroups;\n }\n\n /**\n * @type {boolean}\n */\n get visible() {\n if (this.#userSet) {\n return this.#visible;\n }\n if (!this.#visible) {\n return false;\n }\n const { print, view } = this.usage;\n\n if (this.#isDisplay) {\n return view?.viewState !== \"OFF\";\n } else if (this.#isPrint) {\n return print?.printState !== \"OFF\";\n }\n return true;\n }\n\n /**\n * @ignore\n */\n _setVisible(internal, visible, userSet = false) {\n if (internal !== INTERNAL) {\n unreachable(\"Internal method `_setVisible` called.\");\n }\n this.#userSet = userSet;\n this.#visible = visible;\n }\n}\n\nclass OptionalContentConfig {\n #cachedGetHash = null;\n\n #groups = new Map();\n\n #initialHash = null;\n\n #order = null;\n\n constructor(data, renderingIntent = RenderingIntentFlag.DISPLAY) {\n this.renderingIntent = renderingIntent;\n\n this.name = null;\n this.creator = null;\n\n if (data === null) {\n return;\n }\n this.name = data.name;\n this.creator = data.creator;\n this.#order = data.order;\n for (const group of data.groups) {\n this.#groups.set(\n group.id,\n new OptionalContentGroup(renderingIntent, group)\n );\n }\n\n if (data.baseState === \"OFF\") {\n for (const group of this.#groups.values()) {\n group._setVisible(INTERNAL, false);\n }\n }\n\n for (const on of data.on) {\n this.#groups.get(on)._setVisible(INTERNAL, true);\n }\n\n for (const off of data.off) {\n this.#groups.get(off)._setVisible(INTERNAL, false);\n }\n\n // The following code must always run *last* in the constructor.\n this.#initialHash = this.getHash();\n }\n\n #evaluateVisibilityExpression(array) {\n const length = array.length;\n if (length < 2) {\n return true;\n }\n const operator = array[0];\n for (let i = 1; i < length; i++) {\n const element = array[i];\n let state;\n if (Array.isArray(element)) {\n state = this.#evaluateVisibilityExpression(element);\n } else if (this.#groups.has(element)) {\n state = this.#groups.get(element).visible;\n } else {\n warn(`Optional content group not found: ${element}`);\n return true;\n }\n switch (operator) {\n case \"And\":\n if (!state) {\n return false;\n }\n break;\n case \"Or\":\n if (state) {\n return true;\n }\n break;\n case \"Not\":\n return !state;\n default:\n return true;\n }\n }\n return operator === \"And\";\n }\n\n isVisible(group) {\n if (this.#groups.size === 0) {\n return true;\n }\n if (!group) {\n info(\"Optional content group not defined.\");\n return true;\n }\n if (group.type === \"OCG\") {\n if (!this.#groups.has(group.id)) {\n warn(`Optional content group not found: ${group.id}`);\n return true;\n }\n return this.#groups.get(group.id).visible;\n } else if (group.type === \"OCMD\") {\n // Per the spec, the expression should be preferred if available.\n if (group.expression) {\n return this.#evaluateVisibilityExpression(group.expression);\n }\n if (!group.policy || group.policy === \"AnyOn\") {\n // Default\n for (const id of group.ids) {\n if (!this.#groups.has(id)) {\n warn(`Optional content group not found: ${id}`);\n return true;\n }\n if (this.#groups.get(id).visible) {\n return true;\n }\n }\n return false;\n } else if (group.policy === \"AllOn\") {\n for (const id of group.ids) {\n if (!this.#groups.has(id)) {\n warn(`Optional content group not found: ${id}`);\n return true;\n }\n if (!this.#groups.get(id).visible) {\n return false;\n }\n }\n return true;\n } else if (group.policy === \"AnyOff\") {\n for (const id of group.ids) {\n if (!this.#groups.has(id)) {\n warn(`Optional content group not found: ${id}`);\n return true;\n }\n if (!this.#groups.get(id).visible) {\n return true;\n }\n }\n return false;\n } else if (group.policy === \"AllOff\") {\n for (const id of group.ids) {\n if (!this.#groups.has(id)) {\n warn(`Optional content group not found: ${id}`);\n return true;\n }\n if (this.#groups.get(id).visible) {\n return false;\n }\n }\n return true;\n }\n warn(`Unknown optional content policy ${group.policy}.`);\n return true;\n }\n warn(`Unknown group type ${group.type}.`);\n return true;\n }\n\n setVisibility(id, visible = true, preserveRB = true) {\n const group = this.#groups.get(id);\n if (!group) {\n warn(`Optional content group not found: ${id}`);\n return;\n }\n\n // If the visibility is about to be set to `true` and the group belongs to\n // any radiobutton groups, hide all other OCGs in these radiobutton groups,\n // provided that radiobutton state relationships are to be preserved.\n if (preserveRB && visible && group.rbGroups.length) {\n for (const rbGroup of group.rbGroups) {\n for (const otherId of rbGroup) {\n if (otherId !== id) {\n this.#groups.get(otherId)?._setVisible(INTERNAL, false, true);\n }\n }\n }\n }\n\n group._setVisible(INTERNAL, !!visible, /* userSet = */ true);\n\n this.#cachedGetHash = null;\n }\n\n setOCGState({ state, preserveRB }) {\n let operator;\n\n for (const elem of state) {\n switch (elem) {\n case \"ON\":\n case \"OFF\":\n case \"Toggle\":\n operator = elem;\n continue;\n }\n\n const group = this.#groups.get(elem);\n if (!group) {\n continue;\n }\n switch (operator) {\n case \"ON\":\n this.setVisibility(elem, true, preserveRB);\n break;\n case \"OFF\":\n this.setVisibility(elem, false, preserveRB);\n break;\n case \"Toggle\":\n this.setVisibility(elem, !group.visible, preserveRB);\n break;\n }\n }\n\n this.#cachedGetHash = null;\n }\n\n get hasInitialVisibility() {\n return this.#initialHash === null || this.getHash() === this.#initialHash;\n }\n\n getOrder() {\n if (!this.#groups.size) {\n return null;\n }\n if (this.#order) {\n return this.#order.slice();\n }\n return [...this.#groups.keys()];\n }\n\n getGroups() {\n return this.#groups.size > 0 ? objectFromMap(this.#groups) : null;\n }\n\n getGroup(id) {\n return this.#groups.get(id) || null;\n }\n\n getHash() {\n if (this.#cachedGetHash !== null) {\n return this.#cachedGetHash;\n }\n const hash = new MurmurHash3_64();\n\n for (const [id, group] of this.#groups) {\n hash.update(`${id}:${group.visible}`);\n }\n return (this.#cachedGetHash = hash.hexdigest());\n }\n}\n\nexport { OptionalContentConfig };\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"../interfaces\").IPDFStream} IPDFStream */\n/** @typedef {import(\"../interfaces\").IPDFStreamReader} IPDFStreamReader */\n// eslint-disable-next-line max-len\n/** @typedef {import(\"../interfaces\").IPDFStreamRangeReader} IPDFStreamRangeReader */\n\nimport { assert } from \"../shared/util.js\";\nimport { isPdfFile } from \"./display_utils.js\";\n\n/** @implements {IPDFStream} */\nclass PDFDataTransportStream {\n constructor(\n pdfDataRangeTransport,\n { disableRange = false, disableStream = false }\n ) {\n assert(\n pdfDataRangeTransport,\n 'PDFDataTransportStream - missing required \"pdfDataRangeTransport\" argument.'\n );\n const { length, initialData, progressiveDone, contentDispositionFilename } =\n pdfDataRangeTransport;\n\n this._queuedChunks = [];\n this._progressiveDone = progressiveDone;\n this._contentDispositionFilename = contentDispositionFilename;\n\n if (initialData?.length > 0) {\n // Prevent any possible issues by only transferring a Uint8Array that\n // completely \"utilizes\" its underlying ArrayBuffer.\n const buffer =\n initialData instanceof Uint8Array &&\n initialData.byteLength === initialData.buffer.byteLength\n ? initialData.buffer\n : new Uint8Array(initialData).buffer;\n this._queuedChunks.push(buffer);\n }\n\n this._pdfDataRangeTransport = pdfDataRangeTransport;\n this._isStreamingSupported = !disableStream;\n this._isRangeSupported = !disableRange;\n this._contentLength = length;\n\n this._fullRequestReader = null;\n this._rangeReaders = [];\n\n pdfDataRangeTransport.addRangeListener((begin, chunk) => {\n this._onReceiveData({ begin, chunk });\n });\n\n pdfDataRangeTransport.addProgressListener((loaded, total) => {\n this._onProgress({ loaded, total });\n });\n\n pdfDataRangeTransport.addProgressiveReadListener(chunk => {\n this._onReceiveData({ chunk });\n });\n\n pdfDataRangeTransport.addProgressiveDoneListener(() => {\n this._onProgressiveDone();\n });\n\n pdfDataRangeTransport.transportReady();\n }\n\n _onReceiveData({ begin, chunk }) {\n // Prevent any possible issues by only transferring a Uint8Array that\n // completely \"utilizes\" its underlying ArrayBuffer.\n const buffer =\n chunk instanceof Uint8Array &&\n chunk.byteLength === chunk.buffer.byteLength\n ? chunk.buffer\n : new Uint8Array(chunk).buffer;\n\n if (begin === undefined) {\n if (this._fullRequestReader) {\n this._fullRequestReader._enqueue(buffer);\n } else {\n this._queuedChunks.push(buffer);\n }\n } else {\n const found = this._rangeReaders.some(function (rangeReader) {\n if (rangeReader._begin !== begin) {\n return false;\n }\n rangeReader._enqueue(buffer);\n return true;\n });\n assert(\n found,\n \"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.\"\n );\n }\n }\n\n get _progressiveDataLength() {\n return this._fullRequestReader?._loaded ?? 0;\n }\n\n _onProgress(evt) {\n if (evt.total === undefined) {\n // Reporting to first range reader, if it exists.\n this._rangeReaders[0]?.onProgress?.({ loaded: evt.loaded });\n } else {\n this._fullRequestReader?.onProgress?.({\n loaded: evt.loaded,\n total: evt.total,\n });\n }\n }\n\n _onProgressiveDone() {\n this._fullRequestReader?.progressiveDone();\n this._progressiveDone = true;\n }\n\n _removeRangeReader(reader) {\n const i = this._rangeReaders.indexOf(reader);\n if (i >= 0) {\n this._rangeReaders.splice(i, 1);\n }\n }\n\n getFullReader() {\n assert(\n !this._fullRequestReader,\n \"PDFDataTransportStream.getFullReader can only be called once.\"\n );\n const queuedChunks = this._queuedChunks;\n this._queuedChunks = null;\n return new PDFDataTransportStreamReader(\n this,\n queuedChunks,\n this._progressiveDone,\n this._contentDispositionFilename\n );\n }\n\n getRangeReader(begin, end) {\n if (end <= this._progressiveDataLength) {\n return null;\n }\n const reader = new PDFDataTransportStreamRangeReader(this, begin, end);\n this._pdfDataRangeTransport.requestDataRange(begin, end);\n this._rangeReaders.push(reader);\n return reader;\n }\n\n cancelAllRequests(reason) {\n this._fullRequestReader?.cancel(reason);\n\n for (const reader of this._rangeReaders.slice(0)) {\n reader.cancel(reason);\n }\n this._pdfDataRangeTransport.abort();\n }\n}\n\n/** @implements {IPDFStreamReader} */\nclass PDFDataTransportStreamReader {\n constructor(\n stream,\n queuedChunks,\n progressiveDone = false,\n contentDispositionFilename = null\n ) {\n this._stream = stream;\n this._done = progressiveDone || false;\n this._filename = isPdfFile(contentDispositionFilename)\n ? contentDispositionFilename\n : null;\n this._queuedChunks = queuedChunks || [];\n this._loaded = 0;\n for (const chunk of this._queuedChunks) {\n this._loaded += chunk.byteLength;\n }\n this._requests = [];\n this._headersReady = Promise.resolve();\n stream._fullRequestReader = this;\n\n this.onProgress = null;\n }\n\n _enqueue(chunk) {\n if (this._done) {\n return; // Ignore new data.\n }\n if (this._requests.length > 0) {\n const requestCapability = this._requests.shift();\n requestCapability.resolve({ value: chunk, done: false });\n } else {\n this._queuedChunks.push(chunk);\n }\n this._loaded += chunk.byteLength;\n }\n\n get headersReady() {\n return this._headersReady;\n }\n\n get filename() {\n return this._filename;\n }\n\n get isRangeSupported() {\n return this._stream._isRangeSupported;\n }\n\n get isStreamingSupported() {\n return this._stream._isStreamingSupported;\n }\n\n get contentLength() {\n return this._stream._contentLength;\n }\n\n async read() {\n if (this._queuedChunks.length > 0) {\n const chunk = this._queuedChunks.shift();\n return { value: chunk, done: false };\n }\n if (this._done) {\n return { value: undefined, done: true };\n }\n const requestCapability = Promise.withResolvers();\n this._requests.push(requestCapability);\n return requestCapability.promise;\n }\n\n cancel(reason) {\n this._done = true;\n for (const requestCapability of this._requests) {\n requestCapability.resolve({ value: undefined, done: true });\n }\n this._requests.length = 0;\n }\n\n progressiveDone() {\n if (this._done) {\n return;\n }\n this._done = true;\n }\n}\n\n/** @implements {IPDFStreamRangeReader} */\nclass PDFDataTransportStreamRangeReader {\n constructor(stream, begin, end) {\n this._stream = stream;\n this._begin = begin;\n this._end = end;\n this._queuedChunk = null;\n this._requests = [];\n this._done = false;\n\n this.onProgress = null;\n }\n\n _enqueue(chunk) {\n if (this._done) {\n return; // ignore new data\n }\n if (this._requests.length === 0) {\n this._queuedChunk = chunk;\n } else {\n const requestsCapability = this._requests.shift();\n requestsCapability.resolve({ value: chunk, done: false });\n for (const requestCapability of this._requests) {\n requestCapability.resolve({ value: undefined, done: true });\n }\n this._requests.length = 0;\n }\n this._done = true;\n this._stream._removeRangeReader(this);\n }\n\n get isStreamingSupported() {\n return false;\n }\n\n async read() {\n if (this._queuedChunk) {\n const chunk = this._queuedChunk;\n this._queuedChunk = null;\n return { value: chunk, done: false };\n }\n if (this._done) {\n return { value: undefined, done: true };\n }\n const requestCapability = Promise.withResolvers();\n this._requests.push(requestCapability);\n return requestCapability.promise;\n }\n\n cancel(reason) {\n this._done = true;\n for (const requestCapability of this._requests) {\n requestCapability.resolve({ value: undefined, done: true });\n }\n this._requests.length = 0;\n this._stream._removeRangeReader(this);\n }\n}\n\nexport { PDFDataTransportStream };\n","/* Copyright 2017 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { stringToBytes } from \"../shared/util.js\";\n\n// This getFilenameFromContentDispositionHeader function is adapted from\n// https://github.com/Rob--W/open-in-browser/blob/7e2e35a38b8b4e981b11da7b2f01df0149049e92/extension/content-disposition.js\n// with the following changes:\n// - Modified to conform to PDF.js's coding style.\n// - Move return to the end of the function to prevent Babel from dropping the\n// function declarations.\n\n/**\n * Extract file name from the Content-Disposition HTTP response header.\n *\n * @param {string} contentDisposition\n * @returns {string} Filename, if found in the Content-Disposition header.\n */\nfunction getFilenameFromContentDispositionHeader(contentDisposition) {\n let needsEncodingFixup = true;\n\n // filename*=ext-value (\"ext-value\" from RFC 5987, referenced by RFC 6266).\n let tmp = toParamRegExp(\"filename\\\\*\", \"i\").exec(contentDisposition);\n if (tmp) {\n tmp = tmp[1];\n let filename = rfc2616unquote(tmp);\n filename = unescape(filename);\n filename = rfc5987decode(filename);\n filename = rfc2047decode(filename);\n return fixupEncoding(filename);\n }\n\n // Continuations (RFC 2231 section 3, referenced by RFC 5987 section 3.1).\n // filename*n*=part\n // filename*n=part\n tmp = rfc2231getparam(contentDisposition);\n if (tmp) {\n // RFC 2047, section\n const filename = rfc2047decode(tmp);\n return fixupEncoding(filename);\n }\n\n // filename=value (RFC 5987, section 4.1).\n tmp = toParamRegExp(\"filename\", \"i\").exec(contentDisposition);\n if (tmp) {\n tmp = tmp[1];\n let filename = rfc2616unquote(tmp);\n filename = rfc2047decode(filename);\n return fixupEncoding(filename);\n }\n\n // After this line there are only function declarations. We cannot put\n // \"return\" here for readability because babel would then drop the function\n // declarations...\n function toParamRegExp(attributePattern, flags) {\n return new RegExp(\n \"(?:^|;)\\\\s*\" +\n attributePattern +\n \"\\\\s*=\\\\s*\" +\n // Captures: value = token | quoted-string\n // (RFC 2616, section 3.6 and referenced by RFC 6266 4.1)\n \"(\" +\n '[^\";\\\\s][^;\\\\s]*' +\n \"|\" +\n '\"(?:[^\"\\\\\\\\]|\\\\\\\\\"?)+\"?' +\n \")\",\n flags\n );\n }\n function textdecode(encoding, value) {\n if (encoding) {\n if (!/^[\\x00-\\xFF]+$/.test(value)) {\n return value;\n }\n try {\n const decoder = new TextDecoder(encoding, { fatal: true });\n const buffer = stringToBytes(value);\n value = decoder.decode(buffer);\n needsEncodingFixup = false;\n } catch {\n // TextDecoder constructor threw - unrecognized encoding.\n }\n }\n return value;\n }\n function fixupEncoding(value) {\n if (needsEncodingFixup && /[\\x80-\\xff]/.test(value)) {\n // Maybe multi-byte UTF-8.\n value = textdecode(\"utf-8\", value);\n if (needsEncodingFixup) {\n // Try iso-8859-1 encoding.\n value = textdecode(\"iso-8859-1\", value);\n }\n }\n return value;\n }\n function rfc2231getparam(contentDispositionStr) {\n const matches = [];\n let match;\n // Iterate over all filename*n= and filename*n*= with n being an integer\n // of at least zero. Any non-zero number must not start with '0'.\n const iter = toParamRegExp(\"filename\\\\*((?!0\\\\d)\\\\d+)(\\\\*?)\", \"ig\");\n while ((match = iter.exec(contentDispositionStr)) !== null) {\n let [, n, quot, part] = match; // eslint-disable-line prefer-const\n n = parseInt(n, 10);\n if (n in matches) {\n // Ignore anything after the invalid second filename*0.\n if (n === 0) {\n break;\n }\n continue;\n }\n matches[n] = [quot, part];\n }\n const parts = [];\n for (let n = 0; n < matches.length; ++n) {\n if (!(n in matches)) {\n // Numbers must be consecutive. Truncate when there is a hole.\n break;\n }\n let [quot, part] = matches[n]; // eslint-disable-line prefer-const\n part = rfc2616unquote(part);\n if (quot) {\n part = unescape(part);\n if (n === 0) {\n part = rfc5987decode(part);\n }\n }\n parts.push(part);\n }\n return parts.join(\"\");\n }\n function rfc2616unquote(value) {\n if (value.startsWith('\"')) {\n const parts = value.slice(1).split('\\\\\"');\n // Find the first unescaped \" and terminate there.\n for (let i = 0; i < parts.length; ++i) {\n const quotindex = parts[i].indexOf('\"');\n if (quotindex !== -1) {\n parts[i] = parts[i].slice(0, quotindex);\n parts.length = i + 1; // Truncates and stop the iteration.\n }\n parts[i] = parts[i].replaceAll(/\\\\(.)/g, \"$1\");\n }\n value = parts.join('\"');\n }\n return value;\n }\n function rfc5987decode(extvalue) {\n // Decodes \"ext-value\" from RFC 5987.\n const encodingend = extvalue.indexOf(\"'\");\n if (encodingend === -1) {\n // Some servers send \"filename*=\" without encoding 'language' prefix,\n // e.g. in https://github.com/Rob--W/open-in-browser/issues/26\n // Let's accept the value like Firefox (57) (Chrome 62 rejects it).\n return extvalue;\n }\n const encoding = extvalue.slice(0, encodingend);\n const langvalue = extvalue.slice(encodingend + 1);\n // Ignore language (RFC 5987 section 3.2.1, and RFC 6266 section 4.1 ).\n const value = langvalue.replace(/^[^']*'/, \"\");\n return textdecode(encoding, value);\n }\n function rfc2047decode(value) {\n // RFC 2047-decode the result. Firefox tried to drop support for it, but\n // backed out because some servers use it - https://bugzil.la/875615\n // Firefox's condition for decoding is here: https://searchfox.org/mozilla-central/rev/4a590a5a15e35d88a3b23dd6ac3c471cf85b04a8/netwerk/mime/nsMIMEHeaderParamImpl.cpp#742-748\n\n // We are more strict and only recognize RFC 2047-encoding if the value\n // starts with \"=?\", since then it is likely that the full value is\n // RFC 2047-encoded.\n\n // Firefox also decodes words even where RFC 2047 section 5 states:\n // \"An 'encoded-word' MUST NOT appear within a 'quoted-string'.\"\n if (!value.startsWith(\"=?\") || /[\\x00-\\x19\\x80-\\xff]/.test(value)) {\n return value;\n }\n // RFC 2047, section 2.4\n // encoded-word = \"=?\" charset \"?\" encoding \"?\" encoded-text \"?=\"\n // charset = token (but let's restrict to characters that denote a\n // possibly valid encoding).\n // encoding = q or b\n // encoded-text = any printable ASCII character other than ? or space.\n // ... but Firefox permits ? and space.\n return value.replaceAll(\n /=\\?([\\w-]*)\\?([QqBb])\\?((?:[^?]|\\?(?!=))*)\\?=/g,\n function (matches, charset, encoding, text) {\n if (encoding === \"q\" || encoding === \"Q\") {\n // RFC 2047 section 4.2.\n text = text.replaceAll(\"_\", \" \");\n text = text.replaceAll(/=([0-9a-fA-F]{2})/g, function (match, hex) {\n return String.fromCharCode(parseInt(hex, 16));\n });\n return textdecode(charset, text);\n } // else encoding is b or B - base64 (RFC 2047 section 4.1)\n try {\n text = atob(text);\n } catch {}\n return textdecode(charset, text);\n }\n );\n }\n\n return \"\";\n}\n\nexport { getFilenameFromContentDispositionHeader };\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n MissingPDFException,\n UnexpectedResponseException,\n} from \"../shared/util.js\";\nimport { getFilenameFromContentDispositionHeader } from \"./content_disposition.js\";\nimport { isPdfFile } from \"./display_utils.js\";\n\nfunction createHeaders(isHttp, httpHeaders) {\n const headers = new Headers();\n\n if (!isHttp || !httpHeaders || typeof httpHeaders !== \"object\") {\n return headers;\n }\n for (const key in httpHeaders) {\n const val = httpHeaders[key];\n if (val !== undefined) {\n headers.append(key, val);\n }\n }\n return headers;\n}\n\nfunction getResponseOrigin(url) {\n try {\n return new URL(url).origin;\n } catch {\n // `new URL()` will throw on incorrect data.\n }\n // Notably, null is distinct from \"null\" string (e.g. from file:-URLs).\n return null;\n}\n\nfunction validateRangeRequestCapabilities({\n responseHeaders,\n isHttp,\n rangeChunkSize,\n disableRange,\n}) {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n assert(\n Number.isInteger(rangeChunkSize) && rangeChunkSize > 0,\n \"rangeChunkSize must be an integer larger than zero.\"\n );\n }\n const returnValues = {\n allowRangeRequests: false,\n suggestedLength: undefined,\n };\n\n const length = parseInt(responseHeaders.get(\"Content-Length\"), 10);\n if (!Number.isInteger(length)) {\n return returnValues;\n }\n\n returnValues.suggestedLength = length;\n\n if (length <= 2 * rangeChunkSize) {\n // The file size is smaller than the size of two chunks, so it does not\n // make any sense to abort the request and retry with a range request.\n return returnValues;\n }\n\n if (disableRange || !isHttp) {\n return returnValues;\n }\n if (responseHeaders.get(\"Accept-Ranges\") !== \"bytes\") {\n return returnValues;\n }\n\n const contentEncoding = responseHeaders.get(\"Content-Encoding\") || \"identity\";\n if (contentEncoding !== \"identity\") {\n return returnValues;\n }\n\n returnValues.allowRangeRequests = true;\n return returnValues;\n}\n\nfunction extractFilenameFromHeader(responseHeaders) {\n const contentDisposition = responseHeaders.get(\"Content-Disposition\");\n if (contentDisposition) {\n let filename = getFilenameFromContentDispositionHeader(contentDisposition);\n if (filename.includes(\"%\")) {\n try {\n filename = decodeURIComponent(filename);\n } catch {}\n }\n if (isPdfFile(filename)) {\n return filename;\n }\n }\n return null;\n}\n\nfunction createResponseStatusError(status, url) {\n if (status === 404 || (status === 0 && url.startsWith(\"file:\"))) {\n return new MissingPDFException('Missing PDF \"' + url + '\".');\n }\n return new UnexpectedResponseException(\n `Unexpected server response (${status}) while retrieving PDF \"${url}\".`,\n status\n );\n}\n\nfunction validateResponseStatus(status) {\n return status === 200 || status === 206;\n}\n\nexport {\n createHeaders,\n createResponseStatusError,\n extractFilenameFromHeader,\n getResponseOrigin,\n validateRangeRequestCapabilities,\n validateResponseStatus,\n};\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AbortException, assert, warn } from \"../shared/util.js\";\nimport {\n createHeaders,\n createResponseStatusError,\n extractFilenameFromHeader,\n getResponseOrigin,\n validateRangeRequestCapabilities,\n validateResponseStatus,\n} from \"./network_utils.js\";\n\nif (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\n 'Module \"./fetch_stream.js\" shall not be used with MOZCENTRAL builds.'\n );\n}\n\nfunction createFetchOptions(headers, withCredentials, abortController) {\n return {\n method: \"GET\",\n headers,\n signal: abortController.signal,\n mode: \"cors\",\n credentials: withCredentials ? \"include\" : \"same-origin\",\n redirect: \"follow\",\n };\n}\n\nfunction getArrayBuffer(val) {\n if (val instanceof Uint8Array) {\n return val.buffer;\n }\n if (val instanceof ArrayBuffer) {\n return val;\n }\n warn(`getArrayBuffer - unexpected data format: ${val}`);\n return new Uint8Array(val).buffer;\n}\n\n/** @implements {IPDFStream} */\nclass PDFFetchStream {\n _responseOrigin = null;\n\n constructor(source) {\n this.source = source;\n this.isHttp = /^https?:/i.test(source.url);\n this.headers = createHeaders(this.isHttp, source.httpHeaders);\n\n this._fullRequestReader = null;\n this._rangeRequestReaders = [];\n }\n\n get _progressiveDataLength() {\n return this._fullRequestReader?._loaded ?? 0;\n }\n\n getFullReader() {\n assert(\n !this._fullRequestReader,\n \"PDFFetchStream.getFullReader can only be called once.\"\n );\n this._fullRequestReader = new PDFFetchStreamReader(this);\n return this._fullRequestReader;\n }\n\n getRangeReader(begin, end) {\n if (end <= this._progressiveDataLength) {\n return null;\n }\n const reader = new PDFFetchStreamRangeReader(this, begin, end);\n this._rangeRequestReaders.push(reader);\n return reader;\n }\n\n cancelAllRequests(reason) {\n this._fullRequestReader?.cancel(reason);\n\n for (const reader of this._rangeRequestReaders.slice(0)) {\n reader.cancel(reason);\n }\n }\n}\n\n/** @implements {IPDFStreamReader} */\nclass PDFFetchStreamReader {\n constructor(stream) {\n this._stream = stream;\n this._reader = null;\n this._loaded = 0;\n this._filename = null;\n const source = stream.source;\n this._withCredentials = source.withCredentials || false;\n this._contentLength = source.length;\n this._headersCapability = Promise.withResolvers();\n this._disableRange = source.disableRange || false;\n this._rangeChunkSize = source.rangeChunkSize;\n if (!this._rangeChunkSize && !this._disableRange) {\n this._disableRange = true;\n }\n\n this._abortController = new AbortController();\n this._isStreamingSupported = !source.disableStream;\n this._isRangeSupported = !source.disableRange;\n // Always create a copy of the headers.\n const headers = new Headers(stream.headers);\n\n const url = source.url;\n fetch(\n url,\n createFetchOptions(headers, this._withCredentials, this._abortController)\n )\n .then(response => {\n stream._responseOrigin = getResponseOrigin(response.url);\n\n if (!validateResponseStatus(response.status)) {\n throw createResponseStatusError(response.status, url);\n }\n this._reader = response.body.getReader();\n this._headersCapability.resolve();\n\n const responseHeaders = response.headers;\n\n const { allowRangeRequests, suggestedLength } =\n validateRangeRequestCapabilities({\n responseHeaders,\n isHttp: stream.isHttp,\n rangeChunkSize: this._rangeChunkSize,\n disableRange: this._disableRange,\n });\n\n this._isRangeSupported = allowRangeRequests;\n // Setting right content length.\n this._contentLength = suggestedLength || this._contentLength;\n\n this._filename = extractFilenameFromHeader(responseHeaders);\n\n // We need to stop reading when range is supported and streaming is\n // disabled.\n if (!this._isStreamingSupported && this._isRangeSupported) {\n this.cancel(new AbortException(\"Streaming is disabled.\"));\n }\n })\n .catch(this._headersCapability.reject);\n\n this.onProgress = null;\n }\n\n get headersReady() {\n return this._headersCapability.promise;\n }\n\n get filename() {\n return this._filename;\n }\n\n get contentLength() {\n return this._contentLength;\n }\n\n get isRangeSupported() {\n return this._isRangeSupported;\n }\n\n get isStreamingSupported() {\n return this._isStreamingSupported;\n }\n\n async read() {\n await this._headersCapability.promise;\n const { value, done } = await this._reader.read();\n if (done) {\n return { value, done };\n }\n this._loaded += value.byteLength;\n this.onProgress?.({\n loaded: this._loaded,\n total: this._contentLength,\n });\n\n return { value: getArrayBuffer(value), done: false };\n }\n\n cancel(reason) {\n this._reader?.cancel(reason);\n this._abortController.abort();\n }\n}\n\n/** @implements {IPDFStreamRangeReader} */\nclass PDFFetchStreamRangeReader {\n constructor(stream, begin, end) {\n this._stream = stream;\n this._reader = null;\n this._loaded = 0;\n const source = stream.source;\n this._withCredentials = source.withCredentials || false;\n this._readCapability = Promise.withResolvers();\n this._isStreamingSupported = !source.disableStream;\n\n this._abortController = new AbortController();\n // Always create a copy of the headers.\n const headers = new Headers(stream.headers);\n headers.append(\"Range\", `bytes=${begin}-${end - 1}`);\n\n const url = source.url;\n fetch(\n url,\n createFetchOptions(headers, this._withCredentials, this._abortController)\n )\n .then(response => {\n const responseOrigin = getResponseOrigin(response.url);\n\n if (responseOrigin !== stream._responseOrigin) {\n throw new Error(\n `Expected range response-origin \"${responseOrigin}\" to match \"${stream._responseOrigin}\".`\n );\n }\n if (!validateResponseStatus(response.status)) {\n throw createResponseStatusError(response.status, url);\n }\n this._readCapability.resolve();\n this._reader = response.body.getReader();\n })\n .catch(this._readCapability.reject);\n\n this.onProgress = null;\n }\n\n get isStreamingSupported() {\n return this._isStreamingSupported;\n }\n\n async read() {\n await this._readCapability.promise;\n const { value, done } = await this._reader.read();\n if (done) {\n return { value, done };\n }\n this._loaded += value.byteLength;\n this.onProgress?.({ loaded: this._loaded });\n\n return { value: getArrayBuffer(value), done: false };\n }\n\n cancel(reason) {\n this._reader?.cancel(reason);\n this._abortController.abort();\n }\n}\n\nexport { PDFFetchStream };\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, stringToBytes } from \"../shared/util.js\";\nimport {\n createHeaders,\n createResponseStatusError,\n extractFilenameFromHeader,\n getResponseOrigin,\n validateRangeRequestCapabilities,\n} from \"./network_utils.js\";\n\nif (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\n 'Module \"./network.js\" shall not be used with MOZCENTRAL builds.'\n );\n}\n\nconst OK_RESPONSE = 200;\nconst PARTIAL_CONTENT_RESPONSE = 206;\n\nfunction getArrayBuffer(xhr) {\n const data = xhr.response;\n if (typeof data !== \"string\") {\n return data;\n }\n return stringToBytes(data).buffer;\n}\n\nclass NetworkManager {\n _responseOrigin = null;\n\n constructor({ url, httpHeaders, withCredentials }) {\n this.url = url;\n this.isHttp = /^https?:/i.test(url);\n this.headers = createHeaders(this.isHttp, httpHeaders);\n this.withCredentials = withCredentials || false;\n\n this.currXhrId = 0;\n this.pendingRequests = Object.create(null);\n }\n\n requestRange(begin, end, listeners) {\n const args = {\n begin,\n end,\n };\n for (const prop in listeners) {\n args[prop] = listeners[prop];\n }\n return this.request(args);\n }\n\n requestFull(listeners) {\n return this.request(listeners);\n }\n\n request(args) {\n const xhr = new XMLHttpRequest();\n const xhrId = this.currXhrId++;\n const pendingRequest = (this.pendingRequests[xhrId] = { xhr });\n\n xhr.open(\"GET\", this.url);\n xhr.withCredentials = this.withCredentials;\n for (const [key, val] of this.headers) {\n xhr.setRequestHeader(key, val);\n }\n if (this.isHttp && \"begin\" in args && \"end\" in args) {\n xhr.setRequestHeader(\"Range\", `bytes=${args.begin}-${args.end - 1}`);\n pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;\n } else {\n pendingRequest.expectedStatus = OK_RESPONSE;\n }\n xhr.responseType = \"arraybuffer\";\n\n if (args.onError) {\n xhr.onerror = function (evt) {\n args.onError(xhr.status);\n };\n }\n xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);\n xhr.onprogress = this.onProgress.bind(this, xhrId);\n\n pendingRequest.onHeadersReceived = args.onHeadersReceived;\n pendingRequest.onDone = args.onDone;\n pendingRequest.onError = args.onError;\n pendingRequest.onProgress = args.onProgress;\n\n xhr.send(null);\n\n return xhrId;\n }\n\n onProgress(xhrId, evt) {\n const pendingRequest = this.pendingRequests[xhrId];\n if (!pendingRequest) {\n return; // Maybe abortRequest was called...\n }\n pendingRequest.onProgress?.(evt);\n }\n\n onStateChange(xhrId, evt) {\n const pendingRequest = this.pendingRequests[xhrId];\n if (!pendingRequest) {\n return; // Maybe abortRequest was called...\n }\n\n const xhr = pendingRequest.xhr;\n if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {\n pendingRequest.onHeadersReceived();\n delete pendingRequest.onHeadersReceived;\n }\n\n if (xhr.readyState !== 4) {\n return;\n }\n\n if (!(xhrId in this.pendingRequests)) {\n // The XHR request might have been aborted in onHeadersReceived()\n // callback, in which case we should abort request.\n return;\n }\n\n delete this.pendingRequests[xhrId];\n\n // Success status == 0 can be on ftp, file and other protocols.\n if (xhr.status === 0 && this.isHttp) {\n pendingRequest.onError?.(xhr.status);\n return;\n }\n const xhrStatus = xhr.status || OK_RESPONSE;\n\n // From http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.2:\n // \"A server MAY ignore the Range header\". This means it's possible to\n // get a 200 rather than a 206 response from a range request.\n const ok_response_on_range_request =\n xhrStatus === OK_RESPONSE &&\n pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;\n\n if (\n !ok_response_on_range_request &&\n xhrStatus !== pendingRequest.expectedStatus\n ) {\n pendingRequest.onError?.(xhr.status);\n return;\n }\n\n const chunk = getArrayBuffer(xhr);\n if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {\n const rangeHeader = xhr.getResponseHeader(\"Content-Range\");\n const matches = /bytes (\\d+)-(\\d+)\\/(\\d+)/.exec(rangeHeader);\n pendingRequest.onDone({\n begin: parseInt(matches[1], 10),\n chunk,\n });\n } else if (chunk) {\n pendingRequest.onDone({\n begin: 0,\n chunk,\n });\n } else {\n pendingRequest.onError?.(xhr.status);\n }\n }\n\n getRequestXhr(xhrId) {\n return this.pendingRequests[xhrId].xhr;\n }\n\n isPendingRequest(xhrId) {\n return xhrId in this.pendingRequests;\n }\n\n abortRequest(xhrId) {\n const xhr = this.pendingRequests[xhrId].xhr;\n delete this.pendingRequests[xhrId];\n xhr.abort();\n }\n}\n\n/** @implements {IPDFStream} */\nclass PDFNetworkStream {\n constructor(source) {\n this._source = source;\n this._manager = new NetworkManager(source);\n this._rangeChunkSize = source.rangeChunkSize;\n this._fullRequestReader = null;\n this._rangeRequestReaders = [];\n }\n\n _onRangeRequestReaderClosed(reader) {\n const i = this._rangeRequestReaders.indexOf(reader);\n if (i >= 0) {\n this._rangeRequestReaders.splice(i, 1);\n }\n }\n\n getFullReader() {\n assert(\n !this._fullRequestReader,\n \"PDFNetworkStream.getFullReader can only be called once.\"\n );\n this._fullRequestReader = new PDFNetworkStreamFullRequestReader(\n this._manager,\n this._source\n );\n return this._fullRequestReader;\n }\n\n getRangeReader(begin, end) {\n const reader = new PDFNetworkStreamRangeRequestReader(\n this._manager,\n begin,\n end\n );\n reader.onClosed = this._onRangeRequestReaderClosed.bind(this);\n this._rangeRequestReaders.push(reader);\n return reader;\n }\n\n cancelAllRequests(reason) {\n this._fullRequestReader?.cancel(reason);\n\n for (const reader of this._rangeRequestReaders.slice(0)) {\n reader.cancel(reason);\n }\n }\n}\n\n/** @implements {IPDFStreamReader} */\nclass PDFNetworkStreamFullRequestReader {\n constructor(manager, source) {\n this._manager = manager;\n\n const args = {\n onHeadersReceived: this._onHeadersReceived.bind(this),\n onDone: this._onDone.bind(this),\n onError: this._onError.bind(this),\n onProgress: this._onProgress.bind(this),\n };\n this._url = source.url;\n this._fullRequestId = manager.requestFull(args);\n this._headersCapability = Promise.withResolvers();\n this._disableRange = source.disableRange || false;\n this._contentLength = source.length; // Optional\n this._rangeChunkSize = source.rangeChunkSize;\n if (!this._rangeChunkSize && !this._disableRange) {\n this._disableRange = true;\n }\n\n this._isStreamingSupported = false;\n this._isRangeSupported = false;\n\n this._cachedChunks = [];\n this._requests = [];\n this._done = false;\n this._storedError = undefined;\n this._filename = null;\n\n this.onProgress = null;\n }\n\n _onHeadersReceived() {\n const fullRequestXhrId = this._fullRequestId;\n const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);\n\n this._manager._responseOrigin = getResponseOrigin(\n fullRequestXhr.responseURL\n );\n\n const rawResponseHeaders = fullRequestXhr.getAllResponseHeaders();\n const responseHeaders = new Headers(\n rawResponseHeaders\n ? rawResponseHeaders\n .trim()\n .split(/[\\r\\n]+/)\n .map(x => {\n const [key, ...val] = x.split(\": \");\n return [key, val.join(\": \")];\n })\n : []\n );\n\n const { allowRangeRequests, suggestedLength } =\n validateRangeRequestCapabilities({\n responseHeaders,\n isHttp: this._manager.isHttp,\n rangeChunkSize: this._rangeChunkSize,\n disableRange: this._disableRange,\n });\n\n if (allowRangeRequests) {\n this._isRangeSupported = true;\n }\n // Setting right content length.\n this._contentLength = suggestedLength || this._contentLength;\n\n this._filename = extractFilenameFromHeader(responseHeaders);\n\n if (this._isRangeSupported) {\n // NOTE: by cancelling the full request, and then issuing range\n // requests, there will be an issue for sites where you can only\n // request the pdf once. However, if this is the case, then the\n // server should not be returning that it can support range requests.\n this._manager.abortRequest(fullRequestXhrId);\n }\n\n this._headersCapability.resolve();\n }\n\n _onDone(data) {\n if (data) {\n if (this._requests.length > 0) {\n const requestCapability = this._requests.shift();\n requestCapability.resolve({ value: data.chunk, done: false });\n } else {\n this._cachedChunks.push(data.chunk);\n }\n }\n this._done = true;\n if (this._cachedChunks.length > 0) {\n return;\n }\n for (const requestCapability of this._requests) {\n requestCapability.resolve({ value: undefined, done: true });\n }\n this._requests.length = 0;\n }\n\n _onError(status) {\n this._storedError = createResponseStatusError(status, this._url);\n this._headersCapability.reject(this._storedError);\n for (const requestCapability of this._requests) {\n requestCapability.reject(this._storedError);\n }\n this._requests.length = 0;\n this._cachedChunks.length = 0;\n }\n\n _onProgress(evt) {\n this.onProgress?.({\n loaded: evt.loaded,\n total: evt.lengthComputable ? evt.total : this._contentLength,\n });\n }\n\n get filename() {\n return this._filename;\n }\n\n get isRangeSupported() {\n return this._isRangeSupported;\n }\n\n get isStreamingSupported() {\n return this._isStreamingSupported;\n }\n\n get contentLength() {\n return this._contentLength;\n }\n\n get headersReady() {\n return this._headersCapability.promise;\n }\n\n async read() {\n await this._headersCapability.promise;\n\n if (this._storedError) {\n throw this._storedError;\n }\n if (this._cachedChunks.length > 0) {\n const chunk = this._cachedChunks.shift();\n return { value: chunk, done: false };\n }\n if (this._done) {\n return { value: undefined, done: true };\n }\n const requestCapability = Promise.withResolvers();\n this._requests.push(requestCapability);\n return requestCapability.promise;\n }\n\n cancel(reason) {\n this._done = true;\n this._headersCapability.reject(reason);\n for (const requestCapability of this._requests) {\n requestCapability.resolve({ value: undefined, done: true });\n }\n this._requests.length = 0;\n if (this._manager.isPendingRequest(this._fullRequestId)) {\n this._manager.abortRequest(this._fullRequestId);\n }\n this._fullRequestReader = null;\n }\n}\n\n/** @implements {IPDFStreamRangeReader} */\nclass PDFNetworkStreamRangeRequestReader {\n constructor(manager, begin, end) {\n this._manager = manager;\n\n const args = {\n onHeadersReceived: this._onHeadersReceived.bind(this),\n onDone: this._onDone.bind(this),\n onError: this._onError.bind(this),\n onProgress: this._onProgress.bind(this),\n };\n this._url = manager.url;\n this._requestId = manager.requestRange(begin, end, args);\n this._requests = [];\n this._queuedChunk = null;\n this._done = false;\n this._storedError = undefined;\n\n this.onProgress = null;\n this.onClosed = null;\n }\n\n _onHeadersReceived() {\n const responseOrigin = getResponseOrigin(\n this._manager.getRequestXhr(this._requestId)?.responseURL\n );\n\n if (responseOrigin !== this._manager._responseOrigin) {\n this._storedError = new Error(\n `Expected range response-origin \"${responseOrigin}\" to match \"${this._manager._responseOrigin}\".`\n );\n this._onError(0);\n }\n }\n\n _close() {\n this.onClosed?.(this);\n }\n\n _onDone(data) {\n const chunk = data.chunk;\n if (this._requests.length > 0) {\n const requestCapability = this._requests.shift();\n requestCapability.resolve({ value: chunk, done: false });\n } else {\n this._queuedChunk = chunk;\n }\n this._done = true;\n for (const requestCapability of this._requests) {\n requestCapability.resolve({ value: undefined, done: true });\n }\n this._requests.length = 0;\n this._close();\n }\n\n _onError(status) {\n this._storedError ??= createResponseStatusError(status, this._url);\n for (const requestCapability of this._requests) {\n requestCapability.reject(this._storedError);\n }\n this._requests.length = 0;\n this._queuedChunk = null;\n }\n\n _onProgress(evt) {\n if (!this.isStreamingSupported) {\n this.onProgress?.({ loaded: evt.loaded });\n }\n }\n\n get isStreamingSupported() {\n return false;\n }\n\n async read() {\n if (this._storedError) {\n throw this._storedError;\n }\n if (this._queuedChunk !== null) {\n const chunk = this._queuedChunk;\n this._queuedChunk = null;\n return { value: chunk, done: false };\n }\n if (this._done) {\n return { value: undefined, done: true };\n }\n const requestCapability = Promise.withResolvers();\n this._requests.push(requestCapability);\n return requestCapability.promise;\n }\n\n cancel(reason) {\n this._done = true;\n for (const requestCapability of this._requests) {\n requestCapability.resolve({ value: undefined, done: true });\n }\n this._requests.length = 0;\n if (this._manager.isPendingRequest(this._requestId)) {\n this._manager.abortRequest(this._requestId);\n }\n this._close();\n }\n}\n\nexport { PDFNetworkStream };\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/* globals process */\n\nimport { AbortException, assert, MissingPDFException } from \"../shared/util.js\";\n\nif (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\n 'Module \"./node_stream.js\" shall not be used with MOZCENTRAL builds.'\n );\n}\n\nconst urlRegex = /^[a-z][a-z0-9\\-+.]+:/i;\n\nfunction parseUrlOrPath(sourceUrl) {\n if (urlRegex.test(sourceUrl)) {\n return new URL(sourceUrl);\n }\n const url = process.getBuiltinModule(\"url\");\n return new URL(url.pathToFileURL(sourceUrl));\n}\n\nclass PDFNodeStream {\n constructor(source) {\n this.source = source;\n this.url = parseUrlOrPath(source.url);\n assert(\n this.url.protocol === \"file:\",\n \"PDFNodeStream only supports file:// URLs.\"\n );\n\n this._fullRequestReader = null;\n this._rangeRequestReaders = [];\n }\n\n get _progressiveDataLength() {\n return this._fullRequestReader?._loaded ?? 0;\n }\n\n getFullReader() {\n assert(\n !this._fullRequestReader,\n \"PDFNodeStream.getFullReader can only be called once.\"\n );\n this._fullRequestReader = new PDFNodeStreamFsFullReader(this);\n return this._fullRequestReader;\n }\n\n getRangeReader(start, end) {\n if (end <= this._progressiveDataLength) {\n return null;\n }\n const rangeReader = new PDFNodeStreamFsRangeReader(this, start, end);\n this._rangeRequestReaders.push(rangeReader);\n return rangeReader;\n }\n\n cancelAllRequests(reason) {\n this._fullRequestReader?.cancel(reason);\n\n for (const reader of this._rangeRequestReaders.slice(0)) {\n reader.cancel(reason);\n }\n }\n}\n\nclass PDFNodeStreamFsFullReader {\n constructor(stream) {\n this._url = stream.url;\n this._done = false;\n this._storedError = null;\n this.onProgress = null;\n const source = stream.source;\n this._contentLength = source.length; // optional\n this._loaded = 0;\n this._filename = null;\n\n this._disableRange = source.disableRange || false;\n this._rangeChunkSize = source.rangeChunkSize;\n if (!this._rangeChunkSize && !this._disableRange) {\n this._disableRange = true;\n }\n\n this._isStreamingSupported = !source.disableStream;\n this._isRangeSupported = !source.disableRange;\n\n this._readableStream = null;\n this._readCapability = Promise.withResolvers();\n this._headersCapability = Promise.withResolvers();\n\n const fs = process.getBuiltinModule(\"fs\");\n fs.promises.lstat(this._url).then(\n stat => {\n // Setting right content length.\n this._contentLength = stat.size;\n\n this._setReadableStream(fs.createReadStream(this._url));\n this._headersCapability.resolve();\n },\n error => {\n if (error.code === \"ENOENT\") {\n error = new MissingPDFException(`Missing PDF \"${this._url}\".`);\n }\n this._storedError = error;\n this._headersCapability.reject(error);\n }\n );\n }\n\n get headersReady() {\n return this._headersCapability.promise;\n }\n\n get filename() {\n return this._filename;\n }\n\n get contentLength() {\n return this._contentLength;\n }\n\n get isRangeSupported() {\n return this._isRangeSupported;\n }\n\n get isStreamingSupported() {\n return this._isStreamingSupported;\n }\n\n async read() {\n await this._readCapability.promise;\n if (this._done) {\n return { value: undefined, done: true };\n }\n if (this._storedError) {\n throw this._storedError;\n }\n\n const chunk = this._readableStream.read();\n if (chunk === null) {\n this._readCapability = Promise.withResolvers();\n return this.read();\n }\n this._loaded += chunk.length;\n this.onProgress?.({\n loaded: this._loaded,\n total: this._contentLength,\n });\n\n // Ensure that `read()` method returns ArrayBuffer.\n const buffer = new Uint8Array(chunk).buffer;\n return { value: buffer, done: false };\n }\n\n cancel(reason) {\n // Call `this._error()` method when cancel is called\n // before _readableStream is set.\n if (!this._readableStream) {\n this._error(reason);\n return;\n }\n this._readableStream.destroy(reason);\n }\n\n _error(reason) {\n this._storedError = reason;\n this._readCapability.resolve();\n }\n\n _setReadableStream(readableStream) {\n this._readableStream = readableStream;\n readableStream.on(\"readable\", () => {\n this._readCapability.resolve();\n });\n\n readableStream.on(\"end\", () => {\n // Destroy readable to minimize resource usage.\n readableStream.destroy();\n this._done = true;\n this._readCapability.resolve();\n });\n\n readableStream.on(\"error\", reason => {\n this._error(reason);\n });\n\n // We need to stop reading when range is supported and streaming is\n // disabled.\n if (!this._isStreamingSupported && this._isRangeSupported) {\n this._error(new AbortException(\"streaming is disabled\"));\n }\n\n // Destroy ReadableStream if already in errored state.\n if (this._storedError) {\n this._readableStream.destroy(this._storedError);\n }\n }\n}\n\nclass PDFNodeStreamFsRangeReader {\n constructor(stream, start, end) {\n this._url = stream.url;\n this._done = false;\n this._storedError = null;\n this.onProgress = null;\n this._loaded = 0;\n this._readableStream = null;\n this._readCapability = Promise.withResolvers();\n const source = stream.source;\n this._isStreamingSupported = !source.disableStream;\n\n const fs = process.getBuiltinModule(\"fs\");\n this._setReadableStream(\n fs.createReadStream(this._url, { start, end: end - 1 })\n );\n }\n\n get isStreamingSupported() {\n return this._isStreamingSupported;\n }\n\n async read() {\n await this._readCapability.promise;\n if (this._done) {\n return { value: undefined, done: true };\n }\n if (this._storedError) {\n throw this._storedError;\n }\n\n const chunk = this._readableStream.read();\n if (chunk === null) {\n this._readCapability = Promise.withResolvers();\n return this.read();\n }\n this._loaded += chunk.length;\n this.onProgress?.({ loaded: this._loaded });\n\n // Ensure that `read()` method returns ArrayBuffer.\n const buffer = new Uint8Array(chunk).buffer;\n return { value: buffer, done: false };\n }\n\n cancel(reason) {\n // Call `this._error()` method when cancel is called\n // before _readableStream is set.\n if (!this._readableStream) {\n this._error(reason);\n return;\n }\n this._readableStream.destroy(reason);\n }\n\n _error(reason) {\n this._storedError = reason;\n this._readCapability.resolve();\n }\n\n _setReadableStream(readableStream) {\n this._readableStream = readableStream;\n readableStream.on(\"readable\", () => {\n this._readCapability.resolve();\n });\n\n readableStream.on(\"end\", () => {\n // Destroy readableStream to minimize resource usage.\n readableStream.destroy();\n this._done = true;\n this._readCapability.resolve();\n });\n\n readableStream.on(\"error\", reason => {\n this._error(reason);\n });\n\n // Destroy readableStream if already in errored state.\n if (this._storedError) {\n this._readableStream.destroy(this._storedError);\n }\n }\n}\n\nexport { PDFNodeStream };\n","/* Copyright 2015 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./display_utils\").PageViewport} PageViewport */\n/** @typedef {import(\"./api\").TextContent} TextContent */\n\nimport {\n AbortException,\n FeatureTest,\n shadow,\n Util,\n warn,\n} from \"../shared/util.js\";\nimport { setLayerDimensions } from \"./display_utils.js\";\n\n/**\n * @typedef {Object} TextLayerParameters\n * @property {ReadableStream | TextContent} textContentSource - Text content to\n * render, i.e. the value returned by the page's `streamTextContent` or\n * `getTextContent` method.\n * @property {HTMLElement} container - The DOM node that will contain the text\n * runs.\n * @property {PageViewport} viewport - The target viewport to properly layout\n * the text runs.\n */\n\n/**\n * @typedef {Object} TextLayerUpdateParameters\n * @property {PageViewport} viewport - The target viewport to properly layout\n * the text runs.\n * @property {function} [onBefore] - Callback invoked before the textLayer is\n * updated in the DOM.\n */\n\nconst MAX_TEXT_DIVS_TO_RENDER = 100000;\nconst DEFAULT_FONT_SIZE = 30;\nconst DEFAULT_FONT_ASCENT = 0.8;\n\nclass TextLayer {\n #capability = Promise.withResolvers();\n\n #container = null;\n\n #disableProcessItems = false;\n\n #fontInspectorEnabled = !!globalThis.FontInspector?.enabled;\n\n #lang = null;\n\n #layoutTextParams = null;\n\n #pageHeight = 0;\n\n #pageWidth = 0;\n\n #reader = null;\n\n #rootContainer = null;\n\n #rotation = 0;\n\n #scale = 0;\n\n #styleCache = Object.create(null);\n\n #textContentItemsStr = [];\n\n #textContentSource = null;\n\n #textDivs = [];\n\n #textDivProperties = new WeakMap();\n\n #transform = null;\n\n static #ascentCache = new Map();\n\n static #canvasContexts = new Map();\n\n static #canvasCtxFonts = new WeakMap();\n\n static #minFontSize = null;\n\n static #pendingTextLayers = new Set();\n\n /**\n * @param {TextLayerParameters} options\n */\n constructor({ textContentSource, container, viewport }) {\n if (textContentSource instanceof ReadableStream) {\n this.#textContentSource = textContentSource;\n } else if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) &&\n typeof textContentSource === \"object\"\n ) {\n this.#textContentSource = new ReadableStream({\n start(controller) {\n controller.enqueue(textContentSource);\n controller.close();\n },\n });\n } else {\n throw new Error('No \"textContentSource\" parameter specified.');\n }\n this.#container = this.#rootContainer = container;\n\n this.#scale = viewport.scale * (globalThis.devicePixelRatio || 1);\n this.#rotation = viewport.rotation;\n this.#layoutTextParams = {\n div: null,\n properties: null,\n ctx: null,\n };\n const { pageWidth, pageHeight, pageX, pageY } = viewport.rawDims;\n this.#transform = [1, 0, 0, -1, -pageX, pageY + pageHeight];\n this.#pageWidth = pageWidth;\n this.#pageHeight = pageHeight;\n\n TextLayer.#ensureMinFontSizeComputed();\n\n setLayerDimensions(container, viewport);\n\n // Always clean-up the temporary canvas once rendering is no longer pending.\n this.#capability.promise\n .finally(() => {\n TextLayer.#pendingTextLayers.delete(this);\n this.#layoutTextParams = null;\n this.#styleCache = null;\n })\n .catch(() => {\n // Avoid \"Uncaught promise\" messages in the console.\n });\n\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n // For testing purposes.\n Object.defineProperty(this, \"pageWidth\", {\n get() {\n return this.#pageWidth;\n },\n });\n Object.defineProperty(this, \"pageHeight\", {\n get() {\n return this.#pageHeight;\n },\n });\n }\n }\n\n static get fontFamilyMap() {\n const { isWindows, isFirefox } = FeatureTest.platform;\n return shadow(\n this,\n \"fontFamilyMap\",\n new Map([\n [\n \"sans-serif\",\n `${isWindows && isFirefox ? \"Calibri, \" : \"\"}sans-serif`,\n ],\n [\n \"monospace\",\n `${isWindows && isFirefox ? \"Lucida Console, \" : \"\"}monospace`,\n ],\n ])\n );\n }\n\n /**\n * Render the textLayer.\n * @returns {Promise}\n */\n render() {\n const pump = () => {\n this.#reader.read().then(({ value, done }) => {\n if (done) {\n this.#capability.resolve();\n return;\n }\n this.#lang ??= value.lang;\n Object.assign(this.#styleCache, value.styles);\n this.#processItems(value.items);\n pump();\n }, this.#capability.reject);\n };\n this.#reader = this.#textContentSource.getReader();\n TextLayer.#pendingTextLayers.add(this);\n pump();\n\n return this.#capability.promise;\n }\n\n /**\n * Update a previously rendered textLayer, if necessary.\n * @param {TextLayerUpdateParameters} options\n * @returns {undefined}\n */\n update({ viewport, onBefore = null }) {\n const scale = viewport.scale * (globalThis.devicePixelRatio || 1);\n const rotation = viewport.rotation;\n\n if (rotation !== this.#rotation) {\n onBefore?.();\n this.#rotation = rotation;\n setLayerDimensions(this.#rootContainer, { rotation });\n }\n\n if (scale !== this.#scale) {\n onBefore?.();\n this.#scale = scale;\n const params = {\n div: null,\n properties: null,\n ctx: TextLayer.#getCtx(this.#lang),\n };\n for (const div of this.#textDivs) {\n params.properties = this.#textDivProperties.get(div);\n params.div = div;\n this.#layout(params);\n }\n }\n }\n\n /**\n * Cancel rendering of the textLayer.\n * @returns {undefined}\n */\n cancel() {\n const abortEx = new AbortException(\"TextLayer task cancelled.\");\n\n this.#reader?.cancel(abortEx).catch(() => {\n // Avoid \"Uncaught promise\" messages in the console.\n });\n this.#reader = null;\n\n this.#capability.reject(abortEx);\n }\n\n /**\n * @type {Array} HTML elements that correspond to the text items\n * of the textContent input.\n * This is output and will initially be set to an empty array.\n */\n get textDivs() {\n return this.#textDivs;\n }\n\n /**\n * @type {Array} Strings that correspond to the `str` property of\n * the text items of the textContent input.\n * This is output and will initially be set to an empty array\n */\n get textContentItemsStr() {\n return this.#textContentItemsStr;\n }\n\n #processItems(items) {\n if (this.#disableProcessItems) {\n return;\n }\n this.#layoutTextParams.ctx ??= TextLayer.#getCtx(this.#lang);\n\n const textDivs = this.#textDivs,\n textContentItemsStr = this.#textContentItemsStr;\n\n for (const item of items) {\n // No point in rendering many divs as it would make the browser\n // unusable even after the divs are rendered.\n if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) {\n warn(\"Ignoring additional textDivs for performance reasons.\");\n\n this.#disableProcessItems = true; // Avoid multiple warnings for one page.\n return;\n }\n\n if (item.str === undefined) {\n if (\n item.type === \"beginMarkedContentProps\" ||\n item.type === \"beginMarkedContent\"\n ) {\n const parent = this.#container;\n this.#container = document.createElement(\"span\");\n this.#container.classList.add(\"markedContent\");\n if (item.id !== null) {\n this.#container.setAttribute(\"id\", `${item.id}`);\n }\n parent.append(this.#container);\n } else if (item.type === \"endMarkedContent\") {\n this.#container = this.#container.parentNode;\n }\n continue;\n }\n textContentItemsStr.push(item.str);\n this.#appendText(item);\n }\n }\n\n #appendText(geom) {\n // Initialize all used properties to keep the caches monomorphic.\n const textDiv = document.createElement(\"span\");\n const textDivProperties = {\n angle: 0,\n canvasWidth: 0,\n hasText: geom.str !== \"\",\n hasEOL: geom.hasEOL,\n fontSize: 0,\n };\n this.#textDivs.push(textDiv);\n\n const tx = Util.transform(this.#transform, geom.transform);\n let angle = Math.atan2(tx[1], tx[0]);\n const style = this.#styleCache[geom.fontName];\n if (style.vertical) {\n angle += Math.PI / 2;\n }\n\n let fontFamily =\n (this.#fontInspectorEnabled && style.fontSubstitution) ||\n style.fontFamily;\n\n // Workaround for bug 1922063.\n fontFamily = TextLayer.fontFamilyMap.get(fontFamily) || fontFamily;\n const fontHeight = Math.hypot(tx[2], tx[3]);\n const fontAscent =\n fontHeight * TextLayer.#getAscent(fontFamily, this.#lang);\n\n let left, top;\n if (angle === 0) {\n left = tx[4];\n top = tx[5] - fontAscent;\n } else {\n left = tx[4] + fontAscent * Math.sin(angle);\n top = tx[5] - fontAscent * Math.cos(angle);\n }\n\n const scaleFactorStr = \"calc(var(--scale-factor)*\";\n const divStyle = textDiv.style;\n // Setting the style properties individually, rather than all at once,\n // should be OK since the `textDiv` isn't appended to the document yet.\n if (this.#container === this.#rootContainer) {\n divStyle.left = `${((100 * left) / this.#pageWidth).toFixed(2)}%`;\n divStyle.top = `${((100 * top) / this.#pageHeight).toFixed(2)}%`;\n } else {\n // We're in a marked content span, hence we can't use percents.\n divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`;\n divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`;\n }\n // We multiply the font size by #minFontSize, and then #layout will\n // scale the element by 1/#minFontSize. This allows us to effectively\n // ignore the minimum font size enforced by the browser, so that the text\n // layer s can always match the size of the text in the canvas.\n divStyle.fontSize = `${scaleFactorStr}${(TextLayer.#minFontSize * fontHeight).toFixed(2)}px)`;\n divStyle.fontFamily = fontFamily;\n\n textDivProperties.fontSize = fontHeight;\n\n // Keeps screen readers from pausing on every new text span.\n textDiv.setAttribute(\"role\", \"presentation\");\n\n textDiv.textContent = geom.str;\n // geom.dir may be 'ttb' for vertical texts.\n textDiv.dir = geom.dir;\n\n // `fontName` is only used by the FontInspector, and we only use `dataset`\n // here to make the font name available in the debugger.\n if (this.#fontInspectorEnabled) {\n textDiv.dataset.fontName =\n style.fontSubstitutionLoadedName || geom.fontName;\n }\n if (angle !== 0) {\n textDivProperties.angle = angle * (180 / Math.PI);\n }\n // We don't bother scaling single-char text divs, because it has very\n // little effect on text highlighting. This makes scrolling on docs with\n // lots of such divs a lot faster.\n let shouldScaleText = false;\n if (geom.str.length > 1) {\n shouldScaleText = true;\n } else if (geom.str !== \" \" && geom.transform[0] !== geom.transform[3]) {\n const absScaleX = Math.abs(geom.transform[0]),\n absScaleY = Math.abs(geom.transform[3]);\n // When the horizontal/vertical scaling differs significantly, also scale\n // even single-char text to improve highlighting (fixes issue11713.pdf).\n if (\n absScaleX !== absScaleY &&\n Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5\n ) {\n shouldScaleText = true;\n }\n }\n if (shouldScaleText) {\n textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width;\n }\n this.#textDivProperties.set(textDiv, textDivProperties);\n\n // Finally, layout and append the text to the DOM.\n this.#layoutTextParams.div = textDiv;\n this.#layoutTextParams.properties = textDivProperties;\n this.#layout(this.#layoutTextParams);\n\n if (textDivProperties.hasText) {\n this.#container.append(textDiv);\n }\n if (textDivProperties.hasEOL) {\n const br = document.createElement(\"br\");\n br.setAttribute(\"role\", \"presentation\");\n this.#container.append(br);\n }\n }\n\n #layout(params) {\n const { div, properties, ctx } = params;\n const { style } = div;\n\n let transform = \"\";\n if (TextLayer.#minFontSize > 1) {\n transform = `scale(${1 / TextLayer.#minFontSize})`;\n }\n\n if (properties.canvasWidth !== 0 && properties.hasText) {\n const { fontFamily } = style;\n const { canvasWidth, fontSize } = properties;\n\n TextLayer.#ensureCtxFont(ctx, fontSize * this.#scale, fontFamily);\n // Only measure the width for multi-char text divs, see `appendText`.\n const { width } = ctx.measureText(div.textContent);\n\n if (width > 0) {\n transform = `scaleX(${(canvasWidth * this.#scale) / width}) ${transform}`;\n }\n }\n if (properties.angle !== 0) {\n transform = `rotate(${properties.angle}deg) ${transform}`;\n }\n if (transform.length > 0) {\n style.transform = transform;\n }\n }\n\n /**\n * Clean-up global textLayer data.\n * @returns {undefined}\n */\n static cleanup() {\n if (this.#pendingTextLayers.size > 0) {\n return;\n }\n this.#ascentCache.clear();\n\n for (const { canvas } of this.#canvasContexts.values()) {\n canvas.remove();\n }\n this.#canvasContexts.clear();\n }\n\n static #getCtx(lang = null) {\n let ctx = this.#canvasContexts.get((lang ||= \"\"));\n if (!ctx) {\n // We don't use an OffscreenCanvas here because we use serif/sans serif\n // fonts with it and they depends on the locale.\n // In Firefox, the element get a lang attribute that depends on\n // what Fluent returns for the locale and the OffscreenCanvas uses\n // the OS locale.\n // Those two locales can be different and consequently the used fonts will\n // be different (see bug 1869001).\n // Ideally, we should use in the text layer the fonts we've in the pdf (or\n // their replacements when they aren't embedded) and then we can use an\n // OffscreenCanvas.\n const canvas = document.createElement(\"canvas\");\n canvas.className = \"hiddenCanvasElement\";\n canvas.lang = lang;\n document.body.append(canvas);\n ctx = canvas.getContext(\"2d\", {\n alpha: false,\n willReadFrequently: true,\n });\n this.#canvasContexts.set(lang, ctx);\n\n // Also, initialize state for the `#ensureCtxFont` method.\n this.#canvasCtxFonts.set(ctx, { size: 0, family: \"\" });\n }\n return ctx;\n }\n\n static #ensureCtxFont(ctx, size, family) {\n const cached = this.#canvasCtxFonts.get(ctx);\n if (size === cached.size && family === cached.family) {\n return; // The font is already set.\n }\n ctx.font = `${size}px ${family}`;\n cached.size = size;\n cached.family = family;\n }\n\n /**\n * Compute the minimum font size enforced by the browser.\n */\n static #ensureMinFontSizeComputed() {\n if (this.#minFontSize !== null) {\n return;\n }\n const div = document.createElement(\"div\");\n div.style.opacity = 0;\n div.style.lineHeight = 1;\n div.style.fontSize = \"1px\";\n div.style.position = \"absolute\";\n div.textContent = \"X\";\n document.body.append(div);\n // In `display:block` elements contain a single line of text,\n // the height matches the line height (which, when set to 1,\n // matches the actual font size).\n this.#minFontSize = div.getBoundingClientRect().height;\n div.remove();\n }\n\n static #getAscent(fontFamily, lang) {\n const cachedAscent = this.#ascentCache.get(fontFamily);\n if (cachedAscent) {\n return cachedAscent;\n }\n const ctx = this.#getCtx(lang);\n\n ctx.canvas.width = ctx.canvas.height = DEFAULT_FONT_SIZE;\n this.#ensureCtxFont(ctx, DEFAULT_FONT_SIZE, fontFamily);\n const metrics = ctx.measureText(\"\");\n\n // Both properties aren't available by default in Firefox.\n let ascent = metrics.fontBoundingBoxAscent;\n let descent = Math.abs(metrics.fontBoundingBoxDescent);\n if (ascent) {\n const ratio = ascent / (ascent + descent);\n this.#ascentCache.set(fontFamily, ratio);\n\n ctx.canvas.width = ctx.canvas.height = 0;\n return ratio;\n }\n\n // Try basic heuristic to guess ascent/descent.\n // Draw a g with baseline at 0,0 and then get the line\n // number where a pixel has non-null red component (starting\n // from bottom).\n ctx.strokeStyle = \"red\";\n ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);\n ctx.strokeText(\"g\", 0, 0);\n let pixels = ctx.getImageData(\n 0,\n 0,\n DEFAULT_FONT_SIZE,\n DEFAULT_FONT_SIZE\n ).data;\n descent = 0;\n for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {\n if (pixels[i] > 0) {\n descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);\n break;\n }\n }\n\n // Draw an A with baseline at 0,DEFAULT_FONT_SIZE and then get the line\n // number where a pixel has non-null red component (starting\n // from top).\n ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);\n ctx.strokeText(\"A\", 0, DEFAULT_FONT_SIZE);\n pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;\n ascent = 0;\n for (let i = 0, ii = pixels.length; i < ii; i += 4) {\n if (pixels[i] > 0) {\n ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);\n break;\n }\n }\n\n ctx.canvas.width = ctx.canvas.height = 0;\n\n const ratio = ascent ? ascent / (ascent + descent) : DEFAULT_FONT_ASCENT;\n this.#ascentCache.set(fontFamily, ratio);\n return ratio;\n }\n}\n\nexport { TextLayer };\n","/* Copyright 2021 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./api\").TextContent} TextContent */\n\nclass XfaText {\n /**\n * Walk an XFA tree and create an array of text nodes that is compatible\n * with a regular PDFs TextContent. Currently, only TextItem.str is supported,\n * all other fields and styles haven't been implemented.\n *\n * @param {Object} xfa - An XFA fake DOM object.\n *\n * @returns {TextContent}\n */\n static textContent(xfa) {\n const items = [];\n const output = {\n items,\n styles: Object.create(null),\n };\n function walk(node) {\n if (!node) {\n return;\n }\n let str = null;\n const name = node.name;\n if (name === \"#text\") {\n str = node.value;\n } else if (!XfaText.shouldBuildText(name)) {\n return;\n } else if (node?.attributes?.textContent) {\n str = node.attributes.textContent;\n } else if (node.value) {\n str = node.value;\n }\n if (str !== null) {\n items.push({\n str,\n });\n }\n if (!node.children) {\n return;\n }\n for (const child of node.children) {\n walk(child);\n }\n }\n walk(xfa);\n return output;\n }\n\n /**\n * @param {string} name - DOM node name. (lower case)\n *\n * @returns {boolean} true if the DOM node should have a corresponding text\n * node.\n */\n static shouldBuildText(name) {\n return !(\n name === \"textarea\" ||\n name === \"input\" ||\n name === \"option\" ||\n name === \"select\"\n );\n }\n}\n\nexport { XfaText };\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @module pdfjsLib\n */\n\nimport {\n AbortException,\n AnnotationMode,\n assert,\n FeatureTest,\n getVerbosityLevel,\n info,\n InvalidPDFException,\n isNodeJS,\n MAX_IMAGE_SIZE_TO_CACHE,\n MissingPDFException,\n PasswordException,\n RenderingIntentFlag,\n setVerbosityLevel,\n shadow,\n stringToBytes,\n UnexpectedResponseException,\n UnknownErrorException,\n unreachable,\n warn,\n} from \"../shared/util.js\";\nimport {\n AnnotationStorage,\n PrintAnnotationStorage,\n SerializableEmpty,\n} from \"./annotation_storage.js\";\nimport {\n deprecated,\n isDataScheme,\n isValidFetchUrl,\n PageViewport,\n RenderingCancelledException,\n StatTimer,\n} from \"./display_utils.js\";\nimport { FontFaceObject, FontLoader } from \"./font_loader.js\";\nimport {\n NodeCanvasFactory,\n NodeCMapReaderFactory,\n NodeFilterFactory,\n NodeStandardFontDataFactory,\n} from \"display-node_utils\";\nimport { CanvasGraphics } from \"./canvas.js\";\nimport { DOMCanvasFactory } from \"./canvas_factory.js\";\nimport { DOMCMapReaderFactory } from \"display-cmap_reader_factory\";\nimport { DOMFilterFactory } from \"./filter_factory.js\";\nimport { DOMStandardFontDataFactory } from \"display-standard_fontdata_factory\";\nimport { GlobalWorkerOptions } from \"./worker_options.js\";\nimport { MessageHandler } from \"../shared/message_handler.js\";\nimport { Metadata } from \"./metadata.js\";\nimport { OptionalContentConfig } from \"./optional_content_config.js\";\nimport { PDFDataTransportStream } from \"./transport_stream.js\";\nimport { PDFFetchStream } from \"display-fetch_stream\";\nimport { PDFNetworkStream } from \"display-network\";\nimport { PDFNodeStream } from \"display-node_stream\";\nimport { TextLayer } from \"./text_layer.js\";\nimport { XfaText } from \"./xfa_text.js\";\n\nconst DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536\nconst RENDERING_CANCELLED_TIMEOUT = 100; // ms\nconst DELAYED_CLEANUP_TIMEOUT = 5000; // ms\n\nconst DefaultCanvasFactory =\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"GENERIC\") && isNodeJS\n ? NodeCanvasFactory\n : DOMCanvasFactory;\nconst DefaultCMapReaderFactory =\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"GENERIC\") && isNodeJS\n ? NodeCMapReaderFactory\n : DOMCMapReaderFactory;\nconst DefaultFilterFactory =\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"GENERIC\") && isNodeJS\n ? NodeFilterFactory\n : DOMFilterFactory;\nconst DefaultStandardFontDataFactory =\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"GENERIC\") && isNodeJS\n ? NodeStandardFontDataFactory\n : DOMStandardFontDataFactory;\n\n/**\n * @typedef { Int8Array | Uint8Array | Uint8ClampedArray |\n * Int16Array | Uint16Array |\n * Int32Array | Uint32Array | Float32Array |\n * Float64Array\n * } TypedArray\n */\n\n/**\n * @typedef {Object} RefProxy\n * @property {number} num\n * @property {number} gen\n */\n\n/**\n * Document initialization / loading parameters object.\n *\n * @typedef {Object} DocumentInitParameters\n * @property {string | URL} [url] - The URL of the PDF.\n * @property {TypedArray | ArrayBuffer | Array | string} [data] -\n * Binary PDF data.\n * Use TypedArrays (Uint8Array) to improve the memory usage. If PDF data is\n * BASE64-encoded, use `atob()` to convert it to a binary string first.\n *\n * NOTE: If TypedArrays are used they will generally be transferred to the\n * worker-thread. This will help reduce main-thread memory usage, however\n * it will take ownership of the TypedArrays.\n * @property {Object} [httpHeaders] - Basic authentication headers.\n * @property {boolean} [withCredentials] - Indicates whether or not\n * cross-site Access-Control requests should be made using credentials such\n * as cookies or authorization headers. The default is `false`.\n * @property {string} [password] - For decrypting password-protected PDFs.\n * @property {number} [length] - The PDF file length. It's used for progress\n * reports and range requests operations.\n * @property {PDFDataRangeTransport} [range] - Allows for using a custom range\n * transport implementation.\n * @property {number} [rangeChunkSize] - Specify maximum number of bytes fetched\n * per range request. The default value is {@link DEFAULT_RANGE_CHUNK_SIZE}.\n * @property {PDFWorker} [worker] - The worker that will be used for loading and\n * parsing the PDF data.\n * @property {number} [verbosity] - Controls the logging level; the constants\n * from {@link VerbosityLevel} should be used.\n * @property {string} [docBaseUrl] - The base URL of the document, used when\n * attempting to recover valid absolute URLs for annotations, and outline\n * items, that (incorrectly) only specify relative URLs.\n * @property {string} [cMapUrl] - The URL where the predefined Adobe CMaps are\n * located. Include the trailing slash.\n * @property {boolean} [cMapPacked] - Specifies if the Adobe CMaps are binary\n * packed or not. The default value is `true`.\n * @property {Object} [CMapReaderFactory] - The factory that will be used when\n * reading built-in CMap files. Providing a custom factory is useful for\n * environments without Fetch API or `XMLHttpRequest` support, such as\n * Node.js. The default value is {DOMCMapReaderFactory}.\n * @property {boolean} [useSystemFonts] - When `true`, fonts that aren't\n * embedded in the PDF document will fallback to a system font.\n * The default value is `true` in web environments and `false` in Node.js;\n * unless `disableFontFace === true` in which case this defaults to `false`\n * regardless of the environment (to prevent completely broken fonts).\n * @property {string} [standardFontDataUrl] - The URL where the standard font\n * files are located. Include the trailing slash.\n * @property {Object} [StandardFontDataFactory] - The factory that will be used\n * when reading the standard font files. Providing a custom factory is useful\n * for environments without Fetch API or `XMLHttpRequest` support, such as\n * Node.js. The default value is {DOMStandardFontDataFactory}.\n * @property {boolean} [useWorkerFetch] - Enable using the Fetch API in the\n * worker-thread when reading CMap and standard font files. When `true`,\n * the `CMapReaderFactory` and `StandardFontDataFactory` options are ignored.\n * The default value is `true` in web environments and `false` in Node.js.\n * @property {boolean} [stopAtErrors] - Reject certain promises, e.g.\n * `getOperatorList`, `getTextContent`, and `RenderTask`, when the associated\n * PDF data cannot be successfully parsed, instead of attempting to recover\n * whatever possible of the data. The default value is `false`.\n * @property {number} [maxImageSize] - The maximum allowed image size in total\n * pixels, i.e. width * height. Images above this value will not be rendered.\n * Use -1 for no limit, which is also the default value.\n * @property {boolean} [isEvalSupported] - Determines if we can evaluate strings\n * as JavaScript. Primarily used to improve performance of PDF functions.\n * The default value is `true`.\n * @property {boolean} [isOffscreenCanvasSupported] - Determines if we can use\n * `OffscreenCanvas` in the worker. Primarily used to improve performance of\n * image conversion/rendering.\n * The default value is `true` in web environments and `false` in Node.js.\n * @property {boolean} [isImageDecoderSupported] - Determines if we can use\n * `ImageDecoder` in the worker. Primarily used to improve performance of\n * image conversion/rendering.\n * The default value is `true` in web environments and `false` in Node.js.\n *\n * NOTE: Also temporarily disabled in Chromium browsers, until we no longer\n * support the affected browser versions, because of various bugs:\n *\n * - Crashes when using the BMP decoder with huge images, e.g. issue6741.pdf;\n * see https://issues.chromium.org/issues/374807001\n *\n * - Broken images when using the JPEG decoder with images that have custom\n * colour profiles, e.g. GitHub discussion 19030;\n * see https://issues.chromium.org/issues/378869810\n *\n * @property {number} [canvasMaxAreaInBytes] - The integer value is used to\n * know when an image must be resized (uses `OffscreenCanvas` in the worker).\n * If it's -1 then a possibly slow algorithm is used to guess the max value.\n * @property {boolean} [disableFontFace] - By default fonts are converted to\n * OpenType fonts and loaded via the Font Loading API or `@font-face` rules.\n * If disabled, fonts will be rendered using a built-in font renderer that\n * constructs the glyphs with primitive path commands.\n * The default value is `false` in web environments and `true` in Node.js.\n * @property {boolean} [fontExtraProperties] - Include additional properties,\n * which are unused during rendering of PDF documents, when exporting the\n * parsed font data from the worker-thread. This may be useful for debugging\n * purposes (and backwards compatibility), but note that it will lead to\n * increased memory usage. The default value is `false`.\n * @property {boolean} [enableXfa] - Render Xfa forms if any.\n * The default value is `false`.\n * @property {HTMLDocument} [ownerDocument] - Specify an explicit document\n * context to create elements with and to load resources, such as fonts,\n * into. Defaults to the current document.\n * @property {boolean} [disableRange] - Disable range request loading of PDF\n * files. When enabled, and if the server supports partial content requests,\n * then the PDF will be fetched in chunks. The default value is `false`.\n * @property {boolean} [disableStream] - Disable streaming of PDF file data.\n * By default PDF.js attempts to load PDF files in chunks. The default value\n * is `false`.\n * @property {boolean} [disableAutoFetch] - Disable pre-fetching of PDF file\n * data. When range requests are enabled PDF.js will automatically keep\n * fetching more data even if it isn't needed to display the current page.\n * The default value is `false`.\n *\n * NOTE: It is also necessary to disable streaming, see above, in order for\n * disabling of pre-fetching to work correctly.\n * @property {boolean} [pdfBug] - Enables special hooks for debugging PDF.js\n * (see `web/debugger.js`). The default value is `false`.\n * @property {Object} [CanvasFactory] - The factory that will be used when\n * creating canvases. The default value is {DOMCanvasFactory}.\n * @property {Object} [FilterFactory] - The factory that will be used to\n * create SVG filters when rendering some images on the main canvas.\n * The default value is {DOMFilterFactory}.\n * @property {boolean} [enableHWA] - Enables hardware acceleration for\n * rendering. The default value is `false`.\n */\n\n/**\n * This is the main entry point for loading a PDF and interacting with it.\n *\n * NOTE: If a URL is used to fetch the PDF data a standard Fetch API call (or\n * XHR as fallback) is used, which means it must follow same origin rules,\n * e.g. no cross-domain requests without CORS.\n *\n * @param {string | URL | TypedArray | ArrayBuffer | DocumentInitParameters}\n * src - Can be a URL where a PDF file is located, a typed array (Uint8Array)\n * already populated with data, or a parameter object.\n * @returns {PDFDocumentLoadingTask}\n */\nfunction getDocument(src = {}) {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) {\n if (typeof src === \"string\" || src instanceof URL) {\n src = { url: src };\n } else if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) {\n src = { data: src };\n }\n }\n const task = new PDFDocumentLoadingTask();\n const { docId } = task;\n\n const url = src.url ? getUrlProp(src.url) : null;\n const data = src.data ? getDataProp(src.data) : null;\n const httpHeaders = src.httpHeaders || null;\n const withCredentials = src.withCredentials === true;\n const password = src.password ?? null;\n const rangeTransport =\n src.range instanceof PDFDataRangeTransport ? src.range : null;\n const rangeChunkSize =\n Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0\n ? src.rangeChunkSize\n : DEFAULT_RANGE_CHUNK_SIZE;\n let worker = src.worker instanceof PDFWorker ? src.worker : null;\n const verbosity = src.verbosity;\n // Ignore \"data:\"-URLs, since they can't be used to recover valid absolute\n // URLs anyway. We want to avoid sending them to the worker-thread, since\n // they contain the *entire* PDF document and can thus be arbitrarily long.\n const docBaseUrl =\n typeof src.docBaseUrl === \"string\" && !isDataScheme(src.docBaseUrl)\n ? src.docBaseUrl\n : null;\n const cMapUrl = typeof src.cMapUrl === \"string\" ? src.cMapUrl : null;\n const cMapPacked = src.cMapPacked !== false;\n const CMapReaderFactory = src.CMapReaderFactory || DefaultCMapReaderFactory;\n const standardFontDataUrl =\n typeof src.standardFontDataUrl === \"string\"\n ? src.standardFontDataUrl\n : null;\n const StandardFontDataFactory =\n src.StandardFontDataFactory || DefaultStandardFontDataFactory;\n const ignoreErrors = src.stopAtErrors !== true;\n const maxImageSize =\n Number.isInteger(src.maxImageSize) && src.maxImageSize > -1\n ? src.maxImageSize\n : -1;\n const isEvalSupported = src.isEvalSupported !== false;\n const isOffscreenCanvasSupported =\n typeof src.isOffscreenCanvasSupported === \"boolean\"\n ? src.isOffscreenCanvasSupported\n : !isNodeJS;\n const isImageDecoderSupported =\n // eslint-disable-next-line no-nested-ternary\n typeof src.isImageDecoderSupported === \"boolean\"\n ? src.isImageDecoderSupported\n : // eslint-disable-next-line no-nested-ternary\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")\n ? true\n : typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"CHROME\")\n ? false\n : !isNodeJS && (FeatureTest.platform.isFirefox || !globalThis.chrome);\n const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes)\n ? src.canvasMaxAreaInBytes\n : -1;\n const disableFontFace =\n typeof src.disableFontFace === \"boolean\" ? src.disableFontFace : isNodeJS;\n const fontExtraProperties = src.fontExtraProperties === true;\n const enableXfa = src.enableXfa === true;\n const ownerDocument = src.ownerDocument || globalThis.document;\n const disableRange = src.disableRange === true;\n const disableStream = src.disableStream === true;\n const disableAutoFetch = src.disableAutoFetch === true;\n const pdfBug = src.pdfBug === true;\n const CanvasFactory = src.CanvasFactory || DefaultCanvasFactory;\n const FilterFactory = src.FilterFactory || DefaultFilterFactory;\n const enableHWA = src.enableHWA === true;\n\n // Parameters whose default values depend on other parameters.\n const length = rangeTransport ? rangeTransport.length : (src.length ?? NaN);\n const useSystemFonts =\n typeof src.useSystemFonts === \"boolean\"\n ? src.useSystemFonts\n : !isNodeJS && !disableFontFace;\n const useWorkerFetch =\n typeof src.useWorkerFetch === \"boolean\"\n ? src.useWorkerFetch\n : (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) ||\n (CMapReaderFactory === DOMCMapReaderFactory &&\n StandardFontDataFactory === DOMStandardFontDataFactory &&\n cMapUrl &&\n standardFontDataUrl &&\n isValidFetchUrl(cMapUrl, document.baseURI) &&\n isValidFetchUrl(standardFontDataUrl, document.baseURI));\n\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) {\n if (src.canvasFactory) {\n deprecated(\n \"`canvasFactory`-instance option, please use `CanvasFactory` instead.\"\n );\n }\n if (src.filterFactory) {\n deprecated(\n \"`filterFactory`-instance option, please use `FilterFactory` instead.\"\n );\n }\n }\n\n // Parameters only intended for development/testing purposes.\n const styleElement =\n typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")\n ? src.styleElement\n : null;\n\n // Set the main-thread verbosity level.\n setVerbosityLevel(verbosity);\n\n // Ensure that the various factories can be initialized, when necessary,\n // since the user may provide *custom* ones.\n const transportFactory = {\n canvasFactory: new CanvasFactory({ ownerDocument, enableHWA }),\n filterFactory: new FilterFactory({ docId, ownerDocument }),\n cMapReaderFactory:\n (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) ||\n useWorkerFetch\n ? null\n : new CMapReaderFactory({ baseUrl: cMapUrl, isCompressed: cMapPacked }),\n standardFontDataFactory:\n (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) ||\n useWorkerFetch\n ? null\n : new StandardFontDataFactory({ baseUrl: standardFontDataUrl }),\n };\n\n if (!worker) {\n const workerParams = {\n verbosity,\n port: GlobalWorkerOptions.workerPort,\n };\n // Worker was not provided -- creating and owning our own. If message port\n // is specified in global worker options, using it.\n worker = workerParams.port\n ? PDFWorker.fromPort(workerParams)\n : new PDFWorker(workerParams);\n task._worker = worker;\n }\n\n const docParams = {\n docId,\n apiVersion:\n typeof PDFJSDev !== \"undefined\" && !PDFJSDev.test(\"TESTING\")\n ? PDFJSDev.eval(\"BUNDLE_VERSION\")\n : null,\n data,\n password,\n disableAutoFetch,\n rangeChunkSize,\n length,\n docBaseUrl,\n enableXfa,\n evaluatorOptions: {\n maxImageSize,\n disableFontFace,\n ignoreErrors,\n isEvalSupported,\n isOffscreenCanvasSupported,\n isImageDecoderSupported,\n canvasMaxAreaInBytes,\n fontExtraProperties,\n useSystemFonts,\n cMapUrl: useWorkerFetch ? cMapUrl : null,\n standardFontDataUrl: useWorkerFetch ? standardFontDataUrl : null,\n },\n };\n const transportParams = {\n disableFontFace,\n fontExtraProperties,\n ownerDocument,\n pdfBug,\n styleElement,\n loadingParams: {\n disableAutoFetch,\n enableXfa,\n },\n };\n\n worker.promise\n .then(function () {\n if (task.destroyed) {\n throw new Error(\"Loading aborted\");\n }\n if (worker.destroyed) {\n throw new Error(\"Worker was destroyed\");\n }\n\n const workerIdPromise = worker.messageHandler.sendWithPromise(\n \"GetDocRequest\",\n docParams,\n data ? [data.buffer] : null\n );\n\n let networkStream;\n if (rangeTransport) {\n networkStream = new PDFDataTransportStream(rangeTransport, {\n disableRange,\n disableStream,\n });\n } else if (!data) {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: NetworkStream\");\n }\n if (!url) {\n throw new Error(\"getDocument - no `url` parameter provided.\");\n }\n let NetworkStream;\n\n if (\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"GENERIC\") &&\n isNodeJS\n ) {\n if (isValidFetchUrl(url)) {\n if (\n typeof fetch === \"undefined\" ||\n typeof Response === \"undefined\" ||\n !(\"body\" in Response.prototype)\n ) {\n throw new Error(\n \"getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.\"\n );\n }\n NetworkStream = PDFFetchStream;\n } else {\n NetworkStream = PDFNodeStream;\n }\n } else {\n NetworkStream = isValidFetchUrl(url)\n ? PDFFetchStream\n : PDFNetworkStream;\n }\n\n networkStream = new NetworkStream({\n url,\n length,\n httpHeaders,\n withCredentials,\n rangeChunkSize,\n disableRange,\n disableStream,\n });\n }\n\n return workerIdPromise.then(workerId => {\n if (task.destroyed) {\n throw new Error(\"Loading aborted\");\n }\n if (worker.destroyed) {\n throw new Error(\"Worker was destroyed\");\n }\n\n const messageHandler = new MessageHandler(docId, workerId, worker.port);\n const transport = new WorkerTransport(\n messageHandler,\n task,\n networkStream,\n transportParams,\n transportFactory\n );\n task._transport = transport;\n messageHandler.send(\"Ready\", null);\n });\n })\n .catch(task._capability.reject);\n\n return task;\n}\n\nfunction getUrlProp(val) {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n return null; // The 'url' is unused with `PDFDataRangeTransport`.\n }\n if (val instanceof URL) {\n return val.href;\n }\n try {\n // The full path is required in the 'url' field.\n return new URL(val, window.location).href;\n } catch {\n if (\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"GENERIC\") &&\n isNodeJS &&\n typeof val === \"string\"\n ) {\n return val; // Use the url as-is in Node.js environments.\n }\n }\n throw new Error(\n \"Invalid PDF url data: \" +\n \"either string or URL-object is expected in the url property.\"\n );\n}\n\nfunction getDataProp(val) {\n // Converting string or array-like data to Uint8Array.\n if (\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"GENERIC\") &&\n isNodeJS &&\n typeof Buffer !== \"undefined\" && // eslint-disable-line no-undef\n val instanceof Buffer // eslint-disable-line no-undef\n ) {\n throw new Error(\n \"Please provide binary data as `Uint8Array`, rather than `Buffer`.\"\n );\n }\n if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) {\n // Use the data as-is when it's already a Uint8Array that completely\n // \"utilizes\" its underlying ArrayBuffer, to prevent any possible\n // issues when transferring it to the worker-thread.\n return val;\n }\n if (typeof val === \"string\") {\n return stringToBytes(val);\n }\n if (\n val instanceof ArrayBuffer ||\n ArrayBuffer.isView(val) ||\n (typeof val === \"object\" && !isNaN(val?.length))\n ) {\n return new Uint8Array(val);\n }\n throw new Error(\n \"Invalid PDF binary data: either TypedArray, \" +\n \"string, or array-like object is expected in the data property.\"\n );\n}\n\nfunction isRefProxy(ref) {\n return (\n typeof ref === \"object\" &&\n Number.isInteger(ref?.num) &&\n ref.num >= 0 &&\n Number.isInteger(ref?.gen) &&\n ref.gen >= 0\n );\n}\n\n/**\n * @typedef {Object} OnProgressParameters\n * @property {number} loaded - Currently loaded number of bytes.\n * @property {number} total - Total number of bytes in the PDF file.\n */\n\n/**\n * The loading task controls the operations required to load a PDF document\n * (such as network requests) and provides a way to listen for completion,\n * after which individual pages can be rendered.\n */\nclass PDFDocumentLoadingTask {\n static #docId = 0;\n\n constructor() {\n this._capability = Promise.withResolvers();\n this._transport = null;\n this._worker = null;\n\n /**\n * Unique identifier for the document loading task.\n * @type {string}\n */\n this.docId = `d${PDFDocumentLoadingTask.#docId++}`;\n\n /**\n * Whether the loading task is destroyed or not.\n * @type {boolean}\n */\n this.destroyed = false;\n\n /**\n * Callback to request a password if a wrong or no password was provided.\n * The callback receives two parameters: a function that should be called\n * with the new password, and a reason (see {@link PasswordResponses}).\n * @type {function}\n */\n this.onPassword = null;\n\n /**\n * Callback to be able to monitor the loading progress of the PDF file\n * (necessary to implement e.g. a loading bar).\n * The callback receives an {@link OnProgressParameters} argument.\n * @type {function}\n */\n this.onProgress = null;\n }\n\n /**\n * Promise for document loading task completion.\n * @type {Promise}\n */\n get promise() {\n return this._capability.promise;\n }\n\n /**\n * Abort all network requests and destroy the worker.\n * @returns {Promise} A promise that is resolved when destruction is\n * completed.\n */\n async destroy() {\n this.destroyed = true;\n\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n await this._transport?.destroy();\n } else {\n try {\n if (this._worker?.port) {\n this._worker._pendingDestroy = true;\n }\n await this._transport?.destroy();\n } catch (ex) {\n if (this._worker?.port) {\n delete this._worker._pendingDestroy;\n }\n throw ex;\n }\n }\n this._transport = null;\n\n this._worker?.destroy();\n this._worker = null;\n }\n}\n\n/**\n * Abstract class to support range requests file loading.\n *\n * NOTE: The TypedArrays passed to the constructor and relevant methods below\n * will generally be transferred to the worker-thread. This will help reduce\n * main-thread memory usage, however it will take ownership of the TypedArrays.\n */\nclass PDFDataRangeTransport {\n /**\n * @param {number} length\n * @param {Uint8Array|null} initialData\n * @param {boolean} [progressiveDone]\n * @param {string} [contentDispositionFilename]\n */\n constructor(\n length,\n initialData,\n progressiveDone = false,\n contentDispositionFilename = null\n ) {\n this.length = length;\n this.initialData = initialData;\n this.progressiveDone = progressiveDone;\n this.contentDispositionFilename = contentDispositionFilename;\n\n this._rangeListeners = [];\n this._progressListeners = [];\n this._progressiveReadListeners = [];\n this._progressiveDoneListeners = [];\n this._readyCapability = Promise.withResolvers();\n }\n\n /**\n * @param {function} listener\n */\n addRangeListener(listener) {\n this._rangeListeners.push(listener);\n }\n\n /**\n * @param {function} listener\n */\n addProgressListener(listener) {\n this._progressListeners.push(listener);\n }\n\n /**\n * @param {function} listener\n */\n addProgressiveReadListener(listener) {\n this._progressiveReadListeners.push(listener);\n }\n\n /**\n * @param {function} listener\n */\n addProgressiveDoneListener(listener) {\n this._progressiveDoneListeners.push(listener);\n }\n\n /**\n * @param {number} begin\n * @param {Uint8Array|null} chunk\n */\n onDataRange(begin, chunk) {\n for (const listener of this._rangeListeners) {\n listener(begin, chunk);\n }\n }\n\n /**\n * @param {number} loaded\n * @param {number|undefined} total\n */\n onDataProgress(loaded, total) {\n this._readyCapability.promise.then(() => {\n for (const listener of this._progressListeners) {\n listener(loaded, total);\n }\n });\n }\n\n /**\n * @param {Uint8Array|null} chunk\n */\n onDataProgressiveRead(chunk) {\n this._readyCapability.promise.then(() => {\n for (const listener of this._progressiveReadListeners) {\n listener(chunk);\n }\n });\n }\n\n onDataProgressiveDone() {\n this._readyCapability.promise.then(() => {\n for (const listener of this._progressiveDoneListeners) {\n listener();\n }\n });\n }\n\n transportReady() {\n this._readyCapability.resolve();\n }\n\n /**\n * @param {number} begin\n * @param {number} end\n */\n requestDataRange(begin, end) {\n unreachable(\"Abstract method PDFDataRangeTransport.requestDataRange\");\n }\n\n abort() {}\n}\n\n/**\n * Proxy to a `PDFDocument` in the worker thread.\n */\nclass PDFDocumentProxy {\n constructor(pdfInfo, transport) {\n this._pdfInfo = pdfInfo;\n this._transport = transport;\n\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n // For testing purposes.\n Object.defineProperty(this, \"getNetworkStreamName\", {\n value: () => this._transport.getNetworkStreamName(),\n });\n Object.defineProperty(this, \"getXFADatasets\", {\n value: () => this._transport.getXFADatasets(),\n });\n Object.defineProperty(this, \"getXRefPrevValue\", {\n value: () => this._transport.getXRefPrevValue(),\n });\n Object.defineProperty(this, \"getStartXRefPos\", {\n value: () => this._transport.getStartXRefPos(),\n });\n Object.defineProperty(this, \"getAnnotArray\", {\n value: pageIndex => this._transport.getAnnotArray(pageIndex),\n });\n }\n }\n\n /**\n * @type {AnnotationStorage} Storage for annotation data in forms.\n */\n get annotationStorage() {\n return this._transport.annotationStorage;\n }\n\n /**\n * @type {Object} The canvas factory instance.\n */\n get canvasFactory() {\n return this._transport.canvasFactory;\n }\n\n /**\n * @type {Object} The filter factory instance.\n */\n get filterFactory() {\n return this._transport.filterFactory;\n }\n\n /**\n * @type {number} Total number of pages in the PDF file.\n */\n get numPages() {\n return this._pdfInfo.numPages;\n }\n\n /**\n * @type {Array} A (not guaranteed to be) unique ID to identify\n * the PDF document.\n * NOTE: The first element will always be defined for all PDF documents,\n * whereas the second element is only defined for *modified* PDF documents.\n */\n get fingerprints() {\n return this._pdfInfo.fingerprints;\n }\n\n /**\n * @type {boolean} True if only XFA form.\n */\n get isPureXfa() {\n return shadow(this, \"isPureXfa\", !!this._transport._htmlForXfa);\n }\n\n /**\n * NOTE: This is (mostly) intended to support printing of XFA forms.\n *\n * @type {Object | null} An object representing a HTML tree structure\n * to render the XFA, or `null` when no XFA form exists.\n */\n get allXfaHtml() {\n return this._transport._htmlForXfa;\n }\n\n /**\n * @param {number} pageNumber - The page number to get. The first page is 1.\n * @returns {Promise} A promise that is resolved with\n * a {@link PDFPageProxy} object.\n */\n getPage(pageNumber) {\n return this._transport.getPage(pageNumber);\n }\n\n /**\n * @param {RefProxy} ref - The page reference.\n * @returns {Promise} A promise that is resolved with the page index,\n * starting from zero, that is associated with the reference.\n */\n getPageIndex(ref) {\n return this._transport.getPageIndex(ref);\n }\n\n /**\n * @returns {Promise>>} A promise that is resolved\n * with a mapping from named destinations to references.\n *\n * This can be slow for large documents. Use `getDestination` instead.\n */\n getDestinations() {\n return this._transport.getDestinations();\n }\n\n /**\n * @param {string} id - The named destination to get.\n * @returns {Promise | null>} A promise that is resolved with all\n * information of the given named destination, or `null` when the named\n * destination is not present in the PDF file.\n */\n getDestination(id) {\n return this._transport.getDestination(id);\n }\n\n /**\n * @returns {Promise | null>} A promise that is resolved with\n * an {Array} containing the page labels that correspond to the page\n * indexes, or `null` when no page labels are present in the PDF file.\n */\n getPageLabels() {\n return this._transport.getPageLabels();\n }\n\n /**\n * @returns {Promise} A promise that is resolved with a {string}\n * containing the page layout name.\n */\n getPageLayout() {\n return this._transport.getPageLayout();\n }\n\n /**\n * @returns {Promise} A promise that is resolved with a {string}\n * containing the page mode name.\n */\n getPageMode() {\n return this._transport.getPageMode();\n }\n\n /**\n * @returns {Promise} A promise that is resolved with an\n * {Object} containing the viewer preferences, or `null` when no viewer\n * preferences are present in the PDF file.\n */\n getViewerPreferences() {\n return this._transport.getViewerPreferences();\n }\n\n /**\n * @returns {Promise} A promise that is resolved with an {Array}\n * containing the destination, or `null` when no open action is present\n * in the PDF.\n */\n getOpenAction() {\n return this._transport.getOpenAction();\n }\n\n /**\n * @returns {Promise} A promise that is resolved with a lookup table\n * for mapping named attachments to their content.\n */\n getAttachments() {\n return this._transport.getAttachments();\n }\n\n /**\n * @returns {Promise} A promise that is resolved with\n * an {Object} with the JavaScript actions:\n * - from the name tree.\n * - from A or AA entries in the catalog dictionary.\n * , or `null` if no JavaScript exists.\n */\n getJSActions() {\n return this._transport.getDocJSActions();\n }\n\n /**\n * @typedef {Object} OutlineNode\n * @property {string} title\n * @property {boolean} bold\n * @property {boolean} italic\n * @property {Uint8ClampedArray} color - The color in RGB format to use for\n * display purposes.\n * @property {string | Array | null} dest\n * @property {string | null} url\n * @property {string | undefined} unsafeUrl\n * @property {boolean | undefined} newWindow\n * @property {number | undefined} count\n * @property {Array} items\n */\n\n /**\n * @returns {Promise>} A promise that is resolved with an\n * {Array} that is a tree outline (if it has one) of the PDF file.\n */\n getOutline() {\n return this._transport.getOutline();\n }\n\n /**\n * @typedef {Object} GetOptionalContentConfigParameters\n * @property {string} [intent] - Determines the optional content groups that\n * are visible by default; valid values are:\n * - 'display' (viewable groups).\n * - 'print' (printable groups).\n * - 'any' (all groups).\n * The default value is 'display'.\n */\n\n /**\n * @param {GetOptionalContentConfigParameters} [params] - Optional content\n * config parameters.\n * @returns {Promise} A promise that is resolved with\n * an {@link OptionalContentConfig} that contains all the optional content\n * groups (assuming that the document has any).\n */\n getOptionalContentConfig({ intent = \"display\" } = {}) {\n const { renderingIntent } = this._transport.getRenderingIntent(intent);\n\n return this._transport.getOptionalContentConfig(renderingIntent);\n }\n\n /**\n * @returns {Promise | null>} A promise that is resolved with\n * an {Array} that contains the permission flags for the PDF document, or\n * `null` when no permissions are present in the PDF file.\n */\n getPermissions() {\n return this._transport.getPermissions();\n }\n\n /**\n * @returns {Promise<{ info: Object, metadata: Metadata }>} A promise that is\n * resolved with an {Object} that has `info` and `metadata` properties.\n * `info` is an {Object} filled with anything available in the information\n * dictionary and similarly `metadata` is a {Metadata} object with\n * information from the metadata section of the PDF.\n */\n getMetadata() {\n return this._transport.getMetadata();\n }\n\n /**\n * @typedef {Object} MarkInfo\n * Properties correspond to Table 321 of the PDF 32000-1:2008 spec.\n * @property {boolean} Marked\n * @property {boolean} UserProperties\n * @property {boolean} Suspects\n */\n\n /**\n * @returns {Promise} A promise that is resolved with\n * a {MarkInfo} object that contains the MarkInfo flags for the PDF\n * document, or `null` when no MarkInfo values are present in the PDF file.\n */\n getMarkInfo() {\n return this._transport.getMarkInfo();\n }\n\n /**\n * @returns {Promise} A promise that is resolved with a\n * {Uint8Array} containing the raw data of the PDF document.\n */\n getData() {\n return this._transport.getData();\n }\n\n /**\n * @returns {Promise} A promise that is resolved with a\n * {Uint8Array} containing the full data of the saved document.\n */\n saveDocument() {\n return this._transport.saveDocument();\n }\n\n /**\n * @returns {Promise<{ length: number }>} A promise that is resolved when the\n * document's data is loaded. It is resolved with an {Object} that contains\n * the `length` property that indicates size of the PDF data in bytes.\n */\n getDownloadInfo() {\n return this._transport.downloadInfoCapability.promise;\n }\n\n /**\n * Cleans up resources allocated by the document on both the main and worker\n * threads.\n *\n * NOTE: Do not, under any circumstances, call this method when rendering is\n * currently ongoing since that may lead to rendering errors.\n *\n * @param {boolean} [keepLoadedFonts] - Let fonts remain attached to the DOM.\n * NOTE: This will increase persistent memory usage, hence don't use this\n * option unless absolutely necessary. The default value is `false`.\n * @returns {Promise} A promise that is resolved when clean-up has finished.\n */\n cleanup(keepLoadedFonts = false) {\n return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);\n }\n\n /**\n * Destroys the current document instance and terminates the worker.\n */\n destroy() {\n return this.loadingTask.destroy();\n }\n\n /**\n * @param {RefProxy} ref - The page reference.\n * @returns {number | null} The page number, if it's cached.\n */\n cachedPageNumber(ref) {\n return this._transport.cachedPageNumber(ref);\n }\n\n /**\n * @type {DocumentInitParameters} A subset of the current\n * {DocumentInitParameters}, which are needed in the viewer.\n */\n get loadingParams() {\n return this._transport.loadingParams;\n }\n\n /**\n * @type {PDFDocumentLoadingTask} The loadingTask for the current document.\n */\n get loadingTask() {\n return this._transport.loadingTask;\n }\n\n /**\n * @returns {Promise> | null>} A promise that is\n * resolved with an {Object} containing /AcroForm field data for the JS\n * sandbox, or `null` when no field data is present in the PDF file.\n */\n getFieldObjects() {\n return this._transport.getFieldObjects();\n }\n\n /**\n * @returns {Promise} A promise that is resolved with `true`\n * if some /AcroForm fields have JavaScript actions.\n */\n hasJSActions() {\n return this._transport.hasJSActions();\n }\n\n /**\n * @returns {Promise | null>} A promise that is resolved with an\n * {Array} containing IDs of annotations that have a calculation\n * action, or `null` when no such annotations are present in the PDF file.\n */\n getCalculationOrderIds() {\n return this._transport.getCalculationOrderIds();\n }\n}\n\n/**\n * Page getViewport parameters.\n *\n * @typedef {Object} GetViewportParameters\n * @property {number} scale - The desired scale of the viewport.\n * @property {number} [rotation] - The desired rotation, in degrees, of\n * the viewport. If omitted it defaults to the page rotation.\n * @property {number} [offsetX] - The horizontal, i.e. x-axis, offset.\n * The default value is `0`.\n * @property {number} [offsetY] - The vertical, i.e. y-axis, offset.\n * The default value is `0`.\n * @property {boolean} [dontFlip] - If true, the y-axis will not be\n * flipped. The default value is `false`.\n */\n\n/**\n * Page getTextContent parameters.\n *\n * @typedef {Object} getTextContentParameters\n * @property {boolean} [includeMarkedContent] - When true include marked\n * content items in the items array of TextContent. The default is `false`.\n * @property {boolean} [disableNormalization] - When true the text is *not*\n * normalized in the worker-thread. The default is `false`.\n */\n\n/**\n * Page text content.\n *\n * @typedef {Object} TextContent\n * @property {Array} items - Array of\n * {@link TextItem} and {@link TextMarkedContent} objects. TextMarkedContent\n * items are included when includeMarkedContent is true.\n * @property {Object} styles - {@link TextStyle} objects,\n * indexed by font name.\n * @property {string | null} lang - The document /Lang attribute.\n */\n\n/**\n * Page text content part.\n *\n * @typedef {Object} TextItem\n * @property {string} str - Text content.\n * @property {string} dir - Text direction: 'ttb', 'ltr' or 'rtl'.\n * @property {Array} transform - Transformation matrix.\n * @property {number} width - Width in device space.\n * @property {number} height - Height in device space.\n * @property {string} fontName - Font name used by PDF.js for converted font.\n * @property {boolean} hasEOL - Indicating if the text content is followed by a\n * line-break.\n */\n\n/**\n * Page text marked content part.\n *\n * @typedef {Object} TextMarkedContent\n * @property {string} type - Either 'beginMarkedContent',\n * 'beginMarkedContentProps', or 'endMarkedContent'.\n * @property {string} id - The marked content identifier. Only used for type\n * 'beginMarkedContentProps'.\n */\n\n/**\n * Text style.\n *\n * @typedef {Object} TextStyle\n * @property {number} ascent - Font ascent.\n * @property {number} descent - Font descent.\n * @property {boolean} vertical - Whether or not the text is in vertical mode.\n * @property {string} fontFamily - The possible font family.\n */\n\n/**\n * Page annotation parameters.\n *\n * @typedef {Object} GetAnnotationsParameters\n * @property {string} [intent] - Determines the annotations that are fetched,\n * can be 'display' (viewable annotations), 'print' (printable annotations),\n * or 'any' (all annotations). The default value is 'display'.\n */\n\n/**\n * Page render parameters.\n *\n * @typedef {Object} RenderParameters\n * @property {CanvasRenderingContext2D} canvasContext - A 2D context of a DOM\n * Canvas object.\n * @property {PageViewport} viewport - Rendering viewport obtained by calling\n * the `PDFPageProxy.getViewport` method.\n * @property {string} [intent] - Rendering intent, can be 'display', 'print',\n * or 'any'. The default value is 'display'.\n * @property {number} [annotationMode] Controls which annotations are rendered\n * onto the canvas, for annotations with appearance-data; the values from\n * {@link AnnotationMode} should be used. The following values are supported:\n * - `AnnotationMode.DISABLE`, which disables all annotations.\n * - `AnnotationMode.ENABLE`, which includes all possible annotations (thus\n * it also depends on the `intent`-option, see above).\n * - `AnnotationMode.ENABLE_FORMS`, which excludes annotations that contain\n * interactive form elements (those will be rendered in the display layer).\n * - `AnnotationMode.ENABLE_STORAGE`, which includes all possible annotations\n * (as above) but where interactive form elements are updated with data\n * from the {@link AnnotationStorage}-instance; useful e.g. for printing.\n * The default value is `AnnotationMode.ENABLE`.\n * @property {Array} [transform] - Additional transform, applied just\n * before viewport transform.\n * @property {CanvasGradient | CanvasPattern | string} [background] - Background\n * to use for the canvas.\n * Any valid `canvas.fillStyle` can be used: a `DOMString` parsed as CSS\n * value, a `CanvasGradient` object (a linear or radial gradient) or\n * a `CanvasPattern` object (a repetitive image). The default value is\n * 'rgb(255,255,255)'.\n *\n * NOTE: This option may be partially, or completely, ignored when the\n * `pageColors`-option is used.\n * @property {Object} [pageColors] - Overwrites background and foreground colors\n * with user defined ones in order to improve readability in high contrast\n * mode.\n * @property {Promise} [optionalContentConfigPromise] -\n * A promise that should resolve with an {@link OptionalContentConfig}\n * created from `PDFDocumentProxy.getOptionalContentConfig`. If `null`,\n * the configuration will be fetched automatically with the default visibility\n * states set.\n * @property {Map} [annotationCanvasMap] - Map some\n * annotation ids with canvases used to render them.\n * @property {PrintAnnotationStorage} [printAnnotationStorage]\n * @property {boolean} [isEditing] - Render the page in editing mode.\n */\n\n/**\n * Page getOperatorList parameters.\n *\n * @typedef {Object} GetOperatorListParameters\n * @property {string} [intent] - Rendering intent, can be 'display', 'print',\n * or 'any'. The default value is 'display'.\n * @property {number} [annotationMode] Controls which annotations are included\n * in the operatorList, for annotations with appearance-data; the values from\n * {@link AnnotationMode} should be used. The following values are supported:\n * - `AnnotationMode.DISABLE`, which disables all annotations.\n * - `AnnotationMode.ENABLE`, which includes all possible annotations (thus\n * it also depends on the `intent`-option, see above).\n * - `AnnotationMode.ENABLE_FORMS`, which excludes annotations that contain\n * interactive form elements (those will be rendered in the display layer).\n * - `AnnotationMode.ENABLE_STORAGE`, which includes all possible annotations\n * (as above) but where interactive form elements are updated with data\n * from the {@link AnnotationStorage}-instance; useful e.g. for printing.\n * The default value is `AnnotationMode.ENABLE`.\n * @property {PrintAnnotationStorage} [printAnnotationStorage]\n * @property {boolean} [isEditing] - Render the page in editing mode.\n */\n\n/**\n * Structure tree node. The root node will have a role \"Root\".\n *\n * @typedef {Object} StructTreeNode\n * @property {Array} children - Array of\n * {@link StructTreeNode} and {@link StructTreeContent} objects.\n * @property {string} role - element's role, already mapped if a role map exists\n * in the PDF.\n */\n\n/**\n * Structure tree content.\n *\n * @typedef {Object} StructTreeContent\n * @property {string} type - either \"content\" for page and stream structure\n * elements or \"object\" for object references.\n * @property {string} id - unique id that will map to the text layer.\n */\n\n/**\n * PDF page operator list.\n *\n * @typedef {Object} PDFOperatorList\n * @property {Array} fnArray - Array containing the operator functions.\n * @property {Array} argsArray - Array containing the arguments of the\n * functions.\n */\n\n/**\n * Proxy to a `PDFPage` in the worker thread.\n */\nclass PDFPageProxy {\n #delayedCleanupTimeout = null;\n\n #pendingCleanup = false;\n\n constructor(pageIndex, pageInfo, transport, pdfBug = false) {\n this._pageIndex = pageIndex;\n this._pageInfo = pageInfo;\n this._transport = transport;\n this._stats = pdfBug ? new StatTimer() : null;\n this._pdfBug = pdfBug;\n /** @type {PDFObjects} */\n this.commonObjs = transport.commonObjs;\n this.objs = new PDFObjects();\n\n this._maybeCleanupAfterRender = false;\n this._intentStates = new Map();\n this.destroyed = false;\n }\n\n /**\n * @type {number} Page number of the page. First page is 1.\n */\n get pageNumber() {\n return this._pageIndex + 1;\n }\n\n /**\n * @type {number} The number of degrees the page is rotated clockwise.\n */\n get rotate() {\n return this._pageInfo.rotate;\n }\n\n /**\n * @type {RefProxy | null} The reference that points to this page.\n */\n get ref() {\n return this._pageInfo.ref;\n }\n\n /**\n * @type {number} The default size of units in 1/72nds of an inch.\n */\n get userUnit() {\n return this._pageInfo.userUnit;\n }\n\n /**\n * @type {Array} An array of the visible portion of the PDF page in\n * user space units [x1, y1, x2, y2].\n */\n get view() {\n return this._pageInfo.view;\n }\n\n /**\n * @param {GetViewportParameters} params - Viewport parameters.\n * @returns {PageViewport} Contains 'width' and 'height' properties\n * along with transforms required for rendering.\n */\n getViewport({\n scale,\n rotation = this.rotate,\n offsetX = 0,\n offsetY = 0,\n dontFlip = false,\n } = {}) {\n return new PageViewport({\n viewBox: this.view,\n scale,\n rotation,\n offsetX,\n offsetY,\n dontFlip,\n });\n }\n\n /**\n * @param {GetAnnotationsParameters} [params] - Annotation parameters.\n * @returns {Promise>} A promise that is resolved with an\n * {Array} of the annotation objects.\n */\n getAnnotations({ intent = \"display\" } = {}) {\n const { renderingIntent } = this._transport.getRenderingIntent(intent);\n\n return this._transport.getAnnotations(this._pageIndex, renderingIntent);\n }\n\n /**\n * @returns {Promise} A promise that is resolved with an\n * {Object} with JS actions.\n */\n getJSActions() {\n return this._transport.getPageJSActions(this._pageIndex);\n }\n\n /**\n * @type {Object} The filter factory instance.\n */\n get filterFactory() {\n return this._transport.filterFactory;\n }\n\n /**\n * @type {boolean} True if only XFA form.\n */\n get isPureXfa() {\n return shadow(this, \"isPureXfa\", !!this._transport._htmlForXfa);\n }\n\n /**\n * @returns {Promise} A promise that is resolved with\n * an {Object} with a fake DOM object (a tree structure where elements\n * are {Object} with a name, attributes (class, style, ...), value and\n * children, very similar to a HTML DOM tree), or `null` if no XFA exists.\n */\n async getXfa() {\n return this._transport._htmlForXfa?.children[this._pageIndex] || null;\n }\n\n /**\n * Begins the process of rendering a page to the desired context.\n *\n * @param {RenderParameters} params - Page render parameters.\n * @returns {RenderTask} An object that contains a promise that is\n * resolved when the page finishes rendering.\n */\n render({\n canvasContext,\n viewport,\n intent = \"display\",\n annotationMode = AnnotationMode.ENABLE,\n transform = null,\n background = null,\n optionalContentConfigPromise = null,\n annotationCanvasMap = null,\n pageColors = null,\n printAnnotationStorage = null,\n isEditing = false,\n }) {\n this._stats?.time(\"Overall\");\n\n const intentArgs = this._transport.getRenderingIntent(\n intent,\n annotationMode,\n printAnnotationStorage,\n isEditing\n );\n const { renderingIntent, cacheKey } = intentArgs;\n // If there was a pending destroy, cancel it so no cleanup happens during\n // this call to render...\n this.#pendingCleanup = false;\n // ... and ensure that a delayed cleanup is always aborted.\n this.#abortDelayedCleanup();\n\n optionalContentConfigPromise ||=\n this._transport.getOptionalContentConfig(renderingIntent);\n\n let intentState = this._intentStates.get(cacheKey);\n if (!intentState) {\n intentState = Object.create(null);\n this._intentStates.set(cacheKey, intentState);\n }\n\n // Ensure that a pending `streamReader` cancel timeout is always aborted.\n if (intentState.streamReaderCancelTimeout) {\n clearTimeout(intentState.streamReaderCancelTimeout);\n intentState.streamReaderCancelTimeout = null;\n }\n\n const intentPrint = !!(renderingIntent & RenderingIntentFlag.PRINT);\n\n // If there's no displayReadyCapability yet, then the operatorList\n // was never requested before. Make the request and create the promise.\n if (!intentState.displayReadyCapability) {\n intentState.displayReadyCapability = Promise.withResolvers();\n intentState.operatorList = {\n fnArray: [],\n argsArray: [],\n lastChunk: false,\n separateAnnots: null,\n };\n\n this._stats?.time(\"Page Request\");\n this._pumpOperatorList(intentArgs);\n }\n\n const complete = error => {\n intentState.renderTasks.delete(internalRenderTask);\n\n // Attempt to reduce memory usage during *printing*, by always running\n // cleanup immediately once rendering has finished.\n if (this._maybeCleanupAfterRender || intentPrint) {\n this.#pendingCleanup = true;\n }\n this.#tryCleanup(/* delayed = */ !intentPrint);\n\n if (error) {\n internalRenderTask.capability.reject(error);\n\n this._abortOperatorList({\n intentState,\n reason: error instanceof Error ? error : new Error(error),\n });\n } else {\n internalRenderTask.capability.resolve();\n }\n\n if (this._stats) {\n this._stats.timeEnd(\"Rendering\");\n this._stats.timeEnd(\"Overall\");\n\n if (globalThis.Stats?.enabled) {\n globalThis.Stats.add(this.pageNumber, this._stats);\n }\n }\n };\n\n const internalRenderTask = new InternalRenderTask({\n callback: complete,\n // Only include the required properties, and *not* the entire object.\n params: {\n canvasContext,\n viewport,\n transform,\n background,\n },\n objs: this.objs,\n commonObjs: this.commonObjs,\n annotationCanvasMap,\n operatorList: intentState.operatorList,\n pageIndex: this._pageIndex,\n canvasFactory: this._transport.canvasFactory,\n filterFactory: this._transport.filterFactory,\n useRequestAnimationFrame: !intentPrint,\n pdfBug: this._pdfBug,\n pageColors,\n });\n\n (intentState.renderTasks ||= new Set()).add(internalRenderTask);\n const renderTask = internalRenderTask.task;\n\n Promise.all([\n intentState.displayReadyCapability.promise,\n optionalContentConfigPromise,\n ])\n .then(([transparency, optionalContentConfig]) => {\n if (this.destroyed) {\n complete();\n return;\n }\n this._stats?.time(\"Rendering\");\n\n if (!(optionalContentConfig.renderingIntent & renderingIntent)) {\n throw new Error(\n \"Must use the same `intent`-argument when calling the `PDFPageProxy.render` \" +\n \"and `PDFDocumentProxy.getOptionalContentConfig` methods.\"\n );\n }\n internalRenderTask.initializeGraphics({\n transparency,\n optionalContentConfig,\n });\n internalRenderTask.operatorListChanged();\n })\n .catch(complete);\n\n return renderTask;\n }\n\n /**\n * @param {GetOperatorListParameters} params - Page getOperatorList\n * parameters.\n * @returns {Promise} A promise resolved with an\n * {@link PDFOperatorList} object that represents the page's operator list.\n */\n getOperatorList({\n intent = \"display\",\n annotationMode = AnnotationMode.ENABLE,\n printAnnotationStorage = null,\n isEditing = false,\n } = {}) {\n if (typeof PDFJSDev !== \"undefined\" && !PDFJSDev.test(\"GENERIC\")) {\n throw new Error(\"Not implemented: getOperatorList\");\n }\n function operatorListChanged() {\n if (intentState.operatorList.lastChunk) {\n intentState.opListReadCapability.resolve(intentState.operatorList);\n\n intentState.renderTasks.delete(opListTask);\n }\n }\n\n const intentArgs = this._transport.getRenderingIntent(\n intent,\n annotationMode,\n printAnnotationStorage,\n isEditing,\n /* isOpList = */ true\n );\n let intentState = this._intentStates.get(intentArgs.cacheKey);\n if (!intentState) {\n intentState = Object.create(null);\n this._intentStates.set(intentArgs.cacheKey, intentState);\n }\n let opListTask;\n\n if (!intentState.opListReadCapability) {\n opListTask = Object.create(null);\n opListTask.operatorListChanged = operatorListChanged;\n intentState.opListReadCapability = Promise.withResolvers();\n (intentState.renderTasks ||= new Set()).add(opListTask);\n intentState.operatorList = {\n fnArray: [],\n argsArray: [],\n lastChunk: false,\n separateAnnots: null,\n };\n\n this._stats?.time(\"Page Request\");\n this._pumpOperatorList(intentArgs);\n }\n return intentState.opListReadCapability.promise;\n }\n\n /**\n * NOTE: All occurrences of whitespace will be replaced by\n * standard spaces (0x20).\n *\n * @param {getTextContentParameters} params - getTextContent parameters.\n * @returns {ReadableStream} Stream for reading text content chunks.\n */\n streamTextContent({\n includeMarkedContent = false,\n disableNormalization = false,\n } = {}) {\n const TEXT_CONTENT_CHUNK_SIZE = 100;\n\n return this._transport.messageHandler.sendWithStream(\n \"GetTextContent\",\n {\n pageIndex: this._pageIndex,\n includeMarkedContent: includeMarkedContent === true,\n disableNormalization: disableNormalization === true,\n },\n {\n highWaterMark: TEXT_CONTENT_CHUNK_SIZE,\n size(textContent) {\n return textContent.items.length;\n },\n }\n );\n }\n\n /**\n * NOTE: All occurrences of whitespace will be replaced by\n * standard spaces (0x20).\n *\n * @param {getTextContentParameters} params - getTextContent parameters.\n * @returns {Promise} A promise that is resolved with a\n * {@link TextContent} object that represents the page's text content.\n */\n getTextContent(params = {}) {\n if (this._transport._htmlForXfa) {\n // TODO: We need to revisit this once the XFA foreground patch lands and\n // only do this for non-foreground XFA.\n return this.getXfa().then(xfa => XfaText.textContent(xfa));\n }\n const readableStream = this.streamTextContent(params);\n\n return new Promise(function (resolve, reject) {\n function pump() {\n reader.read().then(function ({ value, done }) {\n if (done) {\n resolve(textContent);\n return;\n }\n textContent.lang ??= value.lang;\n Object.assign(textContent.styles, value.styles);\n textContent.items.push(...value.items);\n pump();\n }, reject);\n }\n\n const reader = readableStream.getReader();\n const textContent = {\n items: [],\n styles: Object.create(null),\n lang: null,\n };\n pump();\n });\n }\n\n /**\n * @returns {Promise} A promise that is resolved with a\n * {@link StructTreeNode} object that represents the page's structure tree,\n * or `null` when no structure tree is present for the current page.\n */\n getStructTree() {\n return this._transport.getStructTree(this._pageIndex);\n }\n\n /**\n * Destroys the page object.\n * @private\n */\n _destroy() {\n this.destroyed = true;\n\n const waitOn = [];\n for (const intentState of this._intentStates.values()) {\n this._abortOperatorList({\n intentState,\n reason: new Error(\"Page was destroyed.\"),\n force: true,\n });\n\n if (intentState.opListReadCapability) {\n // Avoid errors below, since the renderTasks are just stubs.\n continue;\n }\n for (const internalRenderTask of intentState.renderTasks) {\n waitOn.push(internalRenderTask.completed);\n internalRenderTask.cancel();\n }\n }\n this.objs.clear();\n this.#pendingCleanup = false;\n this.#abortDelayedCleanup();\n\n return Promise.all(waitOn);\n }\n\n /**\n * Cleans up resources allocated by the page.\n *\n * @param {boolean} [resetStats] - Reset page stats, if enabled.\n * The default value is `false`.\n * @returns {boolean} Indicates if clean-up was successfully run.\n */\n cleanup(resetStats = false) {\n this.#pendingCleanup = true;\n const success = this.#tryCleanup(/* delayed = */ false);\n\n if (resetStats && success) {\n this._stats &&= new StatTimer();\n }\n return success;\n }\n\n /**\n * Attempts to clean up if rendering is in a state where that's possible.\n * @param {boolean} [delayed] - Delay the cleanup, to e.g. improve zooming\n * performance in documents with large images.\n * The default value is `false`.\n * @returns {boolean} Indicates if clean-up was successfully run.\n */\n #tryCleanup(delayed = false) {\n this.#abortDelayedCleanup();\n\n if (!this.#pendingCleanup || this.destroyed) {\n return false;\n }\n if (delayed) {\n this.#delayedCleanupTimeout = setTimeout(() => {\n this.#delayedCleanupTimeout = null;\n this.#tryCleanup(/* delayed = */ false);\n }, DELAYED_CLEANUP_TIMEOUT);\n\n return false;\n }\n for (const { renderTasks, operatorList } of this._intentStates.values()) {\n if (renderTasks.size > 0 || !operatorList.lastChunk) {\n return false;\n }\n }\n this._intentStates.clear();\n this.objs.clear();\n this.#pendingCleanup = false;\n return true;\n }\n\n #abortDelayedCleanup() {\n if (this.#delayedCleanupTimeout) {\n clearTimeout(this.#delayedCleanupTimeout);\n this.#delayedCleanupTimeout = null;\n }\n }\n\n /**\n * @private\n */\n _startRenderPage(transparency, cacheKey) {\n const intentState = this._intentStates.get(cacheKey);\n if (!intentState) {\n return; // Rendering was cancelled.\n }\n this._stats?.timeEnd(\"Page Request\");\n\n // TODO Refactor RenderPageRequest to separate rendering\n // and operator list logic\n intentState.displayReadyCapability?.resolve(transparency);\n }\n\n /**\n * @private\n */\n _renderPageChunk(operatorListChunk, intentState) {\n // Add the new chunk to the current operator list.\n for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {\n intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);\n intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);\n }\n intentState.operatorList.lastChunk = operatorListChunk.lastChunk;\n intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;\n\n // Notify all the rendering tasks there are more operators to be consumed.\n for (const internalRenderTask of intentState.renderTasks) {\n internalRenderTask.operatorListChanged();\n }\n\n if (operatorListChunk.lastChunk) {\n this.#tryCleanup(/* delayed = */ true);\n }\n }\n\n /**\n * @private\n */\n _pumpOperatorList({\n renderingIntent,\n cacheKey,\n annotationStorageSerializable,\n modifiedIds,\n }) {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n assert(\n Number.isInteger(renderingIntent) && renderingIntent > 0,\n '_pumpOperatorList: Expected valid \"renderingIntent\" argument.'\n );\n }\n const { map, transfer } = annotationStorageSerializable;\n\n const readableStream = this._transport.messageHandler.sendWithStream(\n \"GetOperatorList\",\n {\n pageIndex: this._pageIndex,\n intent: renderingIntent,\n cacheKey,\n annotationStorage: map,\n modifiedIds,\n },\n transfer\n );\n const reader = readableStream.getReader();\n\n const intentState = this._intentStates.get(cacheKey);\n intentState.streamReader = reader;\n\n const pump = () => {\n reader.read().then(\n ({ value, done }) => {\n if (done) {\n intentState.streamReader = null;\n return;\n }\n if (this._transport.destroyed) {\n return; // Ignore any pending requests if the worker was terminated.\n }\n this._renderPageChunk(value, intentState);\n pump();\n },\n reason => {\n intentState.streamReader = null;\n\n if (this._transport.destroyed) {\n return; // Ignore any pending requests if the worker was terminated.\n }\n if (intentState.operatorList) {\n // Mark operator list as complete.\n intentState.operatorList.lastChunk = true;\n\n for (const internalRenderTask of intentState.renderTasks) {\n internalRenderTask.operatorListChanged();\n }\n this.#tryCleanup(/* delayed = */ true);\n }\n\n if (intentState.displayReadyCapability) {\n intentState.displayReadyCapability.reject(reason);\n } else if (intentState.opListReadCapability) {\n intentState.opListReadCapability.reject(reason);\n } else {\n throw reason;\n }\n }\n );\n };\n pump();\n }\n\n /**\n * @private\n */\n _abortOperatorList({ intentState, reason, force = false }) {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n assert(\n reason instanceof Error,\n '_abortOperatorList: Expected valid \"reason\" argument.'\n );\n }\n\n if (!intentState.streamReader) {\n return;\n }\n // Ensure that a pending `streamReader` cancel timeout is always aborted.\n if (intentState.streamReaderCancelTimeout) {\n clearTimeout(intentState.streamReaderCancelTimeout);\n intentState.streamReaderCancelTimeout = null;\n }\n\n if (!force) {\n // Ensure that an Error occurring in *only* one `InternalRenderTask`, e.g.\n // multiple render() calls on the same canvas, won't break all rendering.\n if (intentState.renderTasks.size > 0) {\n return;\n }\n // Don't immediately abort parsing on the worker-thread when rendering is\n // cancelled, since that will unnecessarily delay re-rendering when (for\n // partially parsed pages) e.g. zooming/rotation occurs in the viewer.\n if (reason instanceof RenderingCancelledException) {\n let delay = RENDERING_CANCELLED_TIMEOUT;\n if (reason.extraDelay > 0 && reason.extraDelay < /* ms = */ 1000) {\n // Above, we prevent the total delay from becoming arbitrarily large.\n delay += reason.extraDelay;\n }\n\n intentState.streamReaderCancelTimeout = setTimeout(() => {\n intentState.streamReaderCancelTimeout = null;\n this._abortOperatorList({ intentState, reason, force: true });\n }, delay);\n return;\n }\n }\n intentState.streamReader\n .cancel(new AbortException(reason.message))\n .catch(() => {\n // Avoid \"Uncaught promise\" messages in the console.\n });\n intentState.streamReader = null;\n\n if (this._transport.destroyed) {\n return; // Ignore any pending requests if the worker was terminated.\n }\n // Remove the current `intentState`, since a cancelled `getOperatorList`\n // call on the worker-thread cannot be re-started...\n for (const [curCacheKey, curIntentState] of this._intentStates) {\n if (curIntentState === intentState) {\n this._intentStates.delete(curCacheKey);\n break;\n }\n }\n // ... and force clean-up to ensure that any old state is always removed.\n this.cleanup();\n }\n\n /**\n * @type {StatTimer | null} Returns page stats, if enabled; returns `null`\n * otherwise.\n */\n get stats() {\n return this._stats;\n }\n}\n\nclass LoopbackPort {\n #listeners = new Map();\n\n #deferred = Promise.resolve();\n\n postMessage(obj, transfer) {\n const event = {\n data: structuredClone(obj, transfer ? { transfer } : null),\n };\n\n this.#deferred.then(() => {\n for (const [listener] of this.#listeners) {\n listener.call(this, event);\n }\n });\n }\n\n addEventListener(name, listener, options = null) {\n let rmAbort = null;\n if (options?.signal instanceof AbortSignal) {\n const { signal } = options;\n if (signal.aborted) {\n warn(\"LoopbackPort - cannot use an `aborted` signal.\");\n return;\n }\n const onAbort = () => this.removeEventListener(name, listener);\n rmAbort = () => signal.removeEventListener(\"abort\", onAbort);\n\n signal.addEventListener(\"abort\", onAbort);\n }\n this.#listeners.set(listener, rmAbort);\n }\n\n removeEventListener(name, listener) {\n const rmAbort = this.#listeners.get(listener);\n rmAbort?.();\n\n this.#listeners.delete(listener);\n }\n\n terminate() {\n for (const [, rmAbort] of this.#listeners) {\n rmAbort?.();\n }\n this.#listeners.clear();\n }\n}\n\n/**\n * @typedef {Object} PDFWorkerParameters\n * @property {string} [name] - The name of the worker.\n * @property {Worker} [port] - The `workerPort` object.\n * @property {number} [verbosity] - Controls the logging level;\n * the constants from {@link VerbosityLevel} should be used.\n */\n\n/**\n * PDF.js web worker abstraction that controls the instantiation of PDF\n * documents. Message handlers are used to pass information from the main\n * thread to the worker thread and vice versa. If the creation of a web\n * worker is not possible, a \"fake\" worker will be used instead.\n *\n * @param {PDFWorkerParameters} params - The worker initialization parameters.\n */\nclass PDFWorker {\n static #fakeWorkerId = 0;\n\n static #isWorkerDisabled = false;\n\n static #workerPorts;\n\n static {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) {\n if (isNodeJS) {\n // Workers aren't supported in Node.js, force-disabling them there.\n this.#isWorkerDisabled = true;\n\n GlobalWorkerOptions.workerSrc ||= PDFJSDev.test(\"LIB\")\n ? \"../pdf.worker.js\"\n : \"./pdf.worker.mjs\";\n }\n\n // Check if URLs have the same origin. For non-HTTP based URLs, returns\n // false.\n this._isSameOrigin = (baseUrl, otherUrl) => {\n let base;\n try {\n base = new URL(baseUrl);\n if (!base.origin || base.origin === \"null\") {\n return false; // non-HTTP url\n }\n } catch {\n return false;\n }\n const other = new URL(otherUrl, base);\n return base.origin === other.origin;\n };\n\n this._createCDNWrapper = url => {\n // We will rely on blob URL's property to specify origin.\n // We want this function to fail in case if createObjectURL or Blob do\n // not exist or fail for some reason -- our Worker creation will fail\n // anyway.\n const wrapper = `await import(\"${url}\");`;\n return URL.createObjectURL(\n new Blob([wrapper], { type: \"text/javascript\" })\n );\n };\n }\n }\n\n constructor({\n name = null,\n port = null,\n verbosity = getVerbosityLevel(),\n } = {}) {\n this.name = name;\n this.destroyed = false;\n this.verbosity = verbosity;\n\n this._readyCapability = Promise.withResolvers();\n this._port = null;\n this._webWorker = null;\n this._messageHandler = null;\n\n if (\n (typeof PDFJSDev === \"undefined\" || !PDFJSDev.test(\"MOZCENTRAL\")) &&\n port\n ) {\n if (PDFWorker.#workerPorts?.has(port)) {\n throw new Error(\"Cannot use more than one PDFWorker per port.\");\n }\n (PDFWorker.#workerPorts ||= new WeakMap()).set(port, this);\n this._initializeFromPort(port);\n return;\n }\n this._initialize();\n }\n\n /**\n * Promise for worker initialization completion.\n * @type {Promise}\n */\n get promise() {\n return this._readyCapability.promise;\n }\n\n #resolve() {\n this._readyCapability.resolve();\n // Send global setting, e.g. verbosity level.\n this._messageHandler.send(\"configure\", {\n verbosity: this.verbosity,\n });\n }\n\n /**\n * The current `workerPort`, when it exists.\n * @type {Worker}\n */\n get port() {\n return this._port;\n }\n\n /**\n * The current MessageHandler-instance.\n * @type {MessageHandler}\n */\n get messageHandler() {\n return this._messageHandler;\n }\n\n _initializeFromPort(port) {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: _initializeFromPort\");\n }\n this._port = port;\n this._messageHandler = new MessageHandler(\"main\", \"worker\", port);\n this._messageHandler.on(\"ready\", function () {\n // Ignoring \"ready\" event -- MessageHandler should already be initialized\n // and ready to accept messages.\n });\n this.#resolve();\n }\n\n _initialize() {\n // If worker support isn't disabled explicit and the browser has worker\n // support, create a new web worker and test if it/the browser fulfills\n // all requirements to run parts of pdf.js in a web worker.\n // Right now, the requirement is, that an Uint8Array is still an\n // Uint8Array as it arrives on the worker.\n if (\n PDFWorker.#isWorkerDisabled ||\n PDFWorker.#mainThreadWorkerMessageHandler\n ) {\n this._setupFakeWorker();\n return;\n }\n let { workerSrc } = PDFWorker;\n\n try {\n // Wraps workerSrc path into blob URL, if the former does not belong\n // to the same origin.\n if (\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"GENERIC\") &&\n !PDFWorker._isSameOrigin(window.location.href, workerSrc)\n ) {\n workerSrc = PDFWorker._createCDNWrapper(\n new URL(workerSrc, window.location).href\n );\n }\n\n const worker = new Worker(workerSrc, { type: \"module\" });\n const messageHandler = new MessageHandler(\"main\", \"worker\", worker);\n const terminateEarly = () => {\n ac.abort();\n messageHandler.destroy();\n worker.terminate();\n if (this.destroyed) {\n this._readyCapability.reject(new Error(\"Worker was destroyed\"));\n } else {\n // Fall back to fake worker if the termination is caused by an\n // error (e.g. NetworkError / SecurityError).\n this._setupFakeWorker();\n }\n };\n\n const ac = new AbortController();\n worker.addEventListener(\n \"error\",\n () => {\n if (!this._webWorker) {\n // Worker failed to initialize due to an error. Clean up and fall\n // back to the fake worker.\n terminateEarly();\n }\n },\n { signal: ac.signal }\n );\n\n messageHandler.on(\"test\", data => {\n ac.abort();\n if (this.destroyed || !data) {\n terminateEarly();\n return;\n }\n this._messageHandler = messageHandler;\n this._port = worker;\n this._webWorker = worker;\n\n this.#resolve();\n });\n\n messageHandler.on(\"ready\", data => {\n ac.abort();\n if (this.destroyed) {\n terminateEarly();\n return;\n }\n try {\n sendTest();\n } catch {\n // We need fallback to a faked worker.\n this._setupFakeWorker();\n }\n });\n\n const sendTest = () => {\n const testObj = new Uint8Array();\n // Ensure that we can use `postMessage` transfers.\n messageHandler.send(\"test\", testObj, [testObj.buffer]);\n };\n\n // It might take time for the worker to initialize. We will try to send\n // the \"test\" message immediately, and once the \"ready\" message arrives.\n // The worker shall process only the first received \"test\" message.\n sendTest();\n return;\n } catch {\n info(\"The worker has been disabled.\");\n }\n // Either workers are not supported or have thrown an exception.\n // Thus, we fallback to a faked worker.\n this._setupFakeWorker();\n }\n\n _setupFakeWorker() {\n if (!PDFWorker.#isWorkerDisabled) {\n warn(\"Setting up fake worker.\");\n PDFWorker.#isWorkerDisabled = true;\n }\n\n PDFWorker._setupFakeWorkerGlobal\n .then(WorkerMessageHandler => {\n if (this.destroyed) {\n this._readyCapability.reject(new Error(\"Worker was destroyed\"));\n return;\n }\n const port = new LoopbackPort();\n this._port = port;\n\n // All fake workers use the same port, making id unique.\n const id = `fake${PDFWorker.#fakeWorkerId++}`;\n\n // If the main thread is our worker, setup the handling for the\n // messages -- the main thread sends to it self.\n const workerHandler = new MessageHandler(id + \"_worker\", id, port);\n WorkerMessageHandler.setup(workerHandler, port);\n\n this._messageHandler = new MessageHandler(id, id + \"_worker\", port);\n this.#resolve();\n })\n .catch(reason => {\n this._readyCapability.reject(\n new Error(`Setting up fake worker failed: \"${reason.message}\".`)\n );\n });\n }\n\n /**\n * Destroys the worker instance.\n */\n destroy() {\n this.destroyed = true;\n\n // We need to terminate only web worker created resource.\n this._webWorker?.terminate();\n this._webWorker = null;\n\n PDFWorker.#workerPorts?.delete(this._port);\n this._port = null;\n\n this._messageHandler?.destroy();\n this._messageHandler = null;\n }\n\n /**\n * @param {PDFWorkerParameters} params - The worker initialization parameters.\n */\n static fromPort(params) {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: fromPort\");\n }\n if (!params?.port) {\n throw new Error(\"PDFWorker.fromPort - invalid method signature.\");\n }\n const cachedPort = this.#workerPorts?.get(params.port);\n if (cachedPort) {\n if (cachedPort._pendingDestroy) {\n throw new Error(\n \"PDFWorker.fromPort - the worker is being destroyed.\\n\" +\n \"Please remember to await `PDFDocumentLoadingTask.destroy()`-calls.\"\n );\n }\n return cachedPort;\n }\n return new PDFWorker(params);\n }\n\n /**\n * The current `workerSrc`, when it exists.\n * @type {string}\n */\n static get workerSrc() {\n if (GlobalWorkerOptions.workerSrc) {\n return GlobalWorkerOptions.workerSrc;\n }\n throw new Error('No \"GlobalWorkerOptions.workerSrc\" specified.');\n }\n\n static get #mainThreadWorkerMessageHandler() {\n try {\n return globalThis.pdfjsWorker?.WorkerMessageHandler || null;\n } catch {\n return null;\n }\n }\n\n // Loads worker code into the main-thread.\n static get _setupFakeWorkerGlobal() {\n const loader = async () => {\n if (this.#mainThreadWorkerMessageHandler) {\n // The worker was already loaded using e.g. a ` + + + + + + + +
+ +
+
+
+
+ + + + +
+
+ +
+
+
+ + +
+
+
+
+
+
+ + + +
+
+
+ +
+
+
+
+
+ +
+
+ + +
+
+ +
+ +
+
+ + + + +
+
+
+
+ +
+ +
+ + + +
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+ +
+ + + +
+ +
+ +
+ + +
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+ +
+ +
+ +
+
+ +
+
+ + +
+
+ +
+ File name: +

-

+
+
+ File size: +

-

+
+
+
+ Title: +

-

+
+
+ Author: +

-

+
+
+ Subject: +

-

+
+
+ Keywords: +

-

+
+
+ Creation Date: +

-

+
+
+ Modification Date: +

-

+
+
+ Creator: +

-

+
+
+
+ PDF Producer: +

-

+
+
+ PDF Version: +

-

+
+
+ Page Count: +

-

+
+
+ Page Size: +

-

+
+
+
+ Fast Web View: +

-

+
+
+ +
+
+ +
+
+ Choose an option + + Alt text (alternative text) helps when people can’t see the image or when it doesn’t load. + +
+
+
+
+ + +
+
+ + Aim for 1-2 sentences that describe the subject, setting, or actions. + +
+
+
+ +
+
+
+
+
+ + +
+
+ + This is used for ornamental images, like borders or watermarks. + +
+
+
+
+ + +
+
+
+ +
+
+ Edit alt text (image description) +
+
+
+
+
+
+ +
+ Short description for people who can’t see the image or when the image doesn’t load. +
This alt text was created automatically and may be inaccurate. Learn more
+
+
+ + +
+ +
+
+
+
+
+
+ Couldn’t create alt text automatically + Please write your own alt text or try again later. +
+ +
+
+
+ + + +
+
+
+ + +
+
+ Image alt text settings +
+
+ Automatic alt text +
+
+
+ + +
+
+ Suggests descriptions to help people who can’t see the image or when the image doesn’t load. Learn more +
+
+
+
+ Alt text AI model (180MB) +
+ Runs locally on your device so your data stays private. Required for automatic alt text. +
+
+ + +
+
+
+
+
+ Alt text editor +
+
+ + +
+
+ Helps you make sure all your images have alt text. +
+
+
+
+ +
+
+
+ +
+ Preparing document for printing… +
+
+ + 0% +
+
+ +
+
+
+ + + +
+
+ + diff --git a/pdfjs/web/viewer.mjs b/pdfjs/web/viewer.mjs new file mode 100644 index 0000000..da3d43d --- /dev/null +++ b/pdfjs/web/viewer.mjs @@ -0,0 +1,15428 @@ +/** + * @licstart The following is the entire license notice for the + * JavaScript code in this page + * + * Copyright 2024 Mozilla Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @licend The above is the entire license notice for the + * JavaScript code in this page + */ + +/******/ // The require scope +/******/ var __webpack_require__ = {}; +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __webpack_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/************************************************************************/ +var __webpack_exports__ = {}; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + PDFViewerApplication: () => (/* reexport */ PDFViewerApplication), + PDFViewerApplicationConstants: () => (/* binding */ AppConstants), + PDFViewerApplicationOptions: () => (/* reexport */ AppOptions) +}); + +;// ./web/ui_utils.js +const DEFAULT_SCALE_VALUE = "auto"; +const DEFAULT_SCALE = 1.0; +const DEFAULT_SCALE_DELTA = 1.1; +const MIN_SCALE = 0.1; +const MAX_SCALE = 10.0; +const UNKNOWN_SCALE = 0; +const MAX_AUTO_SCALE = 1.25; +const SCROLLBAR_PADDING = 40; +const VERTICAL_PADDING = 5; +const RenderingStates = { + INITIAL: 0, + RUNNING: 1, + PAUSED: 2, + FINISHED: 3 +}; +const PresentationModeState = { + UNKNOWN: 0, + NORMAL: 1, + CHANGING: 2, + FULLSCREEN: 3 +}; +const SidebarView = { + UNKNOWN: -1, + NONE: 0, + THUMBS: 1, + OUTLINE: 2, + ATTACHMENTS: 3, + LAYERS: 4 +}; +const TextLayerMode = { + DISABLE: 0, + ENABLE: 1, + ENABLE_PERMISSIONS: 2 +}; +const ScrollMode = { + UNKNOWN: -1, + VERTICAL: 0, + HORIZONTAL: 1, + WRAPPED: 2, + PAGE: 3 +}; +const SpreadMode = { + UNKNOWN: -1, + NONE: 0, + ODD: 1, + EVEN: 2 +}; +const CursorTool = { + SELECT: 0, + HAND: 1, + ZOOM: 2 +}; +const AutoPrintRegExp = /\bprint\s*\(/; +function scrollIntoView(element, spot, scrollMatches = false) { + let parent = element.offsetParent; + if (!parent) { + console.error("offsetParent is not set -- cannot scroll"); + return; + } + let offsetY = element.offsetTop + element.clientTop; + let offsetX = element.offsetLeft + element.clientLeft; + while (parent.clientHeight === parent.scrollHeight && parent.clientWidth === parent.scrollWidth || scrollMatches && (parent.classList.contains("markedContent") || getComputedStyle(parent).overflow === "hidden")) { + offsetY += parent.offsetTop; + offsetX += parent.offsetLeft; + parent = parent.offsetParent; + if (!parent) { + return; + } + } + if (spot) { + if (spot.top !== undefined) { + offsetY += spot.top; + } + if (spot.left !== undefined) { + offsetX += spot.left; + parent.scrollLeft = offsetX; + } + } + parent.scrollTop = offsetY; +} +function watchScroll(viewAreaElement, callback, abortSignal = undefined) { + const debounceScroll = function (evt) { + if (rAF) { + return; + } + rAF = window.requestAnimationFrame(function viewAreaElementScrolled() { + rAF = null; + const currentX = viewAreaElement.scrollLeft; + const lastX = state.lastX; + if (currentX !== lastX) { + state.right = currentX > lastX; + } + state.lastX = currentX; + const currentY = viewAreaElement.scrollTop; + const lastY = state.lastY; + if (currentY !== lastY) { + state.down = currentY > lastY; + } + state.lastY = currentY; + callback(state); + }); + }; + const state = { + right: true, + down: true, + lastX: viewAreaElement.scrollLeft, + lastY: viewAreaElement.scrollTop, + _eventHandler: debounceScroll + }; + let rAF = null; + viewAreaElement.addEventListener("scroll", debounceScroll, { + useCapture: true, + signal: abortSignal + }); + abortSignal?.addEventListener("abort", () => window.cancelAnimationFrame(rAF), { + once: true + }); + return state; +} +function parseQueryString(query) { + const params = new Map(); + for (const [key, value] of new URLSearchParams(query)) { + params.set(key.toLowerCase(), value); + } + return params; +} +const InvisibleCharsRegExp = /[\x00-\x1F]/g; +function removeNullCharacters(str, replaceInvisible = false) { + if (!InvisibleCharsRegExp.test(str)) { + return str; + } + if (replaceInvisible) { + return str.replaceAll(InvisibleCharsRegExp, m => m === "\x00" ? "" : " "); + } + return str.replaceAll("\x00", ""); +} +function binarySearchFirstItem(items, condition, start = 0) { + let minIndex = start; + let maxIndex = items.length - 1; + if (maxIndex < 0 || !condition(items[maxIndex])) { + return items.length; + } + if (condition(items[minIndex])) { + return minIndex; + } + while (minIndex < maxIndex) { + const currentIndex = minIndex + maxIndex >> 1; + const currentItem = items[currentIndex]; + if (condition(currentItem)) { + maxIndex = currentIndex; + } else { + minIndex = currentIndex + 1; + } + } + return minIndex; +} +function approximateFraction(x) { + if (Math.floor(x) === x) { + return [x, 1]; + } + const xinv = 1 / x; + const limit = 8; + if (xinv > limit) { + return [1, limit]; + } else if (Math.floor(xinv) === xinv) { + return [1, xinv]; + } + const x_ = x > 1 ? xinv : x; + let a = 0, + b = 1, + c = 1, + d = 1; + while (true) { + const p = a + c, + q = b + d; + if (q > limit) { + break; + } + if (x_ <= p / q) { + c = p; + d = q; + } else { + a = p; + b = q; + } + } + let result; + if (x_ - a / b < c / d - x_) { + result = x_ === x ? [a, b] : [b, a]; + } else { + result = x_ === x ? [c, d] : [d, c]; + } + return result; +} +function floorToDivide(x, div) { + return x - x % div; +} +function getPageSizeInches({ + view, + userUnit, + rotate +}) { + const [x1, y1, x2, y2] = view; + const changeOrientation = rotate % 180 !== 0; + const width = (x2 - x1) / 72 * userUnit; + const height = (y2 - y1) / 72 * userUnit; + return { + width: changeOrientation ? height : width, + height: changeOrientation ? width : height + }; +} +function backtrackBeforeAllVisibleElements(index, views, top) { + if (index < 2) { + return index; + } + let elt = views[index].div; + let pageTop = elt.offsetTop + elt.clientTop; + if (pageTop >= top) { + elt = views[index - 1].div; + pageTop = elt.offsetTop + elt.clientTop; + } + for (let i = index - 2; i >= 0; --i) { + elt = views[i].div; + if (elt.offsetTop + elt.clientTop + elt.clientHeight <= pageTop) { + break; + } + index = i; + } + return index; +} +function getVisibleElements({ + scrollEl, + views, + sortByVisibility = false, + horizontal = false, + rtl = false +}) { + const top = scrollEl.scrollTop, + bottom = top + scrollEl.clientHeight; + const left = scrollEl.scrollLeft, + right = left + scrollEl.clientWidth; + function isElementBottomAfterViewTop(view) { + const element = view.div; + const elementBottom = element.offsetTop + element.clientTop + element.clientHeight; + return elementBottom > top; + } + function isElementNextAfterViewHorizontally(view) { + const element = view.div; + const elementLeft = element.offsetLeft + element.clientLeft; + const elementRight = elementLeft + element.clientWidth; + return rtl ? elementLeft < right : elementRight > left; + } + const visible = [], + ids = new Set(), + numViews = views.length; + let firstVisibleElementInd = binarySearchFirstItem(views, horizontal ? isElementNextAfterViewHorizontally : isElementBottomAfterViewTop); + if (firstVisibleElementInd > 0 && firstVisibleElementInd < numViews && !horizontal) { + firstVisibleElementInd = backtrackBeforeAllVisibleElements(firstVisibleElementInd, views, top); + } + let lastEdge = horizontal ? right : -1; + for (let i = firstVisibleElementInd; i < numViews; i++) { + const view = views[i], + element = view.div; + const currentWidth = element.offsetLeft + element.clientLeft; + const currentHeight = element.offsetTop + element.clientTop; + const viewWidth = element.clientWidth, + viewHeight = element.clientHeight; + const viewRight = currentWidth + viewWidth; + const viewBottom = currentHeight + viewHeight; + if (lastEdge === -1) { + if (viewBottom >= bottom) { + lastEdge = viewBottom; + } + } else if ((horizontal ? currentWidth : currentHeight) > lastEdge) { + break; + } + if (viewBottom <= top || currentHeight >= bottom || viewRight <= left || currentWidth >= right) { + continue; + } + const hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, viewBottom - bottom); + const hiddenWidth = Math.max(0, left - currentWidth) + Math.max(0, viewRight - right); + const fractionHeight = (viewHeight - hiddenHeight) / viewHeight, + fractionWidth = (viewWidth - hiddenWidth) / viewWidth; + const percent = fractionHeight * fractionWidth * 100 | 0; + visible.push({ + id: view.id, + x: currentWidth, + y: currentHeight, + view, + percent, + widthPercent: fractionWidth * 100 | 0 + }); + ids.add(view.id); + } + const first = visible[0], + last = visible.at(-1); + if (sortByVisibility) { + visible.sort(function (a, b) { + const pc = a.percent - b.percent; + if (Math.abs(pc) > 0.001) { + return -pc; + } + return a.id - b.id; + }); + } + return { + first, + last, + views: visible, + ids + }; +} +function normalizeWheelEventDirection(evt) { + let delta = Math.hypot(evt.deltaX, evt.deltaY); + const angle = Math.atan2(evt.deltaY, evt.deltaX); + if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) { + delta = -delta; + } + return delta; +} +function normalizeWheelEventDelta(evt) { + const deltaMode = evt.deltaMode; + let delta = normalizeWheelEventDirection(evt); + const MOUSE_PIXELS_PER_LINE = 30; + const MOUSE_LINES_PER_PAGE = 30; + if (deltaMode === WheelEvent.DOM_DELTA_PIXEL) { + delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE; + } else if (deltaMode === WheelEvent.DOM_DELTA_LINE) { + delta /= MOUSE_LINES_PER_PAGE; + } + return delta; +} +function isValidRotation(angle) { + return Number.isInteger(angle) && angle % 90 === 0; +} +function isValidScrollMode(mode) { + return Number.isInteger(mode) && Object.values(ScrollMode).includes(mode) && mode !== ScrollMode.UNKNOWN; +} +function isValidSpreadMode(mode) { + return Number.isInteger(mode) && Object.values(SpreadMode).includes(mode) && mode !== SpreadMode.UNKNOWN; +} +function isPortraitOrientation(size) { + return size.width <= size.height; +} +const animationStarted = new Promise(function (resolve) { + window.requestAnimationFrame(resolve); +}); +const docStyle = document.documentElement.style; +function clamp(v, min, max) { + return Math.min(Math.max(v, min), max); +} +class ProgressBar { + #classList = null; + #disableAutoFetchTimeout = null; + #percent = 0; + #style = null; + #visible = true; + constructor(bar) { + this.#classList = bar.classList; + this.#style = bar.style; + } + get percent() { + return this.#percent; + } + set percent(val) { + this.#percent = clamp(val, 0, 100); + if (isNaN(val)) { + this.#classList.add("indeterminate"); + return; + } + this.#classList.remove("indeterminate"); + this.#style.setProperty("--progressBar-percent", `${this.#percent}%`); + } + setWidth(viewer) { + if (!viewer) { + return; + } + const container = viewer.parentNode; + const scrollbarWidth = container.offsetWidth - viewer.offsetWidth; + if (scrollbarWidth > 0) { + this.#style.setProperty("--progressBar-end-offset", `${scrollbarWidth}px`); + } + } + setDisableAutoFetch(delay = 5000) { + if (this.#percent === 100 || isNaN(this.#percent)) { + return; + } + if (this.#disableAutoFetchTimeout) { + clearTimeout(this.#disableAutoFetchTimeout); + } + this.show(); + this.#disableAutoFetchTimeout = setTimeout(() => { + this.#disableAutoFetchTimeout = null; + this.hide(); + }, delay); + } + hide() { + if (!this.#visible) { + return; + } + this.#visible = false; + this.#classList.add("hidden"); + } + show() { + if (this.#visible) { + return; + } + this.#visible = true; + this.#classList.remove("hidden"); + } +} +function getActiveOrFocusedElement() { + let curRoot = document; + let curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus"); + while (curActiveOrFocused?.shadowRoot) { + curRoot = curActiveOrFocused.shadowRoot; + curActiveOrFocused = curRoot.activeElement || curRoot.querySelector(":focus"); + } + return curActiveOrFocused; +} +function apiPageLayoutToViewerModes(layout) { + let scrollMode = ScrollMode.VERTICAL, + spreadMode = SpreadMode.NONE; + switch (layout) { + case "SinglePage": + scrollMode = ScrollMode.PAGE; + break; + case "OneColumn": + break; + case "TwoPageLeft": + scrollMode = ScrollMode.PAGE; + case "TwoColumnLeft": + spreadMode = SpreadMode.ODD; + break; + case "TwoPageRight": + scrollMode = ScrollMode.PAGE; + case "TwoColumnRight": + spreadMode = SpreadMode.EVEN; + break; + } + return { + scrollMode, + spreadMode + }; +} +function apiPageModeToSidebarView(mode) { + switch (mode) { + case "UseNone": + return SidebarView.NONE; + case "UseThumbs": + return SidebarView.THUMBS; + case "UseOutlines": + return SidebarView.OUTLINE; + case "UseAttachments": + return SidebarView.ATTACHMENTS; + case "UseOC": + return SidebarView.LAYERS; + } + return SidebarView.NONE; +} +function toggleCheckedBtn(button, toggle, view = null) { + button.classList.toggle("toggled", toggle); + button.setAttribute("aria-checked", toggle); + view?.classList.toggle("hidden", !toggle); +} +function toggleExpandedBtn(button, toggle, view = null) { + button.classList.toggle("toggled", toggle); + button.setAttribute("aria-expanded", toggle); + view?.classList.toggle("hidden", !toggle); +} +const calcRound = function () { + const e = document.createElement("div"); + e.style.width = "round(down, calc(1.6666666666666665 * 792px), 1px)"; + return e.style.width === "calc(1320px)" ? Math.fround : x => x; +}(); + +;// ./web/app_options.js +{ + var compatParams = new Map(); + const userAgent = navigator.userAgent || ""; + const platform = navigator.platform || ""; + const maxTouchPoints = navigator.maxTouchPoints || 1; + const isAndroid = /Android/.test(userAgent); + const isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent) || platform === "MacIntel" && maxTouchPoints > 1; + (function () { + if (isIOS || isAndroid) { + compatParams.set("maxCanvasPixels", 5242880); + } + })(); + (function () { + if (isAndroid) { + compatParams.set("useSystemFonts", false); + } + })(); +} +const OptionKind = { + BROWSER: 0x01, + VIEWER: 0x02, + API: 0x04, + WORKER: 0x08, + EVENT_DISPATCH: 0x10, + PREFERENCE: 0x80 +}; +const Type = { + BOOLEAN: 0x01, + NUMBER: 0x02, + OBJECT: 0x04, + STRING: 0x08, + UNDEFINED: 0x10 +}; +const defaultOptions = { + allowedGlobalEvents: { + value: null, + kind: OptionKind.BROWSER + }, + canvasMaxAreaInBytes: { + value: -1, + kind: OptionKind.BROWSER + OptionKind.API + }, + isInAutomation: { + value: false, + kind: OptionKind.BROWSER + }, + localeProperties: { + value: { + lang: navigator.language || "en-US" + }, + kind: OptionKind.BROWSER + }, + nimbusDataStr: { + value: "", + kind: OptionKind.BROWSER + }, + supportsCaretBrowsingMode: { + value: false, + kind: OptionKind.BROWSER + }, + supportsDocumentFonts: { + value: true, + kind: OptionKind.BROWSER + }, + supportsIntegratedFind: { + value: false, + kind: OptionKind.BROWSER + }, + supportsMouseWheelZoomCtrlKey: { + value: true, + kind: OptionKind.BROWSER + }, + supportsMouseWheelZoomMetaKey: { + value: true, + kind: OptionKind.BROWSER + }, + supportsPinchToZoom: { + value: true, + kind: OptionKind.BROWSER + }, + toolbarDensity: { + value: 0, + kind: OptionKind.BROWSER + OptionKind.EVENT_DISPATCH + }, + altTextLearnMoreUrl: { + value: "", + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + annotationEditorMode: { + value: 0, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + annotationMode: { + value: 2, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + cursorToolOnLoad: { + value: 0, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + debuggerSrc: { + value: "./debugger.mjs", + kind: OptionKind.VIEWER + }, + defaultZoomDelay: { + value: 400, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + defaultZoomValue: { + value: "", + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + disableHistory: { + value: false, + kind: OptionKind.VIEWER + }, + disablePageLabels: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enableAltText: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enableAltTextModelDownload: { + value: true, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH + }, + enableGuessAltText: { + value: true, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH + }, + enableHighlightFloatingButton: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enableNewAltTextWhenAddingImage: { + value: true, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enablePermissions: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enablePrintAutoRotate: { + value: true, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enableScripting: { + value: true, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enableUpdatedAddImage: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + externalLinkRel: { + value: "noopener noreferrer nofollow", + kind: OptionKind.VIEWER + }, + externalLinkTarget: { + value: 0, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + highlightEditorColors: { + value: "yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F", + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + historyUpdateUrl: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + ignoreDestinationZoom: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + imageResourcesPath: { + value: "./images/", + kind: OptionKind.VIEWER + }, + maxCanvasPixels: { + value: 2 ** 25, + kind: OptionKind.VIEWER + }, + forcePageColors: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + pageColorsBackground: { + value: "Canvas", + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + pageColorsForeground: { + value: "CanvasText", + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + pdfBugEnabled: { + value: false, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + printResolution: { + value: 150, + kind: OptionKind.VIEWER + }, + sidebarViewOnLoad: { + value: -1, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + scrollModeOnLoad: { + value: -1, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + spreadModeOnLoad: { + value: -1, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + textLayerMode: { + value: 1, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + viewOnLoad: { + value: 0, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }, + cMapPacked: { + value: true, + kind: OptionKind.API + }, + cMapUrl: { + value: "../web/cmaps/", + kind: OptionKind.API + }, + disableAutoFetch: { + value: false, + kind: OptionKind.API + OptionKind.PREFERENCE + }, + disableFontFace: { + value: false, + kind: OptionKind.API + OptionKind.PREFERENCE + }, + disableRange: { + value: false, + kind: OptionKind.API + OptionKind.PREFERENCE + }, + disableStream: { + value: false, + kind: OptionKind.API + OptionKind.PREFERENCE + }, + docBaseUrl: { + value: "", + kind: OptionKind.API + }, + enableHWA: { + value: true, + kind: OptionKind.API + OptionKind.VIEWER + OptionKind.PREFERENCE + }, + enableXfa: { + value: true, + kind: OptionKind.API + OptionKind.PREFERENCE + }, + fontExtraProperties: { + value: false, + kind: OptionKind.API + }, + isEvalSupported: { + value: true, + kind: OptionKind.API + }, + isOffscreenCanvasSupported: { + value: true, + kind: OptionKind.API + }, + maxImageSize: { + value: -1, + kind: OptionKind.API + }, + pdfBug: { + value: false, + kind: OptionKind.API + }, + standardFontDataUrl: { + value: "../web/standard_fonts/", + kind: OptionKind.API + }, + useSystemFonts: { + value: undefined, + kind: OptionKind.API, + type: Type.BOOLEAN + Type.UNDEFINED + }, + verbosity: { + value: 1, + kind: OptionKind.API + }, + workerPort: { + value: null, + kind: OptionKind.WORKER + }, + workerSrc: { + value: "../build/pdf.worker.mjs", + kind: OptionKind.WORKER + } +}; +{ + defaultOptions.defaultUrl = { + value: "compressed.tracemonkey-pldi-09.pdf", + kind: OptionKind.VIEWER + }; + defaultOptions.sandboxBundleSrc = { + value: "../build/pdf.sandbox.mjs", + kind: OptionKind.VIEWER + }; + defaultOptions.viewerCssTheme = { + value: 0, + kind: OptionKind.VIEWER + OptionKind.PREFERENCE + }; + defaultOptions.enableFakeMLManager = { + value: true, + kind: OptionKind.VIEWER + }; +} +{ + defaultOptions.disablePreferences = { + value: false, + kind: OptionKind.VIEWER + }; +} +class AppOptions { + static eventBus; + static #opts = new Map(); + static { + for (const name in defaultOptions) { + this.#opts.set(name, defaultOptions[name].value); + } + for (const [name, value] of compatParams) { + this.#opts.set(name, value); + } + this._hasInvokedSet = false; + this._checkDisablePreferences = () => { + if (this.get("disablePreferences")) { + return true; + } + if (this._hasInvokedSet) { + console.warn("The Preferences may override manually set AppOptions; " + 'please use the "disablePreferences"-option to prevent that.'); + } + return false; + }; + } + static get(name) { + return this.#opts.get(name); + } + static getAll(kind = null, defaultOnly = false) { + const options = Object.create(null); + for (const name in defaultOptions) { + const defaultOpt = defaultOptions[name]; + if (kind && !(kind & defaultOpt.kind)) { + continue; + } + options[name] = !defaultOnly ? this.#opts.get(name) : defaultOpt.value; + } + return options; + } + static set(name, value) { + this.setAll({ + [name]: value + }); + } + static setAll(options, prefs = false) { + this._hasInvokedSet ||= true; + let events; + for (const name in options) { + const defaultOpt = defaultOptions[name], + userOpt = options[name]; + if (!defaultOpt || !(typeof userOpt === typeof defaultOpt.value || Type[(typeof userOpt).toUpperCase()] & defaultOpt.type)) { + continue; + } + const { + kind + } = defaultOpt; + if (prefs && !(kind & OptionKind.BROWSER || kind & OptionKind.PREFERENCE)) { + continue; + } + if (this.eventBus && kind & OptionKind.EVENT_DISPATCH) { + (events ||= new Map()).set(name, userOpt); + } + this.#opts.set(name, userOpt); + } + if (events) { + for (const [name, value] of events) { + this.eventBus.dispatch(name.toLowerCase(), { + source: this, + value + }); + } + } + } +} + +;// ./web/pdf_link_service.js + +const DEFAULT_LINK_REL = "noopener noreferrer nofollow"; +const LinkTarget = { + NONE: 0, + SELF: 1, + BLANK: 2, + PARENT: 3, + TOP: 4 +}; +class PDFLinkService { + externalLinkEnabled = true; + constructor({ + eventBus, + externalLinkTarget = null, + externalLinkRel = null, + ignoreDestinationZoom = false + } = {}) { + this.eventBus = eventBus; + this.externalLinkTarget = externalLinkTarget; + this.externalLinkRel = externalLinkRel; + this._ignoreDestinationZoom = ignoreDestinationZoom; + this.baseUrl = null; + this.pdfDocument = null; + this.pdfViewer = null; + this.pdfHistory = null; + } + setDocument(pdfDocument, baseUrl = null) { + this.baseUrl = baseUrl; + this.pdfDocument = pdfDocument; + } + setViewer(pdfViewer) { + this.pdfViewer = pdfViewer; + } + setHistory(pdfHistory) { + this.pdfHistory = pdfHistory; + } + get pagesCount() { + return this.pdfDocument ? this.pdfDocument.numPages : 0; + } + get page() { + return this.pdfDocument ? this.pdfViewer.currentPageNumber : 1; + } + set page(value) { + if (this.pdfDocument) { + this.pdfViewer.currentPageNumber = value; + } + } + get rotation() { + return this.pdfDocument ? this.pdfViewer.pagesRotation : 0; + } + set rotation(value) { + if (this.pdfDocument) { + this.pdfViewer.pagesRotation = value; + } + } + get isInPresentationMode() { + return this.pdfDocument ? this.pdfViewer.isInPresentationMode : false; + } + async goToDestination(dest) { + if (!this.pdfDocument) { + return; + } + let namedDest, explicitDest, pageNumber; + if (typeof dest === "string") { + namedDest = dest; + explicitDest = await this.pdfDocument.getDestination(dest); + } else { + namedDest = null; + explicitDest = await dest; + } + if (!Array.isArray(explicitDest)) { + console.error(`goToDestination: "${explicitDest}" is not a valid destination array, for dest="${dest}".`); + return; + } + const [destRef] = explicitDest; + if (destRef && typeof destRef === "object") { + pageNumber = this.pdfDocument.cachedPageNumber(destRef); + if (!pageNumber) { + try { + pageNumber = (await this.pdfDocument.getPageIndex(destRef)) + 1; + } catch { + console.error(`goToDestination: "${destRef}" is not a valid page reference, for dest="${dest}".`); + return; + } + } + } else if (Number.isInteger(destRef)) { + pageNumber = destRef + 1; + } + if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) { + console.error(`goToDestination: "${pageNumber}" is not a valid page number, for dest="${dest}".`); + return; + } + if (this.pdfHistory) { + this.pdfHistory.pushCurrentPosition(); + this.pdfHistory.push({ + namedDest, + explicitDest, + pageNumber + }); + } + this.pdfViewer.scrollPageIntoView({ + pageNumber, + destArray: explicitDest, + ignoreDestinationZoom: this._ignoreDestinationZoom + }); + } + goToPage(val) { + if (!this.pdfDocument) { + return; + } + const pageNumber = typeof val === "string" && this.pdfViewer.pageLabelToPageNumber(val) || val | 0; + if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) { + console.error(`PDFLinkService.goToPage: "${val}" is not a valid page.`); + return; + } + if (this.pdfHistory) { + this.pdfHistory.pushCurrentPosition(); + this.pdfHistory.pushPage(pageNumber); + } + this.pdfViewer.scrollPageIntoView({ + pageNumber + }); + } + addLinkAttributes(link, url, newWindow = false) { + if (!url || typeof url !== "string") { + throw new Error('A valid "url" parameter must provided.'); + } + const target = newWindow ? LinkTarget.BLANK : this.externalLinkTarget, + rel = this.externalLinkRel; + if (this.externalLinkEnabled) { + link.href = link.title = url; + } else { + link.href = ""; + link.title = `Disabled: ${url}`; + link.onclick = () => false; + } + let targetStr = ""; + switch (target) { + case LinkTarget.NONE: + break; + case LinkTarget.SELF: + targetStr = "_self"; + break; + case LinkTarget.BLANK: + targetStr = "_blank"; + break; + case LinkTarget.PARENT: + targetStr = "_parent"; + break; + case LinkTarget.TOP: + targetStr = "_top"; + break; + } + link.target = targetStr; + link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL; + } + getDestinationHash(dest) { + if (typeof dest === "string") { + if (dest.length > 0) { + return this.getAnchorUrl("#" + escape(dest)); + } + } else if (Array.isArray(dest)) { + const str = JSON.stringify(dest); + if (str.length > 0) { + return this.getAnchorUrl("#" + escape(str)); + } + } + return this.getAnchorUrl(""); + } + getAnchorUrl(anchor) { + return this.baseUrl ? this.baseUrl + anchor : anchor; + } + setHash(hash) { + if (!this.pdfDocument) { + return; + } + let pageNumber, dest; + if (hash.includes("=")) { + const params = parseQueryString(hash); + if (params.has("search")) { + const query = params.get("search").replaceAll('"', ""), + phrase = params.get("phrase") === "true"; + this.eventBus.dispatch("findfromurlhash", { + source: this, + query: phrase ? query : query.match(/\S+/g) + }); + } + if (params.has("page")) { + pageNumber = params.get("page") | 0 || 1; + } + if (params.has("zoom")) { + const zoomArgs = params.get("zoom").split(","); + const zoomArg = zoomArgs[0]; + const zoomArgNumber = parseFloat(zoomArg); + if (!zoomArg.includes("Fit")) { + dest = [null, { + name: "XYZ" + }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null, zoomArgs.length > 2 ? zoomArgs[2] | 0 : null, zoomArgNumber ? zoomArgNumber / 100 : zoomArg]; + } else if (zoomArg === "Fit" || zoomArg === "FitB") { + dest = [null, { + name: zoomArg + }]; + } else if (zoomArg === "FitH" || zoomArg === "FitBH" || zoomArg === "FitV" || zoomArg === "FitBV") { + dest = [null, { + name: zoomArg + }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null]; + } else if (zoomArg === "FitR") { + if (zoomArgs.length !== 5) { + console.error('PDFLinkService.setHash: Not enough parameters for "FitR".'); + } else { + dest = [null, { + name: zoomArg + }, zoomArgs[1] | 0, zoomArgs[2] | 0, zoomArgs[3] | 0, zoomArgs[4] | 0]; + } + } else { + console.error(`PDFLinkService.setHash: "${zoomArg}" is not a valid zoom value.`); + } + } + if (dest) { + this.pdfViewer.scrollPageIntoView({ + pageNumber: pageNumber || this.page, + destArray: dest, + allowNegativeOffset: true + }); + } else if (pageNumber) { + this.page = pageNumber; + } + if (params.has("pagemode")) { + this.eventBus.dispatch("pagemode", { + source: this, + mode: params.get("pagemode") + }); + } + if (params.has("nameddest")) { + this.goToDestination(params.get("nameddest")); + } + return; + } + dest = unescape(hash); + try { + dest = JSON.parse(dest); + if (!Array.isArray(dest)) { + dest = dest.toString(); + } + } catch {} + if (typeof dest === "string" || PDFLinkService.#isValidExplicitDest(dest)) { + this.goToDestination(dest); + return; + } + console.error(`PDFLinkService.setHash: "${unescape(hash)}" is not a valid destination.`); + } + executeNamedAction(action) { + if (!this.pdfDocument) { + return; + } + switch (action) { + case "GoBack": + this.pdfHistory?.back(); + break; + case "GoForward": + this.pdfHistory?.forward(); + break; + case "NextPage": + this.pdfViewer.nextPage(); + break; + case "PrevPage": + this.pdfViewer.previousPage(); + break; + case "LastPage": + this.page = this.pagesCount; + break; + case "FirstPage": + this.page = 1; + break; + default: + break; + } + this.eventBus.dispatch("namedaction", { + source: this, + action + }); + } + async executeSetOCGState(action) { + if (!this.pdfDocument) { + return; + } + const pdfDocument = this.pdfDocument, + optionalContentConfig = await this.pdfViewer.optionalContentConfigPromise; + if (pdfDocument !== this.pdfDocument) { + return; + } + optionalContentConfig.setOCGState(action); + this.pdfViewer.optionalContentConfigPromise = Promise.resolve(optionalContentConfig); + } + static #isValidExplicitDest(dest) { + if (!Array.isArray(dest) || dest.length < 2) { + return false; + } + const [page, zoom, ...args] = dest; + if (!(typeof page === "object" && Number.isInteger(page?.num) && Number.isInteger(page?.gen)) && !Number.isInteger(page)) { + return false; + } + if (!(typeof zoom === "object" && typeof zoom?.name === "string")) { + return false; + } + const argsLen = args.length; + let allowNull = true; + switch (zoom.name) { + case "XYZ": + if (argsLen < 2 || argsLen > 3) { + return false; + } + break; + case "Fit": + case "FitB": + return argsLen === 0; + case "FitH": + case "FitBH": + case "FitV": + case "FitBV": + if (argsLen > 1) { + return false; + } + break; + case "FitR": + if (argsLen !== 4) { + return false; + } + allowNull = false; + break; + default: + return false; + } + for (const arg of args) { + if (!(typeof arg === "number" || allowNull && arg === null)) { + return false; + } + } + return true; + } +} +class SimpleLinkService extends PDFLinkService { + setDocument(pdfDocument, baseUrl = null) {} +} + +;// ./web/pdfjs.js +const { + AbortException, + AnnotationEditorLayer, + AnnotationEditorParamsType, + AnnotationEditorType, + AnnotationEditorUIManager, + AnnotationLayer, + AnnotationMode, + build, + ColorPicker, + createValidAbsoluteUrl, + DOMSVGFactory, + DrawLayer, + FeatureTest, + fetchData, + getDocument, + getFilenameFromUrl, + getPdfFilenameFromUrl: pdfjs_getPdfFilenameFromUrl, + getXfaPageViewport, + GlobalWorkerOptions, + ImageKind, + InvalidPDFException, + isDataScheme, + isPdfFile, + MissingPDFException, + noContextMenu, + normalizeUnicode, + OPS, + OutputScale, + PasswordResponses, + PDFDataRangeTransport, + PDFDateString, + PDFWorker, + PermissionFlag, + PixelsPerInch, + RenderingCancelledException, + setLayerDimensions, + shadow, + stopEvent, + TextLayer, + UnexpectedResponseException, + Util, + VerbosityLevel, + version, + XfaLayer +} = globalThis.pdfjsLib; + +;// ./web/event_utils.js +const WaitOnType = { + EVENT: "event", + TIMEOUT: "timeout" +}; +async function waitOnEventOrTimeout({ + target, + name, + delay = 0 +}) { + if (typeof target !== "object" || !(name && typeof name === "string") || !(Number.isInteger(delay) && delay >= 0)) { + throw new Error("waitOnEventOrTimeout - invalid parameters."); + } + const { + promise, + resolve + } = Promise.withResolvers(); + const ac = new AbortController(); + function handler(type) { + ac.abort(); + clearTimeout(timeout); + resolve(type); + } + const evtMethod = target instanceof EventBus ? "_on" : "addEventListener"; + target[evtMethod](name, handler.bind(null, WaitOnType.EVENT), { + signal: ac.signal + }); + const timeout = setTimeout(handler.bind(null, WaitOnType.TIMEOUT), delay); + return promise; +} +class EventBus { + #listeners = Object.create(null); + on(eventName, listener, options = null) { + this._on(eventName, listener, { + external: true, + once: options?.once, + signal: options?.signal + }); + } + off(eventName, listener, options = null) { + this._off(eventName, listener); + } + dispatch(eventName, data) { + const eventListeners = this.#listeners[eventName]; + if (!eventListeners || eventListeners.length === 0) { + return; + } + let externalListeners; + for (const { + listener, + external, + once + } of eventListeners.slice(0)) { + if (once) { + this._off(eventName, listener); + } + if (external) { + (externalListeners ||= []).push(listener); + continue; + } + listener(data); + } + if (externalListeners) { + for (const listener of externalListeners) { + listener(data); + } + externalListeners = null; + } + } + _on(eventName, listener, options = null) { + let rmAbort = null; + if (options?.signal instanceof AbortSignal) { + const { + signal + } = options; + if (signal.aborted) { + console.error("Cannot use an `aborted` signal."); + return; + } + const onAbort = () => this._off(eventName, listener); + rmAbort = () => signal.removeEventListener("abort", onAbort); + signal.addEventListener("abort", onAbort); + } + const eventListeners = this.#listeners[eventName] ||= []; + eventListeners.push({ + listener, + external: options?.external === true, + once: options?.once === true, + rmAbort + }); + } + _off(eventName, listener, options = null) { + const eventListeners = this.#listeners[eventName]; + if (!eventListeners) { + return; + } + for (let i = 0, ii = eventListeners.length; i < ii; i++) { + const evt = eventListeners[i]; + if (evt.listener === listener) { + evt.rmAbort?.(); + eventListeners.splice(i, 1); + return; + } + } + } +} +class FirefoxEventBus extends EventBus { + #externalServices; + #globalEventNames; + #isInAutomation; + constructor(globalEventNames, externalServices, isInAutomation) { + super(); + this.#globalEventNames = globalEventNames; + this.#externalServices = externalServices; + this.#isInAutomation = isInAutomation; + } + dispatch(eventName, data) { + throw new Error("Not implemented: FirefoxEventBus.dispatch"); + } +} + +;// ./web/external_services.js +class BaseExternalServices { + updateFindControlState(data) {} + updateFindMatchesCount(data) {} + initPassiveLoading() {} + reportTelemetry(data) {} + async createL10n() { + throw new Error("Not implemented: createL10n"); + } + createScripting() { + throw new Error("Not implemented: createScripting"); + } + updateEditorStates(data) { + throw new Error("Not implemented: updateEditorStates"); + } + dispatchGlobalEvent(_event) {} +} + +;// ./web/preferences.js + +class BasePreferences { + #defaults = Object.freeze({ + altTextLearnMoreUrl: "", + annotationEditorMode: 0, + annotationMode: 2, + cursorToolOnLoad: 0, + defaultZoomDelay: 400, + defaultZoomValue: "", + disablePageLabels: false, + enableAltText: false, + enableAltTextModelDownload: true, + enableGuessAltText: true, + enableHighlightFloatingButton: false, + enableNewAltTextWhenAddingImage: true, + enablePermissions: false, + enablePrintAutoRotate: true, + enableScripting: true, + enableUpdatedAddImage: false, + externalLinkTarget: 0, + highlightEditorColors: "yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F", + historyUpdateUrl: false, + ignoreDestinationZoom: false, + forcePageColors: false, + pageColorsBackground: "Canvas", + pageColorsForeground: "CanvasText", + pdfBugEnabled: false, + sidebarViewOnLoad: -1, + scrollModeOnLoad: -1, + spreadModeOnLoad: -1, + textLayerMode: 1, + viewOnLoad: 0, + disableAutoFetch: false, + disableFontFace: false, + disableRange: false, + disableStream: false, + enableHWA: true, + enableXfa: true, + viewerCssTheme: 0 + }); + #initializedPromise = null; + constructor() { + this.#initializedPromise = this._readFromStorage(this.#defaults).then(({ + browserPrefs, + prefs + }) => { + if (AppOptions._checkDisablePreferences()) { + return; + } + AppOptions.setAll({ + ...browserPrefs, + ...prefs + }, true); + }); + } + async _writeToStorage(prefObj) { + throw new Error("Not implemented: _writeToStorage"); + } + async _readFromStorage(prefObj) { + throw new Error("Not implemented: _readFromStorage"); + } + async reset() { + await this.#initializedPromise; + AppOptions.setAll(this.#defaults, true); + await this._writeToStorage(this.#defaults); + } + async set(name, value) { + await this.#initializedPromise; + AppOptions.setAll({ + [name]: value + }, true); + await this._writeToStorage(AppOptions.getAll(OptionKind.PREFERENCE)); + } + async get(name) { + await this.#initializedPromise; + return AppOptions.get(name); + } + get initializedPromise() { + return this.#initializedPromise; + } +} + +;// ./node_modules/@fluent/bundle/esm/types.js +class FluentType { + constructor(value) { + this.value = value; + } + valueOf() { + return this.value; + } +} +class FluentNone extends FluentType { + constructor(value = "???") { + super(value); + } + toString(scope) { + return `{${this.value}}`; + } +} +class FluentNumber extends FluentType { + constructor(value, opts = {}) { + super(value); + this.opts = opts; + } + toString(scope) { + try { + const nf = scope.memoizeIntlObject(Intl.NumberFormat, this.opts); + return nf.format(this.value); + } catch (err) { + scope.reportError(err); + return this.value.toString(10); + } + } +} +class FluentDateTime extends FluentType { + constructor(value, opts = {}) { + super(value); + this.opts = opts; + } + toString(scope) { + try { + const dtf = scope.memoizeIntlObject(Intl.DateTimeFormat, this.opts); + return dtf.format(this.value); + } catch (err) { + scope.reportError(err); + return new Date(this.value).toISOString(); + } + } +} +;// ./node_modules/@fluent/bundle/esm/resolver.js + +const MAX_PLACEABLES = 100; +const FSI = "\u2068"; +const PDI = "\u2069"; +function match(scope, selector, key) { + if (key === selector) { + return true; + } + if (key instanceof FluentNumber && selector instanceof FluentNumber && key.value === selector.value) { + return true; + } + if (selector instanceof FluentNumber && typeof key === "string") { + let category = scope.memoizeIntlObject(Intl.PluralRules, selector.opts).select(selector.value); + if (key === category) { + return true; + } + } + return false; +} +function getDefault(scope, variants, star) { + if (variants[star]) { + return resolvePattern(scope, variants[star].value); + } + scope.reportError(new RangeError("No default")); + return new FluentNone(); +} +function getArguments(scope, args) { + const positional = []; + const named = Object.create(null); + for (const arg of args) { + if (arg.type === "narg") { + named[arg.name] = resolveExpression(scope, arg.value); + } else { + positional.push(resolveExpression(scope, arg)); + } + } + return { + positional, + named + }; +} +function resolveExpression(scope, expr) { + switch (expr.type) { + case "str": + return expr.value; + case "num": + return new FluentNumber(expr.value, { + minimumFractionDigits: expr.precision + }); + case "var": + return resolveVariableReference(scope, expr); + case "mesg": + return resolveMessageReference(scope, expr); + case "term": + return resolveTermReference(scope, expr); + case "func": + return resolveFunctionReference(scope, expr); + case "select": + return resolveSelectExpression(scope, expr); + default: + return new FluentNone(); + } +} +function resolveVariableReference(scope, { + name +}) { + let arg; + if (scope.params) { + if (Object.prototype.hasOwnProperty.call(scope.params, name)) { + arg = scope.params[name]; + } else { + return new FluentNone(`$${name}`); + } + } else if (scope.args && Object.prototype.hasOwnProperty.call(scope.args, name)) { + arg = scope.args[name]; + } else { + scope.reportError(new ReferenceError(`Unknown variable: $${name}`)); + return new FluentNone(`$${name}`); + } + if (arg instanceof FluentType) { + return arg; + } + switch (typeof arg) { + case "string": + return arg; + case "number": + return new FluentNumber(arg); + case "object": + if (arg instanceof Date) { + return new FluentDateTime(arg.getTime()); + } + default: + scope.reportError(new TypeError(`Variable type not supported: $${name}, ${typeof arg}`)); + return new FluentNone(`$${name}`); + } +} +function resolveMessageReference(scope, { + name, + attr +}) { + const message = scope.bundle._messages.get(name); + if (!message) { + scope.reportError(new ReferenceError(`Unknown message: ${name}`)); + return new FluentNone(name); + } + if (attr) { + const attribute = message.attributes[attr]; + if (attribute) { + return resolvePattern(scope, attribute); + } + scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`)); + return new FluentNone(`${name}.${attr}`); + } + if (message.value) { + return resolvePattern(scope, message.value); + } + scope.reportError(new ReferenceError(`No value: ${name}`)); + return new FluentNone(name); +} +function resolveTermReference(scope, { + name, + attr, + args +}) { + const id = `-${name}`; + const term = scope.bundle._terms.get(id); + if (!term) { + scope.reportError(new ReferenceError(`Unknown term: ${id}`)); + return new FluentNone(id); + } + if (attr) { + const attribute = term.attributes[attr]; + if (attribute) { + scope.params = getArguments(scope, args).named; + const resolved = resolvePattern(scope, attribute); + scope.params = null; + return resolved; + } + scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`)); + return new FluentNone(`${id}.${attr}`); + } + scope.params = getArguments(scope, args).named; + const resolved = resolvePattern(scope, term.value); + scope.params = null; + return resolved; +} +function resolveFunctionReference(scope, { + name, + args +}) { + let func = scope.bundle._functions[name]; + if (!func) { + scope.reportError(new ReferenceError(`Unknown function: ${name}()`)); + return new FluentNone(`${name}()`); + } + if (typeof func !== "function") { + scope.reportError(new TypeError(`Function ${name}() is not callable`)); + return new FluentNone(`${name}()`); + } + try { + let resolved = getArguments(scope, args); + return func(resolved.positional, resolved.named); + } catch (err) { + scope.reportError(err); + return new FluentNone(`${name}()`); + } +} +function resolveSelectExpression(scope, { + selector, + variants, + star +}) { + let sel = resolveExpression(scope, selector); + if (sel instanceof FluentNone) { + return getDefault(scope, variants, star); + } + for (const variant of variants) { + const key = resolveExpression(scope, variant.key); + if (match(scope, sel, key)) { + return resolvePattern(scope, variant.value); + } + } + return getDefault(scope, variants, star); +} +function resolveComplexPattern(scope, ptn) { + if (scope.dirty.has(ptn)) { + scope.reportError(new RangeError("Cyclic reference")); + return new FluentNone(); + } + scope.dirty.add(ptn); + const result = []; + const useIsolating = scope.bundle._useIsolating && ptn.length > 1; + for (const elem of ptn) { + if (typeof elem === "string") { + result.push(scope.bundle._transform(elem)); + continue; + } + scope.placeables++; + if (scope.placeables > MAX_PLACEABLES) { + scope.dirty.delete(ptn); + throw new RangeError(`Too many placeables expanded: ${scope.placeables}, ` + `max allowed is ${MAX_PLACEABLES}`); + } + if (useIsolating) { + result.push(FSI); + } + result.push(resolveExpression(scope, elem).toString(scope)); + if (useIsolating) { + result.push(PDI); + } + } + scope.dirty.delete(ptn); + return result.join(""); +} +function resolvePattern(scope, value) { + if (typeof value === "string") { + return scope.bundle._transform(value); + } + return resolveComplexPattern(scope, value); +} +;// ./node_modules/@fluent/bundle/esm/scope.js +class Scope { + constructor(bundle, errors, args) { + this.dirty = new WeakSet(); + this.params = null; + this.placeables = 0; + this.bundle = bundle; + this.errors = errors; + this.args = args; + } + reportError(error) { + if (!this.errors || !(error instanceof Error)) { + throw error; + } + this.errors.push(error); + } + memoizeIntlObject(ctor, opts) { + let cache = this.bundle._intls.get(ctor); + if (!cache) { + cache = {}; + this.bundle._intls.set(ctor, cache); + } + let id = JSON.stringify(opts); + if (!cache[id]) { + cache[id] = new ctor(this.bundle.locales, opts); + } + return cache[id]; + } +} +;// ./node_modules/@fluent/bundle/esm/builtins.js + +function values(opts, allowed) { + const unwrapped = Object.create(null); + for (const [name, opt] of Object.entries(opts)) { + if (allowed.includes(name)) { + unwrapped[name] = opt.valueOf(); + } + } + return unwrapped; +} +const NUMBER_ALLOWED = ["unitDisplay", "currencyDisplay", "useGrouping", "minimumIntegerDigits", "minimumFractionDigits", "maximumFractionDigits", "minimumSignificantDigits", "maximumSignificantDigits"]; +function NUMBER(args, opts) { + let arg = args[0]; + if (arg instanceof FluentNone) { + return new FluentNone(`NUMBER(${arg.valueOf()})`); + } + if (arg instanceof FluentNumber) { + return new FluentNumber(arg.valueOf(), { + ...arg.opts, + ...values(opts, NUMBER_ALLOWED) + }); + } + if (arg instanceof FluentDateTime) { + return new FluentNumber(arg.valueOf(), { + ...values(opts, NUMBER_ALLOWED) + }); + } + throw new TypeError("Invalid argument to NUMBER"); +} +const DATETIME_ALLOWED = ["dateStyle", "timeStyle", "fractionalSecondDigits", "dayPeriod", "hour12", "weekday", "era", "year", "month", "day", "hour", "minute", "second", "timeZoneName"]; +function DATETIME(args, opts) { + let arg = args[0]; + if (arg instanceof FluentNone) { + return new FluentNone(`DATETIME(${arg.valueOf()})`); + } + if (arg instanceof FluentDateTime) { + return new FluentDateTime(arg.valueOf(), { + ...arg.opts, + ...values(opts, DATETIME_ALLOWED) + }); + } + if (arg instanceof FluentNumber) { + return new FluentDateTime(arg.valueOf(), { + ...values(opts, DATETIME_ALLOWED) + }); + } + throw new TypeError("Invalid argument to DATETIME"); +} +;// ./node_modules/@fluent/bundle/esm/memoizer.js +const cache = new Map(); +function getMemoizerForLocale(locales) { + const stringLocale = Array.isArray(locales) ? locales.join(" ") : locales; + let memoizer = cache.get(stringLocale); + if (memoizer === undefined) { + memoizer = new Map(); + cache.set(stringLocale, memoizer); + } + return memoizer; +} +;// ./node_modules/@fluent/bundle/esm/bundle.js + + + + + +class FluentBundle { + constructor(locales, { + functions, + useIsolating = true, + transform = v => v + } = {}) { + this._terms = new Map(); + this._messages = new Map(); + this.locales = Array.isArray(locales) ? locales : [locales]; + this._functions = { + NUMBER: NUMBER, + DATETIME: DATETIME, + ...functions + }; + this._useIsolating = useIsolating; + this._transform = transform; + this._intls = getMemoizerForLocale(locales); + } + hasMessage(id) { + return this._messages.has(id); + } + getMessage(id) { + return this._messages.get(id); + } + addResource(res, { + allowOverrides = false + } = {}) { + const errors = []; + for (let i = 0; i < res.body.length; i++) { + let entry = res.body[i]; + if (entry.id.startsWith("-")) { + if (allowOverrides === false && this._terms.has(entry.id)) { + errors.push(new Error(`Attempt to override an existing term: "${entry.id}"`)); + continue; + } + this._terms.set(entry.id, entry); + } else { + if (allowOverrides === false && this._messages.has(entry.id)) { + errors.push(new Error(`Attempt to override an existing message: "${entry.id}"`)); + continue; + } + this._messages.set(entry.id, entry); + } + } + return errors; + } + formatPattern(pattern, args = null, errors = null) { + if (typeof pattern === "string") { + return this._transform(pattern); + } + let scope = new Scope(this, errors, args); + try { + let value = resolveComplexPattern(scope, pattern); + return value.toString(scope); + } catch (err) { + if (scope.errors && err instanceof Error) { + scope.errors.push(err); + return new FluentNone().toString(scope); + } + throw err; + } + } +} +;// ./node_modules/@fluent/bundle/esm/resource.js +const RE_MESSAGE_START = /^(-?[a-zA-Z][\w-]*) *= */gm; +const RE_ATTRIBUTE_START = /\.([a-zA-Z][\w-]*) *= */y; +const RE_VARIANT_START = /\*?\[/y; +const RE_NUMBER_LITERAL = /(-?[0-9]+(?:\.([0-9]+))?)/y; +const RE_IDENTIFIER = /([a-zA-Z][\w-]*)/y; +const RE_REFERENCE = /([$-])?([a-zA-Z][\w-]*)(?:\.([a-zA-Z][\w-]*))?/y; +const RE_FUNCTION_NAME = /^[A-Z][A-Z0-9_-]*$/; +const RE_TEXT_RUN = /([^{}\n\r]+)/y; +const RE_STRING_RUN = /([^\\"\n\r]*)/y; +const RE_STRING_ESCAPE = /\\([\\"])/y; +const RE_UNICODE_ESCAPE = /\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{6})/y; +const RE_LEADING_NEWLINES = /^\n+/; +const RE_TRAILING_SPACES = / +$/; +const RE_BLANK_LINES = / *\r?\n/g; +const RE_INDENT = /( *)$/; +const TOKEN_BRACE_OPEN = /{\s*/y; +const TOKEN_BRACE_CLOSE = /\s*}/y; +const TOKEN_BRACKET_OPEN = /\[\s*/y; +const TOKEN_BRACKET_CLOSE = /\s*] */y; +const TOKEN_PAREN_OPEN = /\s*\(\s*/y; +const TOKEN_ARROW = /\s*->\s*/y; +const TOKEN_COLON = /\s*:\s*/y; +const TOKEN_COMMA = /\s*,?\s*/y; +const TOKEN_BLANK = /\s+/y; +class FluentResource { + constructor(source) { + this.body = []; + RE_MESSAGE_START.lastIndex = 0; + let cursor = 0; + while (true) { + let next = RE_MESSAGE_START.exec(source); + if (next === null) { + break; + } + cursor = RE_MESSAGE_START.lastIndex; + try { + this.body.push(parseMessage(next[1])); + } catch (err) { + if (err instanceof SyntaxError) { + continue; + } + throw err; + } + } + function test(re) { + re.lastIndex = cursor; + return re.test(source); + } + function consumeChar(char, errorClass) { + if (source[cursor] === char) { + cursor++; + return true; + } + if (errorClass) { + throw new errorClass(`Expected ${char}`); + } + return false; + } + function consumeToken(re, errorClass) { + if (test(re)) { + cursor = re.lastIndex; + return true; + } + if (errorClass) { + throw new errorClass(`Expected ${re.toString()}`); + } + return false; + } + function match(re) { + re.lastIndex = cursor; + let result = re.exec(source); + if (result === null) { + throw new SyntaxError(`Expected ${re.toString()}`); + } + cursor = re.lastIndex; + return result; + } + function match1(re) { + return match(re)[1]; + } + function parseMessage(id) { + let value = parsePattern(); + let attributes = parseAttributes(); + if (value === null && Object.keys(attributes).length === 0) { + throw new SyntaxError("Expected message value or attributes"); + } + return { + id, + value, + attributes + }; + } + function parseAttributes() { + let attrs = Object.create(null); + while (test(RE_ATTRIBUTE_START)) { + let name = match1(RE_ATTRIBUTE_START); + let value = parsePattern(); + if (value === null) { + throw new SyntaxError("Expected attribute value"); + } + attrs[name] = value; + } + return attrs; + } + function parsePattern() { + let first; + if (test(RE_TEXT_RUN)) { + first = match1(RE_TEXT_RUN); + } + if (source[cursor] === "{" || source[cursor] === "}") { + return parsePatternElements(first ? [first] : [], Infinity); + } + let indent = parseIndent(); + if (indent) { + if (first) { + return parsePatternElements([first, indent], indent.length); + } + indent.value = trim(indent.value, RE_LEADING_NEWLINES); + return parsePatternElements([indent], indent.length); + } + if (first) { + return trim(first, RE_TRAILING_SPACES); + } + return null; + } + function parsePatternElements(elements = [], commonIndent) { + while (true) { + if (test(RE_TEXT_RUN)) { + elements.push(match1(RE_TEXT_RUN)); + continue; + } + if (source[cursor] === "{") { + elements.push(parsePlaceable()); + continue; + } + if (source[cursor] === "}") { + throw new SyntaxError("Unbalanced closing brace"); + } + let indent = parseIndent(); + if (indent) { + elements.push(indent); + commonIndent = Math.min(commonIndent, indent.length); + continue; + } + break; + } + let lastIndex = elements.length - 1; + let lastElement = elements[lastIndex]; + if (typeof lastElement === "string") { + elements[lastIndex] = trim(lastElement, RE_TRAILING_SPACES); + } + let baked = []; + for (let element of elements) { + if (element instanceof Indent) { + element = element.value.slice(0, element.value.length - commonIndent); + } + if (element) { + baked.push(element); + } + } + return baked; + } + function parsePlaceable() { + consumeToken(TOKEN_BRACE_OPEN, SyntaxError); + let selector = parseInlineExpression(); + if (consumeToken(TOKEN_BRACE_CLOSE)) { + return selector; + } + if (consumeToken(TOKEN_ARROW)) { + let variants = parseVariants(); + consumeToken(TOKEN_BRACE_CLOSE, SyntaxError); + return { + type: "select", + selector, + ...variants + }; + } + throw new SyntaxError("Unclosed placeable"); + } + function parseInlineExpression() { + if (source[cursor] === "{") { + return parsePlaceable(); + } + if (test(RE_REFERENCE)) { + let [, sigil, name, attr = null] = match(RE_REFERENCE); + if (sigil === "$") { + return { + type: "var", + name + }; + } + if (consumeToken(TOKEN_PAREN_OPEN)) { + let args = parseArguments(); + if (sigil === "-") { + return { + type: "term", + name, + attr, + args + }; + } + if (RE_FUNCTION_NAME.test(name)) { + return { + type: "func", + name, + args + }; + } + throw new SyntaxError("Function names must be all upper-case"); + } + if (sigil === "-") { + return { + type: "term", + name, + attr, + args: [] + }; + } + return { + type: "mesg", + name, + attr + }; + } + return parseLiteral(); + } + function parseArguments() { + let args = []; + while (true) { + switch (source[cursor]) { + case ")": + cursor++; + return args; + case undefined: + throw new SyntaxError("Unclosed argument list"); + } + args.push(parseArgument()); + consumeToken(TOKEN_COMMA); + } + } + function parseArgument() { + let expr = parseInlineExpression(); + if (expr.type !== "mesg") { + return expr; + } + if (consumeToken(TOKEN_COLON)) { + return { + type: "narg", + name: expr.name, + value: parseLiteral() + }; + } + return expr; + } + function parseVariants() { + let variants = []; + let count = 0; + let star; + while (test(RE_VARIANT_START)) { + if (consumeChar("*")) { + star = count; + } + let key = parseVariantKey(); + let value = parsePattern(); + if (value === null) { + throw new SyntaxError("Expected variant value"); + } + variants[count++] = { + key, + value + }; + } + if (count === 0) { + return null; + } + if (star === undefined) { + throw new SyntaxError("Expected default variant"); + } + return { + variants, + star + }; + } + function parseVariantKey() { + consumeToken(TOKEN_BRACKET_OPEN, SyntaxError); + let key; + if (test(RE_NUMBER_LITERAL)) { + key = parseNumberLiteral(); + } else { + key = { + type: "str", + value: match1(RE_IDENTIFIER) + }; + } + consumeToken(TOKEN_BRACKET_CLOSE, SyntaxError); + return key; + } + function parseLiteral() { + if (test(RE_NUMBER_LITERAL)) { + return parseNumberLiteral(); + } + if (source[cursor] === '"') { + return parseStringLiteral(); + } + throw new SyntaxError("Invalid expression"); + } + function parseNumberLiteral() { + let [, value, fraction = ""] = match(RE_NUMBER_LITERAL); + let precision = fraction.length; + return { + type: "num", + value: parseFloat(value), + precision + }; + } + function parseStringLiteral() { + consumeChar('"', SyntaxError); + let value = ""; + while (true) { + value += match1(RE_STRING_RUN); + if (source[cursor] === "\\") { + value += parseEscapeSequence(); + continue; + } + if (consumeChar('"')) { + return { + type: "str", + value + }; + } + throw new SyntaxError("Unclosed string literal"); + } + } + function parseEscapeSequence() { + if (test(RE_STRING_ESCAPE)) { + return match1(RE_STRING_ESCAPE); + } + if (test(RE_UNICODE_ESCAPE)) { + let [, codepoint4, codepoint6] = match(RE_UNICODE_ESCAPE); + let codepoint = parseInt(codepoint4 || codepoint6, 16); + return codepoint <= 0xd7ff || 0xe000 <= codepoint ? String.fromCodePoint(codepoint) : "�"; + } + throw new SyntaxError("Unknown escape sequence"); + } + function parseIndent() { + let start = cursor; + consumeToken(TOKEN_BLANK); + switch (source[cursor]) { + case ".": + case "[": + case "*": + case "}": + case undefined: + return false; + case "{": + return makeIndent(source.slice(start, cursor)); + } + if (source[cursor - 1] === " ") { + return makeIndent(source.slice(start, cursor)); + } + return false; + } + function trim(text, re) { + return text.replace(re, ""); + } + function makeIndent(blank) { + let value = blank.replace(RE_BLANK_LINES, "\n"); + let length = RE_INDENT.exec(blank)[1].length; + return new Indent(value, length); + } + } +} +class Indent { + constructor(value, length) { + this.value = value; + this.length = length; + } +} +;// ./node_modules/@fluent/bundle/esm/index.js + + + +;// ./node_modules/@fluent/dom/esm/overlay.js +const reOverlay = /<|&#?\w+;/; +const TEXT_LEVEL_ELEMENTS = { + "http://www.w3.org/1999/xhtml": ["em", "strong", "small", "s", "cite", "q", "dfn", "abbr", "data", "time", "code", "var", "samp", "kbd", "sub", "sup", "i", "b", "u", "mark", "bdi", "bdo", "span", "br", "wbr"] +}; +const LOCALIZABLE_ATTRIBUTES = { + "http://www.w3.org/1999/xhtml": { + global: ["title", "aria-label", "aria-valuetext"], + a: ["download"], + area: ["download", "alt"], + input: ["alt", "placeholder"], + menuitem: ["label"], + menu: ["label"], + optgroup: ["label"], + option: ["label"], + track: ["label"], + img: ["alt"], + textarea: ["placeholder"], + th: ["abbr"] + }, + "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul": { + global: ["accesskey", "aria-label", "aria-valuetext", "label", "title", "tooltiptext"], + description: ["value"], + key: ["key", "keycode"], + label: ["value"], + textbox: ["placeholder", "value"] + } +}; +function translateElement(element, translation) { + const { + value + } = translation; + if (typeof value === "string") { + if (element.localName === "title" && element.namespaceURI === "http://www.w3.org/1999/xhtml") { + element.textContent = value; + } else if (!reOverlay.test(value)) { + element.textContent = value; + } else { + const templateElement = element.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml", "template"); + templateElement.innerHTML = value; + overlayChildNodes(templateElement.content, element); + } + } + overlayAttributes(translation, element); +} +function overlayChildNodes(fromFragment, toElement) { + for (const childNode of fromFragment.childNodes) { + if (childNode.nodeType === childNode.TEXT_NODE) { + continue; + } + if (childNode.hasAttribute("data-l10n-name")) { + const sanitized = getNodeForNamedElement(toElement, childNode); + fromFragment.replaceChild(sanitized, childNode); + continue; + } + if (isElementAllowed(childNode)) { + const sanitized = createSanitizedElement(childNode); + fromFragment.replaceChild(sanitized, childNode); + continue; + } + console.warn(`An element of forbidden type "${childNode.localName}" was found in ` + "the translation. Only safe text-level elements and elements with " + "data-l10n-name are allowed."); + fromFragment.replaceChild(createTextNodeFromTextContent(childNode), childNode); + } + toElement.textContent = ""; + toElement.appendChild(fromFragment); +} +function hasAttribute(attributes, name) { + if (!attributes) { + return false; + } + for (let attr of attributes) { + if (attr.name === name) { + return true; + } + } + return false; +} +function overlayAttributes(fromElement, toElement) { + const explicitlyAllowed = toElement.hasAttribute("data-l10n-attrs") ? toElement.getAttribute("data-l10n-attrs").split(",").map(i => i.trim()) : null; + for (const attr of Array.from(toElement.attributes)) { + if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && !hasAttribute(fromElement.attributes, attr.name)) { + toElement.removeAttribute(attr.name); + } + } + if (!fromElement.attributes) { + return; + } + for (const attr of Array.from(fromElement.attributes)) { + if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && toElement.getAttribute(attr.name) !== attr.value) { + toElement.setAttribute(attr.name, attr.value); + } + } +} +function getNodeForNamedElement(sourceElement, translatedChild) { + const childName = translatedChild.getAttribute("data-l10n-name"); + const sourceChild = sourceElement.querySelector(`[data-l10n-name="${childName}"]`); + if (!sourceChild) { + console.warn(`An element named "${childName}" wasn't found in the source.`); + return createTextNodeFromTextContent(translatedChild); + } + if (sourceChild.localName !== translatedChild.localName) { + console.warn(`An element named "${childName}" was found in the translation ` + `but its type ${translatedChild.localName} didn't match the ` + `element found in the source (${sourceChild.localName}).`); + return createTextNodeFromTextContent(translatedChild); + } + sourceElement.removeChild(sourceChild); + const clone = sourceChild.cloneNode(false); + return shallowPopulateUsing(translatedChild, clone); +} +function createSanitizedElement(element) { + const clone = element.ownerDocument.createElement(element.localName); + return shallowPopulateUsing(element, clone); +} +function createTextNodeFromTextContent(element) { + return element.ownerDocument.createTextNode(element.textContent); +} +function isElementAllowed(element) { + const allowed = TEXT_LEVEL_ELEMENTS[element.namespaceURI]; + return allowed && allowed.includes(element.localName); +} +function isAttrNameLocalizable(name, element, explicitlyAllowed = null) { + if (explicitlyAllowed && explicitlyAllowed.includes(name)) { + return true; + } + const allowed = LOCALIZABLE_ATTRIBUTES[element.namespaceURI]; + if (!allowed) { + return false; + } + const attrName = name.toLowerCase(); + const elemName = element.localName; + if (allowed.global.includes(attrName)) { + return true; + } + if (!allowed[elemName]) { + return false; + } + if (allowed[elemName].includes(attrName)) { + return true; + } + if (element.namespaceURI === "http://www.w3.org/1999/xhtml" && elemName === "input" && attrName === "value") { + const type = element.type.toLowerCase(); + if (type === "submit" || type === "button" || type === "reset") { + return true; + } + } + return false; +} +function shallowPopulateUsing(fromElement, toElement) { + toElement.textContent = fromElement.textContent; + overlayAttributes(fromElement, toElement); + return toElement; +} +;// ./node_modules/cached-iterable/src/cached_iterable.mjs +class CachedIterable extends Array { + static from(iterable) { + if (iterable instanceof this) { + return iterable; + } + return new this(iterable); + } +} +;// ./node_modules/cached-iterable/src/cached_sync_iterable.mjs + +class CachedSyncIterable extends CachedIterable { + constructor(iterable) { + super(); + if (Symbol.iterator in Object(iterable)) { + this.iterator = iterable[Symbol.iterator](); + } else { + throw new TypeError("Argument must implement the iteration protocol."); + } + } + [Symbol.iterator]() { + const cached = this; + let cur = 0; + return { + next() { + if (cached.length <= cur) { + cached.push(cached.iterator.next()); + } + return cached[cur++]; + } + }; + } + touchNext(count = 1) { + let idx = 0; + while (idx++ < count) { + const last = this[this.length - 1]; + if (last && last.done) { + break; + } + this.push(this.iterator.next()); + } + return this[this.length - 1]; + } +} +;// ./node_modules/cached-iterable/src/cached_async_iterable.mjs + +class CachedAsyncIterable extends CachedIterable { + constructor(iterable) { + super(); + if (Symbol.asyncIterator in Object(iterable)) { + this.iterator = iterable[Symbol.asyncIterator](); + } else if (Symbol.iterator in Object(iterable)) { + this.iterator = iterable[Symbol.iterator](); + } else { + throw new TypeError("Argument must implement the iteration protocol."); + } + } + [Symbol.asyncIterator]() { + const cached = this; + let cur = 0; + return { + async next() { + if (cached.length <= cur) { + cached.push(cached.iterator.next()); + } + return cached[cur++]; + } + }; + } + async touchNext(count = 1) { + let idx = 0; + while (idx++ < count) { + const last = this[this.length - 1]; + if (last && (await last).done) { + break; + } + this.push(this.iterator.next()); + } + return this[this.length - 1]; + } +} +;// ./node_modules/cached-iterable/src/index.mjs + + +;// ./node_modules/@fluent/dom/esm/localization.js + +class Localization { + constructor(resourceIds = [], generateBundles) { + this.resourceIds = resourceIds; + this.generateBundles = generateBundles; + this.onChange(true); + } + addResourceIds(resourceIds, eager = false) { + this.resourceIds.push(...resourceIds); + this.onChange(eager); + return this.resourceIds.length; + } + removeResourceIds(resourceIds) { + this.resourceIds = this.resourceIds.filter(r => !resourceIds.includes(r)); + this.onChange(); + return this.resourceIds.length; + } + async formatWithFallback(keys, method) { + const translations = []; + let hasAtLeastOneBundle = false; + for await (const bundle of this.bundles) { + hasAtLeastOneBundle = true; + const missingIds = keysFromBundle(method, bundle, keys, translations); + if (missingIds.size === 0) { + break; + } + if (typeof console !== "undefined") { + const locale = bundle.locales[0]; + const ids = Array.from(missingIds).join(", "); + console.warn(`[fluent] Missing translations in ${locale}: ${ids}`); + } + } + if (!hasAtLeastOneBundle && typeof console !== "undefined") { + console.warn(`[fluent] Request for keys failed because no resource bundles got generated. + keys: ${JSON.stringify(keys)}. + resourceIds: ${JSON.stringify(this.resourceIds)}.`); + } + return translations; + } + formatMessages(keys) { + return this.formatWithFallback(keys, messageFromBundle); + } + formatValues(keys) { + return this.formatWithFallback(keys, valueFromBundle); + } + async formatValue(id, args) { + const [val] = await this.formatValues([{ + id, + args + }]); + return val; + } + handleEvent() { + this.onChange(); + } + onChange(eager = false) { + this.bundles = CachedAsyncIterable.from(this.generateBundles(this.resourceIds)); + if (eager) { + this.bundles.touchNext(2); + } + } +} +function valueFromBundle(bundle, errors, message, args) { + if (message.value) { + return bundle.formatPattern(message.value, args, errors); + } + return null; +} +function messageFromBundle(bundle, errors, message, args) { + const formatted = { + value: null, + attributes: null + }; + if (message.value) { + formatted.value = bundle.formatPattern(message.value, args, errors); + } + let attrNames = Object.keys(message.attributes); + if (attrNames.length > 0) { + formatted.attributes = new Array(attrNames.length); + for (let [i, name] of attrNames.entries()) { + let value = bundle.formatPattern(message.attributes[name], args, errors); + formatted.attributes[i] = { + name, + value + }; + } + } + return formatted; +} +function keysFromBundle(method, bundle, keys, translations) { + const messageErrors = []; + const missingIds = new Set(); + keys.forEach(({ + id, + args + }, i) => { + if (translations[i] !== undefined) { + return; + } + let message = bundle.getMessage(id); + if (message) { + messageErrors.length = 0; + translations[i] = method(bundle, messageErrors, message, args); + if (messageErrors.length > 0 && typeof console !== "undefined") { + const locale = bundle.locales[0]; + const errors = messageErrors.join(", "); + console.warn(`[fluent][resolver] errors in ${locale}/${id}: ${errors}.`); + } + } else { + missingIds.add(id); + } + }); + return missingIds; +} +;// ./node_modules/@fluent/dom/esm/dom_localization.js + + +const L10NID_ATTR_NAME = "data-l10n-id"; +const L10NARGS_ATTR_NAME = "data-l10n-args"; +const L10N_ELEMENT_QUERY = `[${L10NID_ATTR_NAME}]`; +class DOMLocalization extends Localization { + constructor(resourceIds, generateBundles) { + super(resourceIds, generateBundles); + this.roots = new Set(); + this.pendingrAF = null; + this.pendingElements = new Set(); + this.windowElement = null; + this.mutationObserver = null; + this.observerConfig = { + attributes: true, + characterData: false, + childList: true, + subtree: true, + attributeFilter: [L10NID_ATTR_NAME, L10NARGS_ATTR_NAME] + }; + } + onChange(eager = false) { + super.onChange(eager); + if (this.roots) { + this.translateRoots(); + } + } + setAttributes(element, id, args) { + element.setAttribute(L10NID_ATTR_NAME, id); + if (args) { + element.setAttribute(L10NARGS_ATTR_NAME, JSON.stringify(args)); + } else { + element.removeAttribute(L10NARGS_ATTR_NAME); + } + return element; + } + getAttributes(element) { + return { + id: element.getAttribute(L10NID_ATTR_NAME), + args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null) + }; + } + connectRoot(newRoot) { + for (const root of this.roots) { + if (root === newRoot || root.contains(newRoot) || newRoot.contains(root)) { + throw new Error("Cannot add a root that overlaps with existing root."); + } + } + if (this.windowElement) { + if (this.windowElement !== newRoot.ownerDocument.defaultView) { + throw new Error(`Cannot connect a root: + DOMLocalization already has a root from a different window.`); + } + } else { + this.windowElement = newRoot.ownerDocument.defaultView; + this.mutationObserver = new this.windowElement.MutationObserver(mutations => this.translateMutations(mutations)); + } + this.roots.add(newRoot); + this.mutationObserver.observe(newRoot, this.observerConfig); + } + disconnectRoot(root) { + this.roots.delete(root); + this.pauseObserving(); + if (this.roots.size === 0) { + this.mutationObserver = null; + if (this.windowElement && this.pendingrAF) { + this.windowElement.cancelAnimationFrame(this.pendingrAF); + } + this.windowElement = null; + this.pendingrAF = null; + this.pendingElements.clear(); + return true; + } + this.resumeObserving(); + return false; + } + translateRoots() { + const roots = Array.from(this.roots); + return Promise.all(roots.map(root => this.translateFragment(root))); + } + pauseObserving() { + if (!this.mutationObserver) { + return; + } + this.translateMutations(this.mutationObserver.takeRecords()); + this.mutationObserver.disconnect(); + } + resumeObserving() { + if (!this.mutationObserver) { + return; + } + for (const root of this.roots) { + this.mutationObserver.observe(root, this.observerConfig); + } + } + translateMutations(mutations) { + for (const mutation of mutations) { + switch (mutation.type) { + case "attributes": + if (mutation.target.hasAttribute("data-l10n-id")) { + this.pendingElements.add(mutation.target); + } + break; + case "childList": + for (const addedNode of mutation.addedNodes) { + if (addedNode.nodeType === addedNode.ELEMENT_NODE) { + if (addedNode.childElementCount) { + for (const element of this.getTranslatables(addedNode)) { + this.pendingElements.add(element); + } + } else if (addedNode.hasAttribute(L10NID_ATTR_NAME)) { + this.pendingElements.add(addedNode); + } + } + } + break; + } + } + if (this.pendingElements.size > 0) { + if (this.pendingrAF === null) { + this.pendingrAF = this.windowElement.requestAnimationFrame(() => { + this.translateElements(Array.from(this.pendingElements)); + this.pendingElements.clear(); + this.pendingrAF = null; + }); + } + } + } + translateFragment(frag) { + return this.translateElements(this.getTranslatables(frag)); + } + async translateElements(elements) { + if (!elements.length) { + return undefined; + } + const keys = elements.map(this.getKeysForElement); + const translations = await this.formatMessages(keys); + return this.applyTranslations(elements, translations); + } + applyTranslations(elements, translations) { + this.pauseObserving(); + for (let i = 0; i < elements.length; i++) { + if (translations[i] !== undefined) { + translateElement(elements[i], translations[i]); + } + } + this.resumeObserving(); + } + getTranslatables(element) { + const nodes = Array.from(element.querySelectorAll(L10N_ELEMENT_QUERY)); + if (typeof element.hasAttribute === "function" && element.hasAttribute(L10NID_ATTR_NAME)) { + nodes.push(element); + } + return nodes; + } + getKeysForElement(element) { + return { + id: element.getAttribute(L10NID_ATTR_NAME), + args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null) + }; + } +} +;// ./node_modules/@fluent/dom/esm/index.js + + +;// ./web/l10n.js +class L10n { + #dir; + #elements; + #lang; + #l10n; + constructor({ + lang, + isRTL + }, l10n = null) { + this.#lang = L10n.#fixupLangCode(lang); + this.#l10n = l10n; + this.#dir = isRTL ?? L10n.#isRTL(this.#lang) ? "rtl" : "ltr"; + } + _setL10n(l10n) { + this.#l10n = l10n; + } + getLanguage() { + return this.#lang; + } + getDirection() { + return this.#dir; + } + async get(ids, args = null, fallback) { + if (Array.isArray(ids)) { + ids = ids.map(id => ({ + id + })); + const messages = await this.#l10n.formatMessages(ids); + return messages.map(message => message.value); + } + const messages = await this.#l10n.formatMessages([{ + id: ids, + args + }]); + return messages[0]?.value || fallback; + } + async translate(element) { + (this.#elements ||= new Set()).add(element); + try { + this.#l10n.connectRoot(element); + await this.#l10n.translateRoots(); + } catch {} + } + async translateOnce(element) { + try { + await this.#l10n.translateElements([element]); + } catch (ex) { + console.error(`translateOnce: "${ex}".`); + } + } + async destroy() { + if (this.#elements) { + for (const element of this.#elements) { + this.#l10n.disconnectRoot(element); + } + this.#elements.clear(); + this.#elements = null; + } + this.#l10n.pauseObserving(); + } + pause() { + this.#l10n.pauseObserving(); + } + resume() { + this.#l10n.resumeObserving(); + } + static #fixupLangCode(langCode) { + langCode = langCode?.toLowerCase() || "en-us"; + const PARTIAL_LANG_CODES = { + en: "en-us", + es: "es-es", + fy: "fy-nl", + ga: "ga-ie", + gu: "gu-in", + hi: "hi-in", + hy: "hy-am", + nb: "nb-no", + ne: "ne-np", + nn: "nn-no", + pa: "pa-in", + pt: "pt-pt", + sv: "sv-se", + zh: "zh-cn" + }; + return PARTIAL_LANG_CODES[langCode] || langCode; + } + static #isRTL(lang) { + const shortCode = lang.split("-", 1)[0]; + return ["ar", "he", "fa", "ps", "ur"].includes(shortCode); + } +} +const GenericL10n = null; + +;// ./web/genericl10n.js + + + + +function createBundle(lang, text) { + const resource = new FluentResource(text); + const bundle = new FluentBundle(lang); + const errors = bundle.addResource(resource); + if (errors.length) { + console.error("L10n errors", errors); + } + return bundle; +} +class genericl10n_GenericL10n extends L10n { + constructor(lang) { + super({ + lang + }); + const generateBundles = !lang ? genericl10n_GenericL10n.#generateBundlesFallback.bind(genericl10n_GenericL10n, this.getLanguage()) : genericl10n_GenericL10n.#generateBundles.bind(genericl10n_GenericL10n, "en-us", this.getLanguage()); + this._setL10n(new DOMLocalization([], generateBundles)); + } + static async *#generateBundles(defaultLang, baseLang) { + const { + baseURL, + paths + } = await this.#getPaths(); + const langs = [baseLang]; + if (defaultLang !== baseLang) { + const shortLang = baseLang.split("-", 1)[0]; + if (shortLang !== baseLang) { + langs.push(shortLang); + } + langs.push(defaultLang); + } + for (const lang of langs) { + const bundle = await this.#createBundle(lang, baseURL, paths); + if (bundle) { + yield bundle; + } else if (lang === "en-us") { + yield this.#createBundleFallback(lang); + } + } + } + static async #createBundle(lang, baseURL, paths) { + const path = paths[lang]; + if (!path) { + return null; + } + const url = new URL(path, baseURL); + const text = await fetchData(url, "text"); + return createBundle(lang, text); + } + static async #getPaths() { + try { + const { + href + } = document.querySelector(`link[type="application/l10n"]`); + const paths = await fetchData(href, "json"); + return { + baseURL: href.replace(/[^/]*$/, "") || "./", + paths + }; + } catch {} + return { + baseURL: "./", + paths: Object.create(null) + }; + } + static async *#generateBundlesFallback(lang) { + yield this.#createBundleFallback(lang); + } + static async #createBundleFallback(lang) { + const text = "pdfjs-previous-button =\n .title = Previous Page\npdfjs-previous-button-label = Previous\npdfjs-next-button =\n .title = Next Page\npdfjs-next-button-label = Next\npdfjs-page-input =\n .title = Page\npdfjs-of-pages = of { $pagesCount }\npdfjs-page-of-pages = ({ $pageNumber } of { $pagesCount })\npdfjs-zoom-out-button =\n .title = Zoom Out\npdfjs-zoom-out-button-label = Zoom Out\npdfjs-zoom-in-button =\n .title = Zoom In\npdfjs-zoom-in-button-label = Zoom In\npdfjs-zoom-select =\n .title = Zoom\npdfjs-presentation-mode-button =\n .title = Switch to Presentation Mode\npdfjs-presentation-mode-button-label = Presentation Mode\npdfjs-open-file-button =\n .title = Open File\npdfjs-open-file-button-label = Open\npdfjs-print-button =\n .title = Print\npdfjs-print-button-label = Print\npdfjs-save-button =\n .title = Save\npdfjs-save-button-label = Save\npdfjs-download-button =\n .title = Download\npdfjs-download-button-label = Download\npdfjs-bookmark-button =\n .title = Current Page (View URL from Current Page)\npdfjs-bookmark-button-label = Current Page\npdfjs-tools-button =\n .title = Tools\npdfjs-tools-button-label = Tools\npdfjs-first-page-button =\n .title = Go to First Page\npdfjs-first-page-button-label = Go to First Page\npdfjs-last-page-button =\n .title = Go to Last Page\npdfjs-last-page-button-label = Go to Last Page\npdfjs-page-rotate-cw-button =\n .title = Rotate Clockwise\npdfjs-page-rotate-cw-button-label = Rotate Clockwise\npdfjs-page-rotate-ccw-button =\n .title = Rotate Counterclockwise\npdfjs-page-rotate-ccw-button-label = Rotate Counterclockwise\npdfjs-cursor-text-select-tool-button =\n .title = Enable Text Selection Tool\npdfjs-cursor-text-select-tool-button-label = Text Selection Tool\npdfjs-cursor-hand-tool-button =\n .title = Enable Hand Tool\npdfjs-cursor-hand-tool-button-label = Hand Tool\npdfjs-scroll-page-button =\n .title = Use Page Scrolling\npdfjs-scroll-page-button-label = Page Scrolling\npdfjs-scroll-vertical-button =\n .title = Use Vertical Scrolling\npdfjs-scroll-vertical-button-label = Vertical Scrolling\npdfjs-scroll-horizontal-button =\n .title = Use Horizontal Scrolling\npdfjs-scroll-horizontal-button-label = Horizontal Scrolling\npdfjs-scroll-wrapped-button =\n .title = Use Wrapped Scrolling\npdfjs-scroll-wrapped-button-label = Wrapped Scrolling\npdfjs-spread-none-button =\n .title = Do not join page spreads\npdfjs-spread-none-button-label = No Spreads\npdfjs-spread-odd-button =\n .title = Join page spreads starting with odd-numbered pages\npdfjs-spread-odd-button-label = Odd Spreads\npdfjs-spread-even-button =\n .title = Join page spreads starting with even-numbered pages\npdfjs-spread-even-button-label = Even Spreads\npdfjs-document-properties-button =\n .title = Document Properties\u2026\npdfjs-document-properties-button-label = Document Properties\u2026\npdfjs-document-properties-file-name = File name:\npdfjs-document-properties-file-size = File size:\npdfjs-document-properties-size-kb = { NUMBER($kb, maximumSignificantDigits: 3) } KB ({ $b } bytes)\npdfjs-document-properties-size-mb = { NUMBER($mb, maximumSignificantDigits: 3) } MB ({ $b } bytes)\npdfjs-document-properties-title = Title:\npdfjs-document-properties-author = Author:\npdfjs-document-properties-subject = Subject:\npdfjs-document-properties-keywords = Keywords:\npdfjs-document-properties-creation-date = Creation Date:\npdfjs-document-properties-modification-date = Modification Date:\npdfjs-document-properties-date-time-string = { DATETIME($dateObj, dateStyle: \"short\", timeStyle: \"medium\") }\npdfjs-document-properties-creator = Creator:\npdfjs-document-properties-producer = PDF Producer:\npdfjs-document-properties-version = PDF Version:\npdfjs-document-properties-page-count = Page Count:\npdfjs-document-properties-page-size = Page Size:\npdfjs-document-properties-page-size-unit-inches = in\npdfjs-document-properties-page-size-unit-millimeters = mm\npdfjs-document-properties-page-size-orientation-portrait = portrait\npdfjs-document-properties-page-size-orientation-landscape = landscape\npdfjs-document-properties-page-size-name-a-three = A3\npdfjs-document-properties-page-size-name-a-four = A4\npdfjs-document-properties-page-size-name-letter = Letter\npdfjs-document-properties-page-size-name-legal = Legal\npdfjs-document-properties-page-size-dimension-string = { $width } \xD7 { $height } { $unit } ({ $orientation })\npdfjs-document-properties-page-size-dimension-name-string = { $width } \xD7 { $height } { $unit } ({ $name }, { $orientation })\npdfjs-document-properties-linearized = Fast Web View:\npdfjs-document-properties-linearized-yes = Yes\npdfjs-document-properties-linearized-no = No\npdfjs-document-properties-close-button = Close\npdfjs-print-progress-message = Preparing document for printing\u2026\npdfjs-print-progress-percent = { $progress }%\npdfjs-print-progress-close-button = Cancel\npdfjs-printing-not-supported = Warning: Printing is not fully supported by this browser.\npdfjs-printing-not-ready = Warning: The PDF is not fully loaded for printing.\npdfjs-toggle-sidebar-button =\n .title = Toggle Sidebar\npdfjs-toggle-sidebar-notification-button =\n .title = Toggle Sidebar (document contains outline/attachments/layers)\npdfjs-toggle-sidebar-button-label = Toggle Sidebar\npdfjs-document-outline-button =\n .title = Show Document Outline (double-click to expand/collapse all items)\npdfjs-document-outline-button-label = Document Outline\npdfjs-attachments-button =\n .title = Show Attachments\npdfjs-attachments-button-label = Attachments\npdfjs-layers-button =\n .title = Show Layers (double-click to reset all layers to the default state)\npdfjs-layers-button-label = Layers\npdfjs-thumbs-button =\n .title = Show Thumbnails\npdfjs-thumbs-button-label = Thumbnails\npdfjs-current-outline-item-button =\n .title = Find Current Outline Item\npdfjs-current-outline-item-button-label = Current Outline Item\npdfjs-findbar-button =\n .title = Find in Document\npdfjs-findbar-button-label = Find\npdfjs-additional-layers = Additional Layers\npdfjs-thumb-page-title =\n .title = Page { $page }\npdfjs-thumb-page-canvas =\n .aria-label = Thumbnail of Page { $page }\npdfjs-find-input =\n .title = Find\n .placeholder = Find in document\u2026\npdfjs-find-previous-button =\n .title = Find the previous occurrence of the phrase\npdfjs-find-previous-button-label = Previous\npdfjs-find-next-button =\n .title = Find the next occurrence of the phrase\npdfjs-find-next-button-label = Next\npdfjs-find-highlight-checkbox = Highlight All\npdfjs-find-match-case-checkbox-label = Match Case\npdfjs-find-match-diacritics-checkbox-label = Match Diacritics\npdfjs-find-entire-word-checkbox-label = Whole Words\npdfjs-find-reached-top = Reached top of document, continued from bottom\npdfjs-find-reached-bottom = Reached end of document, continued from top\npdfjs-find-match-count =\n { $total ->\n [one] { $current } of { $total } match\n *[other] { $current } of { $total } matches\n }\npdfjs-find-match-count-limit =\n { $limit ->\n [one] More than { $limit } match\n *[other] More than { $limit } matches\n }\npdfjs-find-not-found = Phrase not found\npdfjs-page-scale-width = Page Width\npdfjs-page-scale-fit = Page Fit\npdfjs-page-scale-auto = Automatic Zoom\npdfjs-page-scale-actual = Actual Size\npdfjs-page-scale-percent = { $scale }%\npdfjs-page-landmark =\n .aria-label = Page { $page }\npdfjs-loading-error = An error occurred while loading the PDF.\npdfjs-invalid-file-error = Invalid or corrupted PDF file.\npdfjs-missing-file-error = Missing PDF file.\npdfjs-unexpected-response-error = Unexpected server response.\npdfjs-rendering-error = An error occurred while rendering the page.\npdfjs-annotation-date-time-string = { DATETIME($dateObj, dateStyle: \"short\", timeStyle: \"medium\") }\npdfjs-text-annotation-type =\n .alt = [{ $type } Annotation]\npdfjs-password-label = Enter the password to open this PDF file.\npdfjs-password-invalid = Invalid password. Please try again.\npdfjs-password-ok-button = OK\npdfjs-password-cancel-button = Cancel\npdfjs-web-fonts-disabled = Web fonts are disabled: unable to use embedded PDF fonts.\npdfjs-editor-free-text-button =\n .title = Text\npdfjs-editor-free-text-button-label = Text\npdfjs-editor-ink-button =\n .title = Draw\npdfjs-editor-ink-button-label = Draw\npdfjs-editor-stamp-button =\n .title = Add or edit images\npdfjs-editor-stamp-button-label = Add or edit images\npdfjs-editor-highlight-button =\n .title = Highlight\npdfjs-editor-highlight-button-label = Highlight\npdfjs-highlight-floating-button1 =\n .title = Highlight\n .aria-label = Highlight\npdfjs-highlight-floating-button-label = Highlight\npdfjs-editor-remove-ink-button =\n .title = Remove drawing\npdfjs-editor-remove-freetext-button =\n .title = Remove text\npdfjs-editor-remove-stamp-button =\n .title = Remove image\npdfjs-editor-remove-highlight-button =\n .title = Remove highlight\npdfjs-editor-free-text-color-input = Color\npdfjs-editor-free-text-size-input = Size\npdfjs-editor-ink-color-input = Color\npdfjs-editor-ink-thickness-input = Thickness\npdfjs-editor-ink-opacity-input = Opacity\npdfjs-editor-stamp-add-image-button =\n .title = Add image\npdfjs-editor-stamp-add-image-button-label = Add image\npdfjs-editor-free-highlight-thickness-input = Thickness\npdfjs-editor-free-highlight-thickness-title =\n .title = Change thickness when highlighting items other than text\npdfjs-free-text2 =\n .aria-label = Text Editor\n .default-content = Start typing\u2026\npdfjs-ink =\n .aria-label = Draw Editor\npdfjs-ink-canvas =\n .aria-label = User-created image\npdfjs-editor-alt-text-button =\n .aria-label = Alt text\npdfjs-editor-alt-text-button-label = Alt text\npdfjs-editor-alt-text-edit-button =\n .aria-label = Edit alt text\npdfjs-editor-alt-text-dialog-label = Choose an option\npdfjs-editor-alt-text-dialog-description = Alt text (alternative text) helps when people can\u2019t see the image or when it doesn\u2019t load.\npdfjs-editor-alt-text-add-description-label = Add a description\npdfjs-editor-alt-text-add-description-description = Aim for 1-2 sentences that describe the subject, setting, or actions.\npdfjs-editor-alt-text-mark-decorative-label = Mark as decorative\npdfjs-editor-alt-text-mark-decorative-description = This is used for ornamental images, like borders or watermarks.\npdfjs-editor-alt-text-cancel-button = Cancel\npdfjs-editor-alt-text-save-button = Save\npdfjs-editor-alt-text-decorative-tooltip = Marked as decorative\npdfjs-editor-alt-text-textarea =\n .placeholder = For example, \u201CA young man sits down at a table to eat a meal\u201D\npdfjs-editor-resizer-top-left =\n .aria-label = Top left corner \u2014 resize\npdfjs-editor-resizer-top-middle =\n .aria-label = Top middle \u2014 resize\npdfjs-editor-resizer-top-right =\n .aria-label = Top right corner \u2014 resize\npdfjs-editor-resizer-middle-right =\n .aria-label = Middle right \u2014 resize\npdfjs-editor-resizer-bottom-right =\n .aria-label = Bottom right corner \u2014 resize\npdfjs-editor-resizer-bottom-middle =\n .aria-label = Bottom middle \u2014 resize\npdfjs-editor-resizer-bottom-left =\n .aria-label = Bottom left corner \u2014 resize\npdfjs-editor-resizer-middle-left =\n .aria-label = Middle left \u2014 resize\npdfjs-editor-highlight-colorpicker-label = Highlight color\npdfjs-editor-colorpicker-button =\n .title = Change color\npdfjs-editor-colorpicker-dropdown =\n .aria-label = Color choices\npdfjs-editor-colorpicker-yellow =\n .title = Yellow\npdfjs-editor-colorpicker-green =\n .title = Green\npdfjs-editor-colorpicker-blue =\n .title = Blue\npdfjs-editor-colorpicker-pink =\n .title = Pink\npdfjs-editor-colorpicker-red =\n .title = Red\npdfjs-editor-highlight-show-all-button-label = Show all\npdfjs-editor-highlight-show-all-button =\n .title = Show all\npdfjs-editor-new-alt-text-dialog-edit-label = Edit alt text (image description)\npdfjs-editor-new-alt-text-dialog-add-label = Add alt text (image description)\npdfjs-editor-new-alt-text-textarea =\n .placeholder = Write your description here\u2026\npdfjs-editor-new-alt-text-description = Short description for people who can\u2019t see the image or when the image doesn\u2019t load.\npdfjs-editor-new-alt-text-disclaimer1 = This alt text was created automatically and may be inaccurate.\npdfjs-editor-new-alt-text-disclaimer-learn-more-url = Learn more\npdfjs-editor-new-alt-text-create-automatically-button-label = Create alt text automatically\npdfjs-editor-new-alt-text-not-now-button = Not now\npdfjs-editor-new-alt-text-error-title = Couldn\u2019t create alt text automatically\npdfjs-editor-new-alt-text-error-description = Please write your own alt text or try again later.\npdfjs-editor-new-alt-text-error-close-button = Close\npdfjs-editor-new-alt-text-ai-model-downloading-progress = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\n .aria-valuetext = Downloading alt text AI model ({ $downloadedSize } of { $totalSize } MB)\npdfjs-editor-new-alt-text-added-button =\n .aria-label = Alt text added\npdfjs-editor-new-alt-text-added-button-label = Alt text added\npdfjs-editor-new-alt-text-missing-button =\n .aria-label = Missing alt text\npdfjs-editor-new-alt-text-missing-button-label = Missing alt text\npdfjs-editor-new-alt-text-to-review-button =\n .aria-label = Review alt text\npdfjs-editor-new-alt-text-to-review-button-label = Review alt text\npdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer = Created automatically: { $generatedAltText }\npdfjs-image-alt-text-settings-button =\n .title = Image alt text settings\npdfjs-image-alt-text-settings-button-label = Image alt text settings\npdfjs-editor-alt-text-settings-dialog-label = Image alt text settings\npdfjs-editor-alt-text-settings-automatic-title = Automatic alt text\npdfjs-editor-alt-text-settings-create-model-button-label = Create alt text automatically\npdfjs-editor-alt-text-settings-create-model-description = Suggests descriptions to help people who can\u2019t see the image or when the image doesn\u2019t load.\npdfjs-editor-alt-text-settings-download-model-label = Alt text AI model ({ $totalSize } MB)\npdfjs-editor-alt-text-settings-ai-model-description = Runs locally on your device so your data stays private. Required for automatic alt text.\npdfjs-editor-alt-text-settings-delete-model-button = Delete\npdfjs-editor-alt-text-settings-download-model-button = Download\npdfjs-editor-alt-text-settings-downloading-model-button = Downloading\u2026\npdfjs-editor-alt-text-settings-editor-title = Alt text editor\npdfjs-editor-alt-text-settings-show-dialog-button-label = Show alt text editor right away when adding an image\npdfjs-editor-alt-text-settings-show-dialog-description = Helps you make sure all your images have alt text.\npdfjs-editor-alt-text-settings-close-button = Close\npdfjs-editor-undo-bar-message-highlight = Highlight removed\npdfjs-editor-undo-bar-message-freetext = Text removed\npdfjs-editor-undo-bar-message-ink = Drawing removed\npdfjs-editor-undo-bar-message-stamp = Image removed\npdfjs-editor-undo-bar-message-multiple =\n { $count ->\n [one] { $count } annotation removed\n *[other] { $count } annotations removed\n }\npdfjs-editor-undo-bar-undo-button =\n .title = Undo\npdfjs-editor-undo-bar-undo-button-label = Undo\npdfjs-editor-undo-bar-close-button =\n .title = Close\npdfjs-editor-undo-bar-close-button-label = Close"; + return createBundle(lang, text); + } +} + +;// ./web/generic_scripting.js + +async function docProperties(pdfDocument) { + const url = "", + baseUrl = url.split("#", 1)[0]; + let { + info, + metadata, + contentDispositionFilename, + contentLength + } = await pdfDocument.getMetadata(); + if (!contentLength) { + const { + length + } = await pdfDocument.getDownloadInfo(); + contentLength = length; + } + return { + ...info, + baseURL: baseUrl, + filesize: contentLength, + filename: contentDispositionFilename || getPdfFilenameFromUrl(url), + metadata: metadata?.getRaw(), + authors: metadata?.get("dc:creator"), + numPages: pdfDocument.numPages, + URL: url + }; +} +class GenericScripting { + constructor(sandboxBundleSrc) { + this._ready = new Promise((resolve, reject) => { + const sandbox = import(/*webpackIgnore: true*/sandboxBundleSrc); + sandbox.then(pdfjsSandbox => { + resolve(pdfjsSandbox.QuickJSSandbox()); + }).catch(reject); + }); + } + async createSandbox(data) { + const sandbox = await this._ready; + sandbox.create(data); + } + async dispatchEventInSandbox(event) { + const sandbox = await this._ready; + setTimeout(() => sandbox.dispatchEvent(event), 0); + } + async destroySandbox() { + const sandbox = await this._ready; + sandbox.nukeSandbox(); + } +} + +;// ./web/genericcom.js + + + + + +function initCom(app) {} +class Preferences extends BasePreferences { + async _writeToStorage(prefObj) { + localStorage.setItem("pdfjs.preferences", JSON.stringify(prefObj)); + } + async _readFromStorage(prefObj) { + return { + prefs: JSON.parse(localStorage.getItem("pdfjs.preferences")) + }; + } +} +class ExternalServices extends BaseExternalServices { + async createL10n() { + return new genericl10n_GenericL10n(AppOptions.get("localeProperties")?.lang); + } + createScripting() { + return new GenericScripting(AppOptions.get("sandboxBundleSrc")); + } +} +class MLManager { + async isEnabledFor(_name) { + return false; + } + async deleteModel(_service) { + return null; + } + isReady(_name) { + return false; + } + guess(_data) {} + toggleService(_name, _enabled) {} + static getFakeMLManager(options) { + return new FakeMLManager(options); + } +} +class FakeMLManager { + eventBus = null; + hasProgress = false; + constructor({ + enableGuessAltText, + enableAltTextModelDownload + }) { + this.enableGuessAltText = enableGuessAltText; + this.enableAltTextModelDownload = enableAltTextModelDownload; + } + setEventBus(eventBus, abortSignal) { + this.eventBus = eventBus; + } + async isEnabledFor(_name) { + return this.enableGuessAltText; + } + async deleteModel(_name) { + this.enableAltTextModelDownload = false; + return null; + } + async loadModel(_name) {} + async downloadModel(_name) { + this.hasProgress = true; + const { + promise, + resolve + } = Promise.withResolvers(); + const total = 1e8; + const end = 1.5 * total; + const increment = 5e6; + let loaded = 0; + const id = setInterval(() => { + loaded += increment; + if (loaded <= end) { + this.eventBus.dispatch("loadaiengineprogress", { + source: this, + detail: { + total, + totalLoaded: loaded, + finished: loaded + increment >= end + } + }); + return; + } + clearInterval(id); + this.hasProgress = false; + this.enableAltTextModelDownload = true; + resolve(true); + }, 900); + return promise; + } + isReady(_name) { + return this.enableAltTextModelDownload; + } + guess({ + request: { + data + } + }) { + return new Promise(resolve => { + setTimeout(() => { + resolve(data ? { + output: "Fake alt text." + } : { + error: true + }); + }, 3000); + }); + } + toggleService(_name, enabled) { + this.enableGuessAltText = enabled; + } +} + +;// ./web/new_alt_text_manager.js + +class NewAltTextManager { + #boundCancel = this.#cancel.bind(this); + #createAutomaticallyButton; + #currentEditor = null; + #cancelButton; + #descriptionContainer; + #dialog; + #disclaimer; + #downloadModel; + #downloadModelDescription; + #eventBus; + #firstTime = false; + #guessedAltText; + #hasAI = null; + #isEditing = null; + #imagePreview; + #imageData; + #isAILoading = false; + #wasAILoading = false; + #learnMore; + #notNowButton; + #overlayManager; + #textarea; + #title; + #uiManager; + #previousAltText = null; + constructor({ + descriptionContainer, + dialog, + imagePreview, + cancelButton, + disclaimer, + notNowButton, + saveButton, + textarea, + learnMore, + errorCloseButton, + createAutomaticallyButton, + downloadModel, + downloadModelDescription, + title + }, overlayManager, eventBus) { + this.#cancelButton = cancelButton; + this.#createAutomaticallyButton = createAutomaticallyButton; + this.#descriptionContainer = descriptionContainer; + this.#dialog = dialog; + this.#disclaimer = disclaimer; + this.#notNowButton = notNowButton; + this.#imagePreview = imagePreview; + this.#textarea = textarea; + this.#learnMore = learnMore; + this.#title = title; + this.#downloadModel = downloadModel; + this.#downloadModelDescription = downloadModelDescription; + this.#overlayManager = overlayManager; + this.#eventBus = eventBus; + dialog.addEventListener("close", this.#close.bind(this)); + dialog.addEventListener("contextmenu", event => { + if (event.target !== this.#textarea) { + event.preventDefault(); + } + }); + cancelButton.addEventListener("click", this.#boundCancel); + notNowButton.addEventListener("click", this.#boundCancel); + saveButton.addEventListener("click", this.#save.bind(this)); + errorCloseButton.addEventListener("click", () => { + this.#toggleError(false); + }); + createAutomaticallyButton.addEventListener("click", async () => { + const checked = createAutomaticallyButton.getAttribute("aria-pressed") !== "true"; + this.#currentEditor._reportTelemetry({ + action: "pdfjs.image.alt_text.ai_generation_check", + data: { + status: checked + } + }); + if (this.#uiManager) { + this.#uiManager.setPreference("enableGuessAltText", checked); + await this.#uiManager.mlManager.toggleService("altText", checked); + } + this.#toggleGuessAltText(checked, false); + }); + textarea.addEventListener("focus", () => { + this.#wasAILoading = this.#isAILoading; + this.#toggleLoading(false); + this.#toggleTitleAndDisclaimer(); + }); + textarea.addEventListener("blur", () => { + if (!textarea.value) { + this.#toggleLoading(this.#wasAILoading); + } + this.#toggleTitleAndDisclaimer(); + }); + textarea.addEventListener("input", () => { + this.#toggleTitleAndDisclaimer(); + }); + eventBus._on("enableguessalttext", ({ + value + }) => { + this.#toggleGuessAltText(value, false); + }); + this.#overlayManager.register(dialog); + this.#learnMore.addEventListener("click", () => { + this.#currentEditor._reportTelemetry({ + action: "pdfjs.image.alt_text.info", + data: { + topic: "alt_text" + } + }); + }); + } + #toggleLoading(value) { + if (!this.#uiManager || this.#isAILoading === value) { + return; + } + this.#isAILoading = value; + this.#descriptionContainer.classList.toggle("loading", value); + } + #toggleError(value) { + if (!this.#uiManager) { + return; + } + this.#dialog.classList.toggle("error", value); + } + async #toggleGuessAltText(value, isInitial = false) { + if (!this.#uiManager) { + return; + } + this.#dialog.classList.toggle("aiDisabled", !value); + this.#createAutomaticallyButton.setAttribute("aria-pressed", value); + if (value) { + const { + altTextLearnMoreUrl + } = this.#uiManager.mlManager; + if (altTextLearnMoreUrl) { + this.#learnMore.href = altTextLearnMoreUrl; + } + this.#mlGuessAltText(isInitial); + } else { + this.#toggleLoading(false); + this.#isAILoading = false; + this.#toggleTitleAndDisclaimer(); + } + } + #toggleNotNow() { + this.#notNowButton.classList.toggle("hidden", !this.#firstTime); + this.#cancelButton.classList.toggle("hidden", this.#firstTime); + } + #toggleAI(value) { + if (!this.#uiManager || this.#hasAI === value) { + return; + } + this.#hasAI = value; + this.#dialog.classList.toggle("noAi", !value); + this.#toggleTitleAndDisclaimer(); + } + #toggleTitleAndDisclaimer() { + const visible = this.#isAILoading || this.#guessedAltText && this.#guessedAltText === this.#textarea.value; + this.#disclaimer.hidden = !visible; + const isEditing = this.#isAILoading || !!this.#textarea.value; + if (this.#isEditing === isEditing) { + return; + } + this.#isEditing = isEditing; + this.#title.setAttribute("data-l10n-id", isEditing ? "pdfjs-editor-new-alt-text-dialog-edit-label" : "pdfjs-editor-new-alt-text-dialog-add-label"); + } + async #mlGuessAltText(isInitial) { + if (this.#isAILoading) { + return; + } + if (this.#textarea.value) { + return; + } + if (isInitial && this.#previousAltText !== null) { + return; + } + this.#guessedAltText = this.#currentEditor.guessedAltText; + if (this.#previousAltText === null && this.#guessedAltText) { + this.#addAltText(this.#guessedAltText); + return; + } + this.#toggleLoading(true); + this.#toggleTitleAndDisclaimer(); + let hasError = false; + try { + const altText = await this.#currentEditor.mlGuessAltText(this.#imageData, false); + if (altText) { + this.#guessedAltText = altText; + this.#wasAILoading = this.#isAILoading; + if (this.#isAILoading) { + this.#addAltText(altText); + } + } + } catch (e) { + console.error(e); + hasError = true; + } + this.#toggleLoading(false); + this.#toggleTitleAndDisclaimer(); + if (hasError && this.#uiManager) { + this.#toggleError(true); + } + } + #addAltText(altText) { + if (!this.#uiManager || this.#textarea.value) { + return; + } + this.#textarea.value = altText; + this.#toggleTitleAndDisclaimer(); + } + #setProgress() { + this.#downloadModel.classList.toggle("hidden", false); + const callback = async ({ + detail: { + finished, + total, + totalLoaded + } + }) => { + const ONE_MEGA_BYTES = 1e6; + totalLoaded = Math.min(0.99 * total, totalLoaded); + const totalSize = this.#downloadModelDescription.ariaValueMax = Math.round(total / ONE_MEGA_BYTES); + const downloadedSize = this.#downloadModelDescription.ariaValueNow = Math.round(totalLoaded / ONE_MEGA_BYTES); + this.#downloadModelDescription.setAttribute("data-l10n-args", JSON.stringify({ + totalSize, + downloadedSize + })); + if (!finished) { + return; + } + this.#eventBus._off("loadaiengineprogress", callback); + this.#downloadModel.classList.toggle("hidden", true); + this.#toggleAI(true); + if (!this.#uiManager) { + return; + } + const { + mlManager + } = this.#uiManager; + mlManager.toggleService("altText", true); + this.#toggleGuessAltText(await mlManager.isEnabledFor("altText"), true); + }; + this.#eventBus._on("loadaiengineprogress", callback); + } + async editAltText(uiManager, editor, firstTime) { + if (this.#currentEditor || !editor) { + return; + } + if (firstTime && editor.hasAltTextData()) { + editor.altTextFinish(); + return; + } + this.#firstTime = firstTime; + let { + mlManager + } = uiManager; + let hasAI = !!mlManager; + this.#toggleTitleAndDisclaimer(); + if (mlManager && !mlManager.isReady("altText")) { + hasAI = false; + if (mlManager.hasProgress) { + this.#setProgress(); + } else { + mlManager = null; + } + } else { + this.#downloadModel.classList.toggle("hidden", true); + } + const isAltTextEnabledPromise = mlManager?.isEnabledFor("altText"); + this.#currentEditor = editor; + this.#uiManager = uiManager; + this.#uiManager.removeEditListeners(); + ({ + altText: this.#previousAltText + } = editor.altTextData); + this.#textarea.value = this.#previousAltText ?? ""; + const AI_MAX_IMAGE_DIMENSION = 224; + const MAX_PREVIEW_DIMENSION = 180; + let canvas, width, height; + if (mlManager) { + ({ + canvas, + width, + height, + imageData: this.#imageData + } = editor.copyCanvas(AI_MAX_IMAGE_DIMENSION, MAX_PREVIEW_DIMENSION, true)); + if (hasAI) { + this.#toggleGuessAltText(await isAltTextEnabledPromise, true); + } + } else { + ({ + canvas, + width, + height + } = editor.copyCanvas(AI_MAX_IMAGE_DIMENSION, MAX_PREVIEW_DIMENSION, false)); + } + canvas.setAttribute("role", "presentation"); + const { + style + } = canvas; + style.width = `${width}px`; + style.height = `${height}px`; + this.#imagePreview.append(canvas); + this.#toggleNotNow(); + this.#toggleAI(hasAI); + this.#toggleError(false); + try { + await this.#overlayManager.open(this.#dialog); + } catch (ex) { + this.#close(); + throw ex; + } + } + #cancel() { + this.#currentEditor.altTextData = { + cancel: true + }; + const altText = this.#textarea.value.trim(); + this.#currentEditor._reportTelemetry({ + action: "pdfjs.image.alt_text.dismiss", + data: { + alt_text_type: altText ? "present" : "empty", + flow: this.#firstTime ? "image_add" : "alt_text_edit" + } + }); + this.#currentEditor._reportTelemetry({ + action: "pdfjs.image.image_added", + data: { + alt_text_modal: true, + alt_text_type: "skipped" + } + }); + this.#finish(); + } + #finish() { + if (this.#overlayManager.active === this.#dialog) { + this.#overlayManager.close(this.#dialog); + } + } + #close() { + const canvas = this.#imagePreview.firstChild; + canvas.remove(); + canvas.width = canvas.height = 0; + this.#imageData = null; + this.#toggleLoading(false); + this.#uiManager?.addEditListeners(); + this.#currentEditor.altTextFinish(); + this.#uiManager?.setSelected(this.#currentEditor); + this.#currentEditor = null; + this.#uiManager = null; + } + #extractWords(text) { + return new Set(text.toLowerCase().split(/[^\p{L}\p{N}]+/gu).filter(x => !!x)); + } + #save() { + const altText = this.#textarea.value.trim(); + this.#currentEditor.altTextData = { + altText, + decorative: false + }; + this.#currentEditor.altTextData.guessedAltText = this.#guessedAltText; + if (this.#guessedAltText && this.#guessedAltText !== altText) { + const guessedWords = this.#extractWords(this.#guessedAltText); + const words = this.#extractWords(altText); + this.#currentEditor._reportTelemetry({ + action: "pdfjs.image.alt_text.user_edit", + data: { + total_words: guessedWords.size, + words_removed: guessedWords.difference(words).size, + words_added: words.difference(guessedWords).size + } + }); + } + this.#currentEditor._reportTelemetry({ + action: "pdfjs.image.image_added", + data: { + alt_text_modal: true, + alt_text_type: altText ? "present" : "empty" + } + }); + this.#currentEditor._reportTelemetry({ + action: "pdfjs.image.alt_text.save", + data: { + alt_text_type: altText ? "present" : "empty", + flow: this.#firstTime ? "image_add" : "alt_text_edit" + } + }); + this.#finish(); + } + destroy() { + this.#uiManager = null; + this.#finish(); + } +} +class ImageAltTextSettings { + #aiModelSettings; + #createModelButton; + #downloadModelButton; + #dialog; + #eventBus; + #mlManager; + #overlayManager; + #showAltTextDialogButton; + constructor({ + dialog, + createModelButton, + aiModelSettings, + learnMore, + closeButton, + deleteModelButton, + downloadModelButton, + showAltTextDialogButton + }, overlayManager, eventBus, mlManager) { + this.#dialog = dialog; + this.#aiModelSettings = aiModelSettings; + this.#createModelButton = createModelButton; + this.#downloadModelButton = downloadModelButton; + this.#showAltTextDialogButton = showAltTextDialogButton; + this.#overlayManager = overlayManager; + this.#eventBus = eventBus; + this.#mlManager = mlManager; + const { + altTextLearnMoreUrl + } = mlManager; + if (altTextLearnMoreUrl) { + learnMore.href = altTextLearnMoreUrl; + } + dialog.addEventListener("contextmenu", noContextMenu); + createModelButton.addEventListener("click", async e => { + const checked = this.#togglePref("enableGuessAltText", e); + await mlManager.toggleService("altText", checked); + this.#reportTelemetry({ + type: "stamp", + action: "pdfjs.image.alt_text.settings_ai_generation_check", + data: { + status: checked + } + }); + }); + showAltTextDialogButton.addEventListener("click", e => { + const checked = this.#togglePref("enableNewAltTextWhenAddingImage", e); + this.#reportTelemetry({ + type: "stamp", + action: "pdfjs.image.alt_text.settings_edit_alt_text_check", + data: { + status: checked + } + }); + }); + deleteModelButton.addEventListener("click", this.#delete.bind(this, true)); + downloadModelButton.addEventListener("click", this.#download.bind(this, true)); + closeButton.addEventListener("click", this.#finish.bind(this)); + learnMore.addEventListener("click", () => { + this.#reportTelemetry({ + type: "stamp", + action: "pdfjs.image.alt_text.info", + data: { + topic: "ai_generation" + } + }); + }); + eventBus._on("enablealttextmodeldownload", ({ + value + }) => { + if (value) { + this.#download(false); + } else { + this.#delete(false); + } + }); + this.#overlayManager.register(dialog); + } + #reportTelemetry(data) { + this.#eventBus.dispatch("reporttelemetry", { + source: this, + details: { + type: "editing", + data + } + }); + } + async #download(isFromUI = false) { + if (isFromUI) { + this.#downloadModelButton.disabled = true; + const span = this.#downloadModelButton.firstChild; + span.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-settings-downloading-model-button"); + await this.#mlManager.downloadModel("altText"); + span.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-settings-download-model-button"); + this.#createModelButton.disabled = false; + this.#setPref("enableGuessAltText", true); + this.#mlManager.toggleService("altText", true); + this.#setPref("enableAltTextModelDownload", true); + this.#downloadModelButton.disabled = false; + } + this.#aiModelSettings.classList.toggle("download", false); + this.#createModelButton.setAttribute("aria-pressed", true); + } + async #delete(isFromUI = false) { + if (isFromUI) { + await this.#mlManager.deleteModel("altText"); + this.#setPref("enableGuessAltText", false); + this.#setPref("enableAltTextModelDownload", false); + } + this.#aiModelSettings.classList.toggle("download", true); + this.#createModelButton.disabled = true; + this.#createModelButton.setAttribute("aria-pressed", false); + } + async open({ + enableGuessAltText, + enableNewAltTextWhenAddingImage + }) { + const { + enableAltTextModelDownload + } = this.#mlManager; + this.#createModelButton.disabled = !enableAltTextModelDownload; + this.#createModelButton.setAttribute("aria-pressed", enableAltTextModelDownload && enableGuessAltText); + this.#showAltTextDialogButton.setAttribute("aria-pressed", enableNewAltTextWhenAddingImage); + this.#aiModelSettings.classList.toggle("download", !enableAltTextModelDownload); + await this.#overlayManager.open(this.#dialog); + this.#reportTelemetry({ + type: "stamp", + action: "pdfjs.image.alt_text.settings_displayed" + }); + } + #togglePref(name, { + target + }) { + const checked = target.getAttribute("aria-pressed") !== "true"; + this.#setPref(name, checked); + target.setAttribute("aria-pressed", checked); + return checked; + } + #setPref(name, value) { + this.#eventBus.dispatch("setpreference", { + source: this, + name, + value + }); + } + #finish() { + if (this.#overlayManager.active === this.#dialog) { + this.#overlayManager.close(this.#dialog); + } + } +} + +;// ./web/alt_text_manager.js + +class AltTextManager { + #clickAC = null; + #currentEditor = null; + #cancelButton; + #dialog; + #eventBus; + #hasUsedPointer = false; + #optionDescription; + #optionDecorative; + #overlayManager; + #saveButton; + #textarea; + #uiManager; + #previousAltText = null; + #resizeAC = null; + #svgElement = null; + #rectElement = null; + #container; + #telemetryData = null; + constructor({ + dialog, + optionDescription, + optionDecorative, + textarea, + cancelButton, + saveButton + }, container, overlayManager, eventBus) { + this.#dialog = dialog; + this.#optionDescription = optionDescription; + this.#optionDecorative = optionDecorative; + this.#textarea = textarea; + this.#cancelButton = cancelButton; + this.#saveButton = saveButton; + this.#overlayManager = overlayManager; + this.#eventBus = eventBus; + this.#container = container; + const onUpdateUIState = this.#updateUIState.bind(this); + dialog.addEventListener("close", this.#close.bind(this)); + dialog.addEventListener("contextmenu", event => { + if (event.target !== this.#textarea) { + event.preventDefault(); + } + }); + cancelButton.addEventListener("click", this.#finish.bind(this)); + saveButton.addEventListener("click", this.#save.bind(this)); + optionDescription.addEventListener("change", onUpdateUIState); + optionDecorative.addEventListener("change", onUpdateUIState); + this.#overlayManager.register(dialog); + } + #createSVGElement() { + if (this.#svgElement) { + return; + } + const svgFactory = new DOMSVGFactory(); + const svg = this.#svgElement = svgFactory.createElement("svg"); + svg.setAttribute("width", "0"); + svg.setAttribute("height", "0"); + const defs = svgFactory.createElement("defs"); + svg.append(defs); + const mask = svgFactory.createElement("mask"); + defs.append(mask); + mask.setAttribute("id", "alttext-manager-mask"); + mask.setAttribute("maskContentUnits", "objectBoundingBox"); + let rect = svgFactory.createElement("rect"); + mask.append(rect); + rect.setAttribute("fill", "white"); + rect.setAttribute("width", "1"); + rect.setAttribute("height", "1"); + rect.setAttribute("x", "0"); + rect.setAttribute("y", "0"); + rect = this.#rectElement = svgFactory.createElement("rect"); + mask.append(rect); + rect.setAttribute("fill", "black"); + this.#dialog.append(svg); + } + async editAltText(uiManager, editor) { + if (this.#currentEditor || !editor) { + return; + } + this.#createSVGElement(); + this.#hasUsedPointer = false; + this.#clickAC = new AbortController(); + const clickOpts = { + signal: this.#clickAC.signal + }, + onClick = this.#onClick.bind(this); + for (const element of [this.#optionDescription, this.#optionDecorative, this.#textarea, this.#saveButton, this.#cancelButton]) { + element.addEventListener("click", onClick, clickOpts); + } + const { + altText, + decorative + } = editor.altTextData; + if (decorative === true) { + this.#optionDecorative.checked = true; + this.#optionDescription.checked = false; + } else { + this.#optionDecorative.checked = false; + this.#optionDescription.checked = true; + } + this.#previousAltText = this.#textarea.value = altText?.trim() || ""; + this.#updateUIState(); + this.#currentEditor = editor; + this.#uiManager = uiManager; + this.#uiManager.removeEditListeners(); + this.#resizeAC = new AbortController(); + this.#eventBus._on("resize", this.#setPosition.bind(this), { + signal: this.#resizeAC.signal + }); + try { + await this.#overlayManager.open(this.#dialog); + this.#setPosition(); + } catch (ex) { + this.#close(); + throw ex; + } + } + #setPosition() { + if (!this.#currentEditor) { + return; + } + const dialog = this.#dialog; + const { + style + } = dialog; + const { + x: containerX, + y: containerY, + width: containerW, + height: containerH + } = this.#container.getBoundingClientRect(); + const { + innerWidth: windowW, + innerHeight: windowH + } = window; + const { + width: dialogW, + height: dialogH + } = dialog.getBoundingClientRect(); + const { + x, + y, + width, + height + } = this.#currentEditor.getClientDimensions(); + const MARGIN = 10; + const isLTR = this.#uiManager.direction === "ltr"; + const xs = Math.max(x, containerX); + const xe = Math.min(x + width, containerX + containerW); + const ys = Math.max(y, containerY); + const ye = Math.min(y + height, containerY + containerH); + this.#rectElement.setAttribute("width", `${(xe - xs) / windowW}`); + this.#rectElement.setAttribute("height", `${(ye - ys) / windowH}`); + this.#rectElement.setAttribute("x", `${xs / windowW}`); + this.#rectElement.setAttribute("y", `${ys / windowH}`); + let left = null; + let top = Math.max(y, 0); + top += Math.min(windowH - (top + dialogH), 0); + if (isLTR) { + if (x + width + MARGIN + dialogW < windowW) { + left = x + width + MARGIN; + } else if (x > dialogW + MARGIN) { + left = x - dialogW - MARGIN; + } + } else if (x > dialogW + MARGIN) { + left = x - dialogW - MARGIN; + } else if (x + width + MARGIN + dialogW < windowW) { + left = x + width + MARGIN; + } + if (left === null) { + top = null; + left = Math.max(x, 0); + left += Math.min(windowW - (left + dialogW), 0); + if (y > dialogH + MARGIN) { + top = y - dialogH - MARGIN; + } else if (y + height + MARGIN + dialogH < windowH) { + top = y + height + MARGIN; + } + } + if (top !== null) { + dialog.classList.add("positioned"); + if (isLTR) { + style.left = `${left}px`; + } else { + style.right = `${windowW - left - dialogW}px`; + } + style.top = `${top}px`; + } else { + dialog.classList.remove("positioned"); + style.left = ""; + style.top = ""; + } + } + #finish() { + if (this.#overlayManager.active === this.#dialog) { + this.#overlayManager.close(this.#dialog); + } + } + #close() { + this.#currentEditor._reportTelemetry(this.#telemetryData || { + action: "alt_text_cancel", + alt_text_keyboard: !this.#hasUsedPointer + }); + this.#telemetryData = null; + this.#removeOnClickListeners(); + this.#uiManager?.addEditListeners(); + this.#resizeAC?.abort(); + this.#resizeAC = null; + this.#currentEditor.altTextFinish(); + this.#currentEditor = null; + this.#uiManager = null; + } + #updateUIState() { + this.#textarea.disabled = this.#optionDecorative.checked; + } + #save() { + const altText = this.#textarea.value.trim(); + const decorative = this.#optionDecorative.checked; + this.#currentEditor.altTextData = { + altText, + decorative + }; + this.#telemetryData = { + action: "alt_text_save", + alt_text_description: !!altText, + alt_text_edit: !!this.#previousAltText && this.#previousAltText !== altText, + alt_text_decorative: decorative, + alt_text_keyboard: !this.#hasUsedPointer + }; + this.#finish(); + } + #onClick(evt) { + if (evt.detail === 0) { + return; + } + this.#hasUsedPointer = true; + this.#removeOnClickListeners(); + } + #removeOnClickListeners() { + this.#clickAC?.abort(); + this.#clickAC = null; + } + destroy() { + this.#uiManager = null; + this.#finish(); + this.#svgElement?.remove(); + this.#svgElement = this.#rectElement = null; + } +} + +;// ./web/annotation_editor_params.js + +class AnnotationEditorParams { + constructor(options, eventBus) { + this.eventBus = eventBus; + this.#bindListeners(options); + } + #bindListeners({ + editorFreeTextFontSize, + editorFreeTextColor, + editorInkColor, + editorInkThickness, + editorInkOpacity, + editorStampAddImage, + editorFreeHighlightThickness, + editorHighlightShowAll + }) { + const dispatchEvent = (typeStr, value) => { + this.eventBus.dispatch("switchannotationeditorparams", { + source: this, + type: AnnotationEditorParamsType[typeStr], + value + }); + }; + editorFreeTextFontSize.addEventListener("input", function () { + dispatchEvent("FREETEXT_SIZE", this.valueAsNumber); + }); + editorFreeTextColor.addEventListener("input", function () { + dispatchEvent("FREETEXT_COLOR", this.value); + }); + editorInkColor.addEventListener("input", function () { + dispatchEvent("INK_COLOR", this.value); + }); + editorInkThickness.addEventListener("input", function () { + dispatchEvent("INK_THICKNESS", this.valueAsNumber); + }); + editorInkOpacity.addEventListener("input", function () { + dispatchEvent("INK_OPACITY", this.valueAsNumber); + }); + editorStampAddImage.addEventListener("click", () => { + this.eventBus.dispatch("reporttelemetry", { + source: this, + details: { + type: "editing", + data: { + action: "pdfjs.image.add_image_click" + } + } + }); + dispatchEvent("CREATE"); + }); + editorFreeHighlightThickness.addEventListener("input", function () { + dispatchEvent("HIGHLIGHT_THICKNESS", this.valueAsNumber); + }); + editorHighlightShowAll.addEventListener("click", function () { + const checked = this.getAttribute("aria-pressed") === "true"; + this.setAttribute("aria-pressed", !checked); + dispatchEvent("HIGHLIGHT_SHOW_ALL", !checked); + }); + this.eventBus._on("annotationeditorparamschanged", evt => { + for (const [type, value] of evt.details) { + switch (type) { + case AnnotationEditorParamsType.FREETEXT_SIZE: + editorFreeTextFontSize.value = value; + break; + case AnnotationEditorParamsType.FREETEXT_COLOR: + editorFreeTextColor.value = value; + break; + case AnnotationEditorParamsType.INK_COLOR: + editorInkColor.value = value; + break; + case AnnotationEditorParamsType.INK_THICKNESS: + editorInkThickness.value = value; + break; + case AnnotationEditorParamsType.INK_OPACITY: + editorInkOpacity.value = value; + break; + case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS: + editorFreeHighlightThickness.value = value; + break; + case AnnotationEditorParamsType.HIGHLIGHT_FREE: + editorFreeHighlightThickness.disabled = !value; + break; + case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL: + editorHighlightShowAll.setAttribute("aria-pressed", value); + break; + } + } + }); + } +} + +;// ./web/caret_browsing.js +const PRECISION = 1e-1; +class CaretBrowsingMode { + #mainContainer; + #toolBarHeight = 0; + #viewerContainer; + constructor(abortSignal, mainContainer, viewerContainer, toolbarContainer) { + this.#mainContainer = mainContainer; + this.#viewerContainer = viewerContainer; + if (!toolbarContainer) { + return; + } + this.#toolBarHeight = toolbarContainer.getBoundingClientRect().height; + const toolbarObserver = new ResizeObserver(entries => { + for (const entry of entries) { + if (entry.target === toolbarContainer) { + this.#toolBarHeight = Math.floor(entry.borderBoxSize[0].blockSize); + break; + } + } + }); + toolbarObserver.observe(toolbarContainer); + abortSignal.addEventListener("abort", () => toolbarObserver.disconnect(), { + once: true + }); + } + #isOnSameLine(rect1, rect2) { + const top1 = rect1.y; + const bot1 = rect1.bottom; + const mid1 = rect1.y + rect1.height / 2; + const top2 = rect2.y; + const bot2 = rect2.bottom; + const mid2 = rect2.y + rect2.height / 2; + return top1 <= mid2 && mid2 <= bot1 || top2 <= mid1 && mid1 <= bot2; + } + #isUnderOver(rect, x, y, isUp) { + const midY = rect.y + rect.height / 2; + return (isUp ? y >= midY : y <= midY) && rect.x - PRECISION <= x && x <= rect.right + PRECISION; + } + #isVisible(rect) { + return rect.top >= this.#toolBarHeight && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth); + } + #getCaretPosition(selection, isUp) { + const { + focusNode, + focusOffset + } = selection; + const range = document.createRange(); + range.setStart(focusNode, focusOffset); + range.setEnd(focusNode, focusOffset); + const rect = range.getBoundingClientRect(); + return [rect.x, isUp ? rect.top : rect.bottom]; + } + static #caretPositionFromPoint(x, y) { + if (!document.caretPositionFromPoint) { + const { + startContainer: offsetNode, + startOffset: offset + } = document.caretRangeFromPoint(x, y); + return { + offsetNode, + offset + }; + } + return document.caretPositionFromPoint(x, y); + } + #setCaretPositionHelper(selection, caretX, select, element, rect) { + rect ||= element.getBoundingClientRect(); + if (caretX <= rect.x + PRECISION) { + if (select) { + selection.extend(element.firstChild, 0); + } else { + selection.setPosition(element.firstChild, 0); + } + return; + } + if (rect.right - PRECISION <= caretX) { + const { + lastChild + } = element; + if (select) { + selection.extend(lastChild, lastChild.length); + } else { + selection.setPosition(lastChild, lastChild.length); + } + return; + } + const midY = rect.y + rect.height / 2; + let caretPosition = CaretBrowsingMode.#caretPositionFromPoint(caretX, midY); + let parentElement = caretPosition.offsetNode?.parentElement; + if (parentElement && parentElement !== element) { + const elementsAtPoint = document.elementsFromPoint(caretX, midY); + const savedVisibilities = []; + for (const el of elementsAtPoint) { + if (el === element) { + break; + } + const { + style + } = el; + savedVisibilities.push([el, style.visibility]); + style.visibility = "hidden"; + } + caretPosition = CaretBrowsingMode.#caretPositionFromPoint(caretX, midY); + parentElement = caretPosition.offsetNode?.parentElement; + for (const [el, visibility] of savedVisibilities) { + el.style.visibility = visibility; + } + } + if (parentElement !== element) { + if (select) { + selection.extend(element.firstChild, 0); + } else { + selection.setPosition(element.firstChild, 0); + } + return; + } + if (select) { + selection.extend(caretPosition.offsetNode, caretPosition.offset); + } else { + selection.setPosition(caretPosition.offsetNode, caretPosition.offset); + } + } + #setCaretPosition(select, selection, newLineElement, newLineElementRect, caretX) { + if (this.#isVisible(newLineElementRect)) { + this.#setCaretPositionHelper(selection, caretX, select, newLineElement, newLineElementRect); + return; + } + this.#mainContainer.addEventListener("scrollend", this.#setCaretPositionHelper.bind(this, selection, caretX, select, newLineElement, null), { + once: true + }); + newLineElement.scrollIntoView(); + } + #getNodeOnNextPage(textLayer, isUp) { + while (true) { + const page = textLayer.closest(".page"); + const pageNumber = parseInt(page.getAttribute("data-page-number")); + const nextPage = isUp ? pageNumber - 1 : pageNumber + 1; + textLayer = this.#viewerContainer.querySelector(`.page[data-page-number="${nextPage}"] .textLayer`); + if (!textLayer) { + return null; + } + const walker = document.createTreeWalker(textLayer, NodeFilter.SHOW_TEXT); + const node = isUp ? walker.lastChild() : walker.firstChild(); + if (node) { + return node; + } + } + } + moveCaret(isUp, select) { + const selection = document.getSelection(); + if (selection.rangeCount === 0) { + return; + } + const { + focusNode + } = selection; + const focusElement = focusNode.nodeType !== Node.ELEMENT_NODE ? focusNode.parentElement : focusNode; + const root = focusElement.closest(".textLayer"); + if (!root) { + return; + } + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + walker.currentNode = focusNode; + const focusRect = focusElement.getBoundingClientRect(); + let newLineElement = null; + const nodeIterator = (isUp ? walker.previousSibling : walker.nextSibling).bind(walker); + while (nodeIterator()) { + const element = walker.currentNode.parentElement; + if (!this.#isOnSameLine(focusRect, element.getBoundingClientRect())) { + newLineElement = element; + break; + } + } + if (!newLineElement) { + const node = this.#getNodeOnNextPage(root, isUp); + if (!node) { + return; + } + if (select) { + const lastNode = (isUp ? walker.firstChild() : walker.lastChild()) || focusNode; + selection.extend(lastNode, isUp ? 0 : lastNode.length); + const range = document.createRange(); + range.setStart(node, isUp ? node.length : 0); + range.setEnd(node, isUp ? node.length : 0); + selection.addRange(range); + return; + } + const [caretX] = this.#getCaretPosition(selection, isUp); + const { + parentElement + } = node; + this.#setCaretPosition(select, selection, parentElement, parentElement.getBoundingClientRect(), caretX); + return; + } + const [caretX, caretY] = this.#getCaretPosition(selection, isUp); + const newLineElementRect = newLineElement.getBoundingClientRect(); + if (this.#isUnderOver(newLineElementRect, caretX, caretY, isUp)) { + this.#setCaretPosition(select, selection, newLineElement, newLineElementRect, caretX); + return; + } + while (nodeIterator()) { + const element = walker.currentNode.parentElement; + const elementRect = element.getBoundingClientRect(); + if (!this.#isOnSameLine(newLineElementRect, elementRect)) { + break; + } + if (this.#isUnderOver(elementRect, caretX, caretY, isUp)) { + this.#setCaretPosition(select, selection, element, elementRect, caretX); + return; + } + } + this.#setCaretPosition(select, selection, newLineElement, newLineElementRect, caretX); + } +} + +;// ./web/download_manager.js + +function download(blobUrl, filename) { + const a = document.createElement("a"); + if (!a.click) { + throw new Error('DownloadManager: "a.click()" is not supported.'); + } + a.href = blobUrl; + a.target = "_parent"; + if ("download" in a) { + a.download = filename; + } + (document.body || document.documentElement).append(a); + a.click(); + a.remove(); +} +class DownloadManager { + #openBlobUrls = new WeakMap(); + downloadData(data, filename, contentType) { + const blobUrl = URL.createObjectURL(new Blob([data], { + type: contentType + })); + download(blobUrl, filename); + } + openOrDownloadData(data, filename, dest = null) { + const isPdfData = isPdfFile(filename); + const contentType = isPdfData ? "application/pdf" : ""; + if (isPdfData) { + let blobUrl = this.#openBlobUrls.get(data); + if (!blobUrl) { + blobUrl = URL.createObjectURL(new Blob([data], { + type: contentType + })); + this.#openBlobUrls.set(data, blobUrl); + } + let viewerUrl; + viewerUrl = "?file=" + encodeURIComponent(blobUrl + "#" + filename); + if (dest) { + viewerUrl += `#${escape(dest)}`; + } + try { + window.open(viewerUrl); + return true; + } catch (ex) { + console.error(`openOrDownloadData: ${ex}`); + URL.revokeObjectURL(blobUrl); + this.#openBlobUrls.delete(data); + } + } + this.downloadData(data, filename, contentType); + return false; + } + download(data, url, filename) { + let blobUrl; + if (data) { + blobUrl = URL.createObjectURL(new Blob([data], { + type: "application/pdf" + })); + } else { + if (!createValidAbsoluteUrl(url, "http://example.com")) { + console.error(`download - not a valid URL: ${url}`); + return; + } + blobUrl = url + "#pdfjs.action=download"; + } + download(blobUrl, filename); + } +} + +;// ./web/editor_undo_bar.js + +class EditorUndoBar { + #closeButton = null; + #container; + #eventBus = null; + #focusTimeout = null; + #initController = null; + isOpen = false; + #message; + #showController = null; + #undoButton; + static #l10nMessages = Object.freeze({ + highlight: "pdfjs-editor-undo-bar-message-highlight", + freetext: "pdfjs-editor-undo-bar-message-freetext", + stamp: "pdfjs-editor-undo-bar-message-stamp", + ink: "pdfjs-editor-undo-bar-message-ink", + _multiple: "pdfjs-editor-undo-bar-message-multiple" + }); + constructor({ + container, + message, + undoButton, + closeButton + }, eventBus) { + this.#container = container; + this.#message = message; + this.#undoButton = undoButton; + this.#closeButton = closeButton; + this.#eventBus = eventBus; + } + destroy() { + this.#initController?.abort(); + this.#initController = null; + this.hide(); + } + show(undoAction, messageData) { + if (!this.#initController) { + this.#initController = new AbortController(); + const opts = { + signal: this.#initController.signal + }; + const boundHide = this.hide.bind(this); + this.#container.addEventListener("contextmenu", noContextMenu, opts); + this.#closeButton.addEventListener("click", boundHide, opts); + this.#eventBus._on("beforeprint", boundHide, opts); + this.#eventBus._on("download", boundHide, opts); + } + this.hide(); + if (typeof messageData === "string") { + this.#message.setAttribute("data-l10n-id", EditorUndoBar.#l10nMessages[messageData]); + } else { + this.#message.setAttribute("data-l10n-id", EditorUndoBar.#l10nMessages._multiple); + this.#message.setAttribute("data-l10n-args", JSON.stringify({ + count: messageData + })); + } + this.isOpen = true; + this.#container.hidden = false; + this.#showController = new AbortController(); + this.#undoButton.addEventListener("click", () => { + undoAction(); + this.hide(); + }, { + signal: this.#showController.signal + }); + this.#focusTimeout = setTimeout(() => { + this.#container.focus(); + this.#focusTimeout = null; + }, 100); + } + hide() { + if (!this.isOpen) { + return; + } + this.isOpen = false; + this.#container.hidden = true; + this.#showController?.abort(); + this.#showController = null; + if (this.#focusTimeout) { + clearTimeout(this.#focusTimeout); + this.#focusTimeout = null; + } + } +} + +;// ./web/overlay_manager.js +class OverlayManager { + #overlays = new WeakMap(); + #active = null; + get active() { + return this.#active; + } + async register(dialog, canForceClose = false) { + if (typeof dialog !== "object") { + throw new Error("Not enough parameters."); + } else if (this.#overlays.has(dialog)) { + throw new Error("The overlay is already registered."); + } + this.#overlays.set(dialog, { + canForceClose + }); + dialog.addEventListener("cancel", evt => { + this.#active = null; + }); + } + async open(dialog) { + if (!this.#overlays.has(dialog)) { + throw new Error("The overlay does not exist."); + } else if (this.#active) { + if (this.#active === dialog) { + throw new Error("The overlay is already active."); + } else if (this.#overlays.get(dialog).canForceClose) { + await this.close(); + } else { + throw new Error("Another overlay is currently active."); + } + } + this.#active = dialog; + dialog.showModal(); + } + async close(dialog = this.#active) { + if (!this.#overlays.has(dialog)) { + throw new Error("The overlay does not exist."); + } else if (!this.#active) { + throw new Error("The overlay is currently not active."); + } else if (this.#active !== dialog) { + throw new Error("Another overlay is currently active."); + } + dialog.close(); + this.#active = null; + } +} + +;// ./web/password_prompt.js + +class PasswordPrompt { + #activeCapability = null; + #updateCallback = null; + #reason = null; + constructor(options, overlayManager, isViewerEmbedded = false) { + this.dialog = options.dialog; + this.label = options.label; + this.input = options.input; + this.submitButton = options.submitButton; + this.cancelButton = options.cancelButton; + this.overlayManager = overlayManager; + this._isViewerEmbedded = isViewerEmbedded; + this.submitButton.addEventListener("click", this.#verify.bind(this)); + this.cancelButton.addEventListener("click", this.close.bind(this)); + this.input.addEventListener("keydown", e => { + if (e.keyCode === 13) { + this.#verify(); + } + }); + this.overlayManager.register(this.dialog, true); + this.dialog.addEventListener("close", this.#cancel.bind(this)); + } + async open() { + await this.#activeCapability?.promise; + this.#activeCapability = Promise.withResolvers(); + try { + await this.overlayManager.open(this.dialog); + } catch (ex) { + this.#activeCapability.resolve(); + throw ex; + } + const passwordIncorrect = this.#reason === PasswordResponses.INCORRECT_PASSWORD; + if (!this._isViewerEmbedded || passwordIncorrect) { + this.input.focus(); + } + this.label.setAttribute("data-l10n-id", passwordIncorrect ? "pdfjs-password-invalid" : "pdfjs-password-label"); + } + async close() { + if (this.overlayManager.active === this.dialog) { + this.overlayManager.close(this.dialog); + } + } + #verify() { + const password = this.input.value; + if (password?.length > 0) { + this.#invokeCallback(password); + } + } + #cancel() { + this.#invokeCallback(new Error("PasswordPrompt cancelled.")); + this.#activeCapability.resolve(); + } + #invokeCallback(password) { + if (!this.#updateCallback) { + return; + } + this.close(); + this.input.value = ""; + this.#updateCallback(password); + this.#updateCallback = null; + } + async setUpdateCallback(updateCallback, reason) { + if (this.#activeCapability) { + await this.#activeCapability.promise; + } + this.#updateCallback = updateCallback; + this.#reason = reason; + } +} + +;// ./web/base_tree_viewer.js + +const TREEITEM_OFFSET_TOP = -100; +const TREEITEM_SELECTED_CLASS = "selected"; +class BaseTreeViewer { + constructor(options) { + this.container = options.container; + this.eventBus = options.eventBus; + this._l10n = options.l10n; + this.reset(); + } + reset() { + this._pdfDocument = null; + this._lastToggleIsShow = true; + this._currentTreeItem = null; + this.container.textContent = ""; + this.container.classList.remove("treeWithDeepNesting"); + } + _dispatchEvent(count) { + throw new Error("Not implemented: _dispatchEvent"); + } + _bindLink(element, params) { + throw new Error("Not implemented: _bindLink"); + } + _normalizeTextContent(str) { + return removeNullCharacters(str, true) || "\u2013"; + } + _addToggleButton(div, hidden = false) { + const toggler = document.createElement("div"); + toggler.className = "treeItemToggler"; + if (hidden) { + toggler.classList.add("treeItemsHidden"); + } + toggler.onclick = evt => { + evt.stopPropagation(); + toggler.classList.toggle("treeItemsHidden"); + if (evt.shiftKey) { + const shouldShowAll = !toggler.classList.contains("treeItemsHidden"); + this._toggleTreeItem(div, shouldShowAll); + } + }; + div.prepend(toggler); + } + _toggleTreeItem(root, show = false) { + this._l10n.pause(); + this._lastToggleIsShow = show; + for (const toggler of root.querySelectorAll(".treeItemToggler")) { + toggler.classList.toggle("treeItemsHidden", !show); + } + this._l10n.resume(); + } + _toggleAllTreeItems() { + this._toggleTreeItem(this.container, !this._lastToggleIsShow); + } + _finishRendering(fragment, count, hasAnyNesting = false) { + if (hasAnyNesting) { + this.container.classList.add("treeWithDeepNesting"); + this._lastToggleIsShow = !fragment.querySelector(".treeItemsHidden"); + } + this._l10n.pause(); + this.container.append(fragment); + this._l10n.resume(); + this._dispatchEvent(count); + } + render(params) { + throw new Error("Not implemented: render"); + } + _updateCurrentTreeItem(treeItem = null) { + if (this._currentTreeItem) { + this._currentTreeItem.classList.remove(TREEITEM_SELECTED_CLASS); + this._currentTreeItem = null; + } + if (treeItem) { + treeItem.classList.add(TREEITEM_SELECTED_CLASS); + this._currentTreeItem = treeItem; + } + } + _scrollToCurrentTreeItem(treeItem) { + if (!treeItem) { + return; + } + this._l10n.pause(); + let currentNode = treeItem.parentNode; + while (currentNode && currentNode !== this.container) { + if (currentNode.classList.contains("treeItem")) { + const toggler = currentNode.firstElementChild; + toggler?.classList.remove("treeItemsHidden"); + } + currentNode = currentNode.parentNode; + } + this._l10n.resume(); + this._updateCurrentTreeItem(treeItem); + this.container.scrollTo(treeItem.offsetLeft, treeItem.offsetTop + TREEITEM_OFFSET_TOP); + } +} + +;// ./web/pdf_attachment_viewer.js + + +class PDFAttachmentViewer extends BaseTreeViewer { + constructor(options) { + super(options); + this.downloadManager = options.downloadManager; + this.eventBus._on("fileattachmentannotation", this.#appendAttachment.bind(this)); + } + reset(keepRenderedCapability = false) { + super.reset(); + this._attachments = null; + if (!keepRenderedCapability) { + this._renderedCapability = Promise.withResolvers(); + } + this._pendingDispatchEvent = false; + } + async _dispatchEvent(attachmentsCount) { + this._renderedCapability.resolve(); + if (attachmentsCount === 0 && !this._pendingDispatchEvent) { + this._pendingDispatchEvent = true; + await waitOnEventOrTimeout({ + target: this.eventBus, + name: "annotationlayerrendered", + delay: 1000 + }); + if (!this._pendingDispatchEvent) { + return; + } + } + this._pendingDispatchEvent = false; + this.eventBus.dispatch("attachmentsloaded", { + source: this, + attachmentsCount + }); + } + _bindLink(element, { + content, + description, + filename + }) { + if (description) { + element.title = description; + } + element.onclick = () => { + this.downloadManager.openOrDownloadData(content, filename); + return false; + }; + } + render({ + attachments, + keepRenderedCapability = false + }) { + if (this._attachments) { + this.reset(keepRenderedCapability); + } + this._attachments = attachments || null; + if (!attachments) { + this._dispatchEvent(0); + return; + } + const fragment = document.createDocumentFragment(); + let attachmentsCount = 0; + for (const name in attachments) { + const item = attachments[name]; + const div = document.createElement("div"); + div.className = "treeItem"; + const element = document.createElement("a"); + this._bindLink(element, item); + element.textContent = this._normalizeTextContent(item.filename); + div.append(element); + fragment.append(div); + attachmentsCount++; + } + this._finishRendering(fragment, attachmentsCount); + } + #appendAttachment(item) { + const renderedPromise = this._renderedCapability.promise; + renderedPromise.then(() => { + if (renderedPromise !== this._renderedCapability.promise) { + return; + } + const attachments = this._attachments || Object.create(null); + for (const name in attachments) { + if (item.filename === name) { + return; + } + } + attachments[item.filename] = item; + this.render({ + attachments, + keepRenderedCapability: true + }); + }); + } +} + +;// ./web/grab_to_pan.js + +const CSS_CLASS_GRAB = "grab-to-pan-grab"; +class GrabToPan { + #activateAC = null; + #mouseDownAC = null; + #scrollAC = null; + constructor({ + element + }) { + this.element = element; + this.document = element.ownerDocument; + const overlay = this.overlay = document.createElement("div"); + overlay.className = "grab-to-pan-grabbing"; + } + activate() { + if (!this.#activateAC) { + this.#activateAC = new AbortController(); + this.element.addEventListener("mousedown", this.#onMouseDown.bind(this), { + capture: true, + signal: this.#activateAC.signal + }); + this.element.classList.add(CSS_CLASS_GRAB); + } + } + deactivate() { + if (this.#activateAC) { + this.#activateAC.abort(); + this.#activateAC = null; + this.#endPan(); + this.element.classList.remove(CSS_CLASS_GRAB); + } + } + toggle() { + if (this.#activateAC) { + this.deactivate(); + } else { + this.activate(); + } + } + ignoreTarget(node) { + return node.matches("a[href], a[href] *, input, textarea, button, button *, select, option"); + } + #onMouseDown(event) { + if (event.button !== 0 || this.ignoreTarget(event.target)) { + return; + } + if (event.originalTarget) { + try { + event.originalTarget.tagName; + } catch { + return; + } + } + this.scrollLeftStart = this.element.scrollLeft; + this.scrollTopStart = this.element.scrollTop; + this.clientXStart = event.clientX; + this.clientYStart = event.clientY; + this.#mouseDownAC = new AbortController(); + const boundEndPan = this.#endPan.bind(this), + mouseOpts = { + capture: true, + signal: this.#mouseDownAC.signal + }; + this.document.addEventListener("mousemove", this.#onMouseMove.bind(this), mouseOpts); + this.document.addEventListener("mouseup", boundEndPan, mouseOpts); + this.#scrollAC = new AbortController(); + this.element.addEventListener("scroll", boundEndPan, { + capture: true, + signal: this.#scrollAC.signal + }); + stopEvent(event); + const focusedElement = document.activeElement; + if (focusedElement && !focusedElement.contains(event.target)) { + focusedElement.blur(); + } + } + #onMouseMove(event) { + this.#scrollAC?.abort(); + this.#scrollAC = null; + if (!(event.buttons & 1)) { + this.#endPan(); + return; + } + const xDiff = event.clientX - this.clientXStart; + const yDiff = event.clientY - this.clientYStart; + this.element.scrollTo({ + top: this.scrollTopStart - yDiff, + left: this.scrollLeftStart - xDiff, + behavior: "instant" + }); + if (!this.overlay.parentNode) { + document.body.append(this.overlay); + } + } + #endPan() { + this.#mouseDownAC?.abort(); + this.#mouseDownAC = null; + this.#scrollAC?.abort(); + this.#scrollAC = null; + this.overlay.remove(); + } +} + +;// ./web/pdf_cursor_tools.js + + + +class PDFCursorTools { + #active = CursorTool.SELECT; + #prevActive = null; + constructor({ + container, + eventBus, + cursorToolOnLoad = CursorTool.SELECT + }) { + this.container = container; + this.eventBus = eventBus; + this.#addEventListeners(); + Promise.resolve().then(() => { + this.switchTool(cursorToolOnLoad); + }); + } + get activeTool() { + return this.#active; + } + switchTool(tool) { + if (this.#prevActive !== null) { + return; + } + this.#switchTool(tool); + } + #switchTool(tool, disabled = false) { + if (tool === this.#active) { + if (this.#prevActive !== null) { + this.eventBus.dispatch("cursortoolchanged", { + source: this, + tool, + disabled + }); + } + return; + } + const disableActiveTool = () => { + switch (this.#active) { + case CursorTool.SELECT: + break; + case CursorTool.HAND: + this._handTool.deactivate(); + break; + case CursorTool.ZOOM: + } + }; + switch (tool) { + case CursorTool.SELECT: + disableActiveTool(); + break; + case CursorTool.HAND: + disableActiveTool(); + this._handTool.activate(); + break; + case CursorTool.ZOOM: + default: + console.error(`switchTool: "${tool}" is an unsupported value.`); + return; + } + this.#active = tool; + this.eventBus.dispatch("cursortoolchanged", { + source: this, + tool, + disabled + }); + } + #addEventListeners() { + this.eventBus._on("switchcursortool", evt => { + if (!evt.reset) { + this.switchTool(evt.tool); + } else if (this.#prevActive !== null) { + annotationEditorMode = AnnotationEditorType.NONE; + presentationModeState = PresentationModeState.NORMAL; + enableActive(); + } + }); + let annotationEditorMode = AnnotationEditorType.NONE, + presentationModeState = PresentationModeState.NORMAL; + const disableActive = () => { + this.#prevActive ??= this.#active; + this.#switchTool(CursorTool.SELECT, true); + }; + const enableActive = () => { + if (this.#prevActive !== null && annotationEditorMode === AnnotationEditorType.NONE && presentationModeState === PresentationModeState.NORMAL) { + this.#switchTool(this.#prevActive); + this.#prevActive = null; + } + }; + this.eventBus._on("annotationeditormodechanged", ({ + mode + }) => { + annotationEditorMode = mode; + if (mode === AnnotationEditorType.NONE) { + enableActive(); + } else { + disableActive(); + } + }); + this.eventBus._on("presentationmodechanged", ({ + state + }) => { + presentationModeState = state; + if (state === PresentationModeState.NORMAL) { + enableActive(); + } else if (state === PresentationModeState.FULLSCREEN) { + disableActive(); + } + }); + } + get _handTool() { + return shadow(this, "_handTool", new GrabToPan({ + element: this.container + })); + } +} + +;// ./web/pdf_document_properties.js + + +const NON_METRIC_LOCALES = ["en-us", "en-lr", "my"]; +const US_PAGE_NAMES = { + "8.5x11": "pdfjs-document-properties-page-size-name-letter", + "8.5x14": "pdfjs-document-properties-page-size-name-legal" +}; +const METRIC_PAGE_NAMES = { + "297x420": "pdfjs-document-properties-page-size-name-a-three", + "210x297": "pdfjs-document-properties-page-size-name-a-four" +}; +function getPageName(size, isPortrait, pageNames) { + const width = isPortrait ? size.width : size.height; + const height = isPortrait ? size.height : size.width; + return pageNames[`${width}x${height}`]; +} +class PDFDocumentProperties { + #fieldData = null; + constructor({ + dialog, + fields, + closeButton + }, overlayManager, eventBus, l10n, fileNameLookup) { + this.dialog = dialog; + this.fields = fields; + this.overlayManager = overlayManager; + this.l10n = l10n; + this._fileNameLookup = fileNameLookup; + this.#reset(); + closeButton.addEventListener("click", this.close.bind(this)); + this.overlayManager.register(this.dialog); + eventBus._on("pagechanging", evt => { + this._currentPageNumber = evt.pageNumber; + }); + eventBus._on("rotationchanging", evt => { + this._pagesRotation = evt.pagesRotation; + }); + } + async open() { + await Promise.all([this.overlayManager.open(this.dialog), this._dataAvailableCapability.promise]); + const currentPageNumber = this._currentPageNumber; + const pagesRotation = this._pagesRotation; + if (this.#fieldData && currentPageNumber === this.#fieldData._currentPageNumber && pagesRotation === this.#fieldData._pagesRotation) { + this.#updateUI(); + return; + } + const [{ + info, + contentLength + }, pdfPage] = await Promise.all([this.pdfDocument.getMetadata(), this.pdfDocument.getPage(currentPageNumber)]); + const [fileName, fileSize, creationDate, modificationDate, pageSize, isLinearized] = await Promise.all([this._fileNameLookup(), this.#parseFileSize(contentLength), this.#parseDate(info.CreationDate), this.#parseDate(info.ModDate), this.#parsePageSize(getPageSizeInches(pdfPage), pagesRotation), this.#parseLinearization(info.IsLinearized)]); + this.#fieldData = Object.freeze({ + fileName, + fileSize, + title: info.Title, + author: info.Author, + subject: info.Subject, + keywords: info.Keywords, + creationDate, + modificationDate, + creator: info.Creator, + producer: info.Producer, + version: info.PDFFormatVersion, + pageCount: this.pdfDocument.numPages, + pageSize, + linearized: isLinearized, + _currentPageNumber: currentPageNumber, + _pagesRotation: pagesRotation + }); + this.#updateUI(); + const { + length + } = await this.pdfDocument.getDownloadInfo(); + if (contentLength === length) { + return; + } + const data = Object.assign(Object.create(null), this.#fieldData); + data.fileSize = await this.#parseFileSize(length); + this.#fieldData = Object.freeze(data); + this.#updateUI(); + } + async close() { + this.overlayManager.close(this.dialog); + } + setDocument(pdfDocument) { + if (this.pdfDocument) { + this.#reset(); + this.#updateUI(); + } + if (!pdfDocument) { + return; + } + this.pdfDocument = pdfDocument; + this._dataAvailableCapability.resolve(); + } + #reset() { + this.pdfDocument = null; + this.#fieldData = null; + this._dataAvailableCapability = Promise.withResolvers(); + this._currentPageNumber = 1; + this._pagesRotation = 0; + } + #updateUI() { + if (this.#fieldData && this.overlayManager.active !== this.dialog) { + return; + } + for (const id in this.fields) { + const content = this.#fieldData?.[id]; + this.fields[id].textContent = content || content === 0 ? content : "-"; + } + } + async #parseFileSize(b = 0) { + const kb = b / 1024, + mb = kb / 1024; + return kb ? this.l10n.get(mb >= 1 ? "pdfjs-document-properties-size-mb" : "pdfjs-document-properties-size-kb", { + mb, + kb, + b + }) : undefined; + } + async #parsePageSize(pageSizeInches, pagesRotation) { + if (!pageSizeInches) { + return undefined; + } + if (pagesRotation % 180 !== 0) { + pageSizeInches = { + width: pageSizeInches.height, + height: pageSizeInches.width + }; + } + const isPortrait = isPortraitOrientation(pageSizeInches), + nonMetric = NON_METRIC_LOCALES.includes(this.l10n.getLanguage()); + let sizeInches = { + width: Math.round(pageSizeInches.width * 100) / 100, + height: Math.round(pageSizeInches.height * 100) / 100 + }; + let sizeMillimeters = { + width: Math.round(pageSizeInches.width * 25.4 * 10) / 10, + height: Math.round(pageSizeInches.height * 25.4 * 10) / 10 + }; + let nameId = getPageName(sizeInches, isPortrait, US_PAGE_NAMES) || getPageName(sizeMillimeters, isPortrait, METRIC_PAGE_NAMES); + if (!nameId && !(Number.isInteger(sizeMillimeters.width) && Number.isInteger(sizeMillimeters.height))) { + const exactMillimeters = { + width: pageSizeInches.width * 25.4, + height: pageSizeInches.height * 25.4 + }; + const intMillimeters = { + width: Math.round(sizeMillimeters.width), + height: Math.round(sizeMillimeters.height) + }; + if (Math.abs(exactMillimeters.width - intMillimeters.width) < 0.1 && Math.abs(exactMillimeters.height - intMillimeters.height) < 0.1) { + nameId = getPageName(intMillimeters, isPortrait, METRIC_PAGE_NAMES); + if (nameId) { + sizeInches = { + width: Math.round(intMillimeters.width / 25.4 * 100) / 100, + height: Math.round(intMillimeters.height / 25.4 * 100) / 100 + }; + sizeMillimeters = intMillimeters; + } + } + } + const [{ + width, + height + }, unit, name, orientation] = await Promise.all([nonMetric ? sizeInches : sizeMillimeters, this.l10n.get(nonMetric ? "pdfjs-document-properties-page-size-unit-inches" : "pdfjs-document-properties-page-size-unit-millimeters"), nameId && this.l10n.get(nameId), this.l10n.get(isPortrait ? "pdfjs-document-properties-page-size-orientation-portrait" : "pdfjs-document-properties-page-size-orientation-landscape")]); + return this.l10n.get(name ? "pdfjs-document-properties-page-size-dimension-name-string" : "pdfjs-document-properties-page-size-dimension-string", { + width, + height, + unit, + name, + orientation + }); + } + async #parseDate(inputDate) { + const dateObj = PDFDateString.toDateObject(inputDate); + return dateObj ? this.l10n.get("pdfjs-document-properties-date-time-string", { + dateObj: dateObj.valueOf() + }) : undefined; + } + #parseLinearization(isLinearized) { + return this.l10n.get(isLinearized ? "pdfjs-document-properties-linearized-yes" : "pdfjs-document-properties-linearized-no"); + } +} + +;// ./web/pdf_find_utils.js +const CharacterType = { + SPACE: 0, + ALPHA_LETTER: 1, + PUNCT: 2, + HAN_LETTER: 3, + KATAKANA_LETTER: 4, + HIRAGANA_LETTER: 5, + HALFWIDTH_KATAKANA_LETTER: 6, + THAI_LETTER: 7 +}; +function isAlphabeticalScript(charCode) { + return charCode < 0x2e80; +} +function isAscii(charCode) { + return (charCode & 0xff80) === 0; +} +function isAsciiAlpha(charCode) { + return charCode >= 0x61 && charCode <= 0x7a || charCode >= 0x41 && charCode <= 0x5a; +} +function isAsciiDigit(charCode) { + return charCode >= 0x30 && charCode <= 0x39; +} +function isAsciiSpace(charCode) { + return charCode === 0x20 || charCode === 0x09 || charCode === 0x0d || charCode === 0x0a; +} +function isHan(charCode) { + return charCode >= 0x3400 && charCode <= 0x9fff || charCode >= 0xf900 && charCode <= 0xfaff; +} +function isKatakana(charCode) { + return charCode >= 0x30a0 && charCode <= 0x30ff; +} +function isHiragana(charCode) { + return charCode >= 0x3040 && charCode <= 0x309f; +} +function isHalfwidthKatakana(charCode) { + return charCode >= 0xff60 && charCode <= 0xff9f; +} +function isThai(charCode) { + return (charCode & 0xff80) === 0x0e00; +} +function getCharacterType(charCode) { + if (isAlphabeticalScript(charCode)) { + if (isAscii(charCode)) { + if (isAsciiSpace(charCode)) { + return CharacterType.SPACE; + } else if (isAsciiAlpha(charCode) || isAsciiDigit(charCode) || charCode === 0x5f) { + return CharacterType.ALPHA_LETTER; + } + return CharacterType.PUNCT; + } else if (isThai(charCode)) { + return CharacterType.THAI_LETTER; + } else if (charCode === 0xa0) { + return CharacterType.SPACE; + } + return CharacterType.ALPHA_LETTER; + } + if (isHan(charCode)) { + return CharacterType.HAN_LETTER; + } else if (isKatakana(charCode)) { + return CharacterType.KATAKANA_LETTER; + } else if (isHiragana(charCode)) { + return CharacterType.HIRAGANA_LETTER; + } else if (isHalfwidthKatakana(charCode)) { + return CharacterType.HALFWIDTH_KATAKANA_LETTER; + } + return CharacterType.ALPHA_LETTER; +} +let NormalizeWithNFKC; +function getNormalizeWithNFKC() { + NormalizeWithNFKC ||= ` ¨ª¯²-µ¸-º¼-¾IJ-ijĿ-ŀʼnſDŽ-njDZ-dzʰ-ʸ˘-˝ˠ-ˤʹͺ;΄-΅·ϐ-ϖϰ-ϲϴ-ϵϹևٵ-ٸक़-य़ড়-ঢ়য়ਲ਼ਸ਼ਖ਼-ਜ਼ਫ਼ଡ଼-ଢ଼ำຳໜ-ໝ༌གྷཌྷདྷབྷཛྷཀྵჼᴬ-ᴮᴰ-ᴺᴼ-ᵍᵏ-ᵪᵸᶛ-ᶿẚ-ẛάέήίόύώΆ᾽-῁ΈΉ῍-῏ΐΊ῝-῟ΰΎ῭-`ΌΏ´-῾ - ‑‗․-… ″-‴‶-‷‼‾⁇-⁉⁗ ⁰-ⁱ⁴-₎ₐ-ₜ₨℀-℃℅-ℇ℉-ℓℕ-№ℙ-ℝ℠-™ℤΩℨK-ℭℯ-ℱℳ-ℹ℻-⅀ⅅ-ⅉ⅐-ⅿ↉∬-∭∯-∰〈-〉①-⓪⨌⩴-⩶⫝̸ⱼ-ⱽⵯ⺟⻳⼀-⿕ 〶〸-〺゛-゜ゟヿㄱ-ㆎ㆒-㆟㈀-㈞㈠-㉇㉐-㉾㊀-㏿ꚜ-ꚝꝰꟲ-ꟴꟸ-ꟹꭜ-ꭟꭩ豈-嗀塚晴凞-羽蘒諸逸-都飯-舘並-龎ff-stﬓ-ﬗיִײַ-זּטּ-לּמּנּ-סּףּ-פּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-﷼︐-︙︰-﹄﹇-﹒﹔-﹦﹨-﹫ﹰ-ﹲﹴﹶ-ﻼ!-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ¢-₩`; + return NormalizeWithNFKC; +} + +;// ./web/pdf_find_controller.js + + +const FindState = { + FOUND: 0, + NOT_FOUND: 1, + WRAPPED: 2, + PENDING: 3 +}; +const FIND_TIMEOUT = 250; +const MATCH_SCROLL_OFFSET_TOP = -50; +const MATCH_SCROLL_OFFSET_LEFT = -400; +const CHARACTERS_TO_NORMALIZE = { + "\u2010": "-", + "\u2018": "'", + "\u2019": "'", + "\u201A": "'", + "\u201B": "'", + "\u201C": '"', + "\u201D": '"', + "\u201E": '"', + "\u201F": '"', + "\u00BC": "1/4", + "\u00BD": "1/2", + "\u00BE": "3/4" +}; +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]); +let DIACRITICS_EXCEPTION_STR; +const DIACRITICS_REG_EXP = /\p{M}+/gu; +const SPECIAL_CHARS_REG_EXP = /([.*+?^${}()|[\]\\])|(\p{P})|(\s+)|(\p{M})|(\p{L})/gu; +const NOT_DIACRITIC_FROM_END_REG_EXP = /([^\p{M}])\p{M}*$/u; +const NOT_DIACRITIC_FROM_START_REG_EXP = /^\p{M}*([^\p{M}])/u; +const SYLLABLES_REG_EXP = /[\uAC00-\uD7AF\uFA6C\uFACF-\uFAD1\uFAD5-\uFAD7]+/g; +const SYLLABLES_LENGTHS = new Map(); +const FIRST_CHAR_SYLLABLES_REG_EXP = "[\\u1100-\\u1112\\ud7a4-\\ud7af\\ud84a\\ud84c\\ud850\\ud854\\ud857\\ud85f]"; +const NFKC_CHARS_TO_NORMALIZE = new Map(); +let noSyllablesRegExp = null; +let withSyllablesRegExp = null; +function normalize(text) { + const syllablePositions = []; + let m; + while ((m = SYLLABLES_REG_EXP.exec(text)) !== null) { + let { + index + } = m; + for (const char of m[0]) { + let len = SYLLABLES_LENGTHS.get(char); + if (!len) { + len = char.normalize("NFD").length; + SYLLABLES_LENGTHS.set(char, len); + } + syllablePositions.push([len, index++]); + } + } + let normalizationRegex; + if (syllablePositions.length === 0 && noSyllablesRegExp) { + normalizationRegex = noSyllablesRegExp; + } else if (syllablePositions.length > 0 && withSyllablesRegExp) { + normalizationRegex = withSyllablesRegExp; + } else { + const replace = Object.keys(CHARACTERS_TO_NORMALIZE).join(""); + const toNormalizeWithNFKC = getNormalizeWithNFKC(); + const CJK = "(?:\\p{Ideographic}|[\u3040-\u30FF])"; + const HKDiacritics = "(?:\u3099|\u309A)"; + const CompoundWord = "\\p{Ll}-\\n\\p{Lu}"; + const regexp = `([${replace}])|([${toNormalizeWithNFKC}])|(${HKDiacritics}\\n)|(\\p{M}+(?:-\\n)?)|(${CompoundWord})|(\\S-\\n)|(${CJK}\\n)|(\\n)`; + if (syllablePositions.length === 0) { + normalizationRegex = noSyllablesRegExp = new RegExp(regexp + "|(\\u0000)", "gum"); + } else { + normalizationRegex = withSyllablesRegExp = new RegExp(regexp + `|(${FIRST_CHAR_SYLLABLES_REG_EXP})`, "gum"); + } + } + const rawDiacriticsPositions = []; + while ((m = DIACRITICS_REG_EXP.exec(text)) !== null) { + rawDiacriticsPositions.push([m[0].length, m.index]); + } + let normalized = text.normalize("NFD"); + const positions = [0, 0]; + let rawDiacriticsIndex = 0; + let syllableIndex = 0; + let shift = 0; + let shiftOrigin = 0; + let eol = 0; + let hasDiacritics = false; + normalized = normalized.replace(normalizationRegex, (match, p1, p2, p3, p4, p5, p6, p7, p8, p9, i) => { + i -= shiftOrigin; + if (p1) { + const replacement = CHARACTERS_TO_NORMALIZE[p1]; + const jj = replacement.length; + for (let j = 1; j < jj; j++) { + positions.push(i - shift + j, shift - j); + } + shift -= jj - 1; + return replacement; + } + if (p2) { + let replacement = NFKC_CHARS_TO_NORMALIZE.get(p2); + if (!replacement) { + replacement = p2.normalize("NFKC"); + NFKC_CHARS_TO_NORMALIZE.set(p2, replacement); + } + const jj = replacement.length; + for (let j = 1; j < jj; j++) { + positions.push(i - shift + j, shift - j); + } + shift -= jj - 1; + return replacement; + } + if (p3) { + hasDiacritics = true; + if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) { + ++rawDiacriticsIndex; + } else { + positions.push(i - 1 - shift + 1, shift - 1); + shift -= 1; + shiftOrigin += 1; + } + positions.push(i - shift + 1, shift); + shiftOrigin += 1; + eol += 1; + return p3.charAt(0); + } + if (p4) { + const hasTrailingDashEOL = p4.endsWith("\n"); + const len = hasTrailingDashEOL ? p4.length - 2 : p4.length; + hasDiacritics = true; + let jj = len; + if (i + eol === rawDiacriticsPositions[rawDiacriticsIndex]?.[1]) { + jj -= rawDiacriticsPositions[rawDiacriticsIndex][0]; + ++rawDiacriticsIndex; + } + for (let j = 1; j <= jj; j++) { + positions.push(i - 1 - shift + j, shift - j); + } + shift -= jj; + shiftOrigin += jj; + if (hasTrailingDashEOL) { + i += len - 1; + positions.push(i - shift + 1, 1 + shift); + shift += 1; + shiftOrigin += 1; + eol += 1; + return p4.slice(0, len); + } + return p4; + } + if (p5) { + shiftOrigin += 1; + eol += 1; + return p5.replace("\n", ""); + } + if (p6) { + const len = p6.length - 2; + positions.push(i - shift + len, 1 + shift); + shift += 1; + shiftOrigin += 1; + eol += 1; + return p6.slice(0, -2); + } + if (p7) { + const len = p7.length - 1; + positions.push(i - shift + len, shift); + shiftOrigin += 1; + eol += 1; + return p7.slice(0, -1); + } + if (p8) { + positions.push(i - shift + 1, shift - 1); + shift -= 1; + shiftOrigin += 1; + eol += 1; + return " "; + } + if (i + eol === syllablePositions[syllableIndex]?.[1]) { + const newCharLen = syllablePositions[syllableIndex][0] - 1; + ++syllableIndex; + for (let j = 1; j <= newCharLen; j++) { + positions.push(i - (shift - j), shift - j); + } + shift -= newCharLen; + shiftOrigin += newCharLen; + } + return p9; + }); + positions.push(normalized.length, shift); + const starts = new Uint32Array(positions.length >> 1); + const shifts = new Int32Array(positions.length >> 1); + for (let i = 0, ii = positions.length; i < ii; i += 2) { + starts[i >> 1] = positions[i]; + shifts[i >> 1] = positions[i + 1]; + } + return [normalized, [starts, shifts], hasDiacritics]; +} +function getOriginalIndex(diffs, pos, len) { + if (!diffs) { + return [pos, len]; + } + const [starts, shifts] = diffs; + const start = pos; + const end = pos + len - 1; + let i = binarySearchFirstItem(starts, x => x >= start); + if (starts[i] > start) { + --i; + } + let j = binarySearchFirstItem(starts, x => x >= end, i); + if (starts[j] > end) { + --j; + } + const oldStart = start + shifts[i]; + const oldEnd = end + shifts[j]; + const oldLen = oldEnd + 1 - oldStart; + return [oldStart, oldLen]; +} +class PDFFindController { + #state = null; + #updateMatchesCountOnProgress = true; + #visitedPagesCount = 0; + constructor({ + linkService, + eventBus, + updateMatchesCountOnProgress = true + }) { + this._linkService = linkService; + this._eventBus = eventBus; + this.#updateMatchesCountOnProgress = updateMatchesCountOnProgress; + this.onIsPageVisible = null; + this.#reset(); + eventBus._on("find", this.#onFind.bind(this)); + eventBus._on("findbarclose", this.#onFindBarClose.bind(this)); + } + get highlightMatches() { + return this._highlightMatches; + } + get pageMatches() { + return this._pageMatches; + } + get pageMatchesLength() { + return this._pageMatchesLength; + } + get selected() { + return this._selected; + } + get state() { + return this.#state; + } + setDocument(pdfDocument) { + if (this._pdfDocument) { + this.#reset(); + } + if (!pdfDocument) { + return; + } + this._pdfDocument = pdfDocument; + this._firstPageCapability.resolve(); + } + #onFind(state) { + if (!state) { + return; + } + const pdfDocument = this._pdfDocument; + const { + type + } = state; + if (this.#state === null || this.#shouldDirtyMatch(state)) { + this._dirtyMatch = true; + } + this.#state = state; + if (type !== "highlightallchange") { + this.#updateUIState(FindState.PENDING); + } + this._firstPageCapability.promise.then(() => { + if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { + return; + } + this.#extractText(); + const findbarClosed = !this._highlightMatches; + const pendingTimeout = !!this._findTimeout; + if (this._findTimeout) { + clearTimeout(this._findTimeout); + this._findTimeout = null; + } + if (!type) { + this._findTimeout = setTimeout(() => { + this.#nextMatch(); + this._findTimeout = null; + }, FIND_TIMEOUT); + } else if (this._dirtyMatch) { + this.#nextMatch(); + } else if (type === "again") { + this.#nextMatch(); + if (findbarClosed && this.#state.highlightAll) { + this.#updateAllPages(); + } + } else if (type === "highlightallchange") { + if (pendingTimeout) { + this.#nextMatch(); + } else { + this._highlightMatches = true; + } + this.#updateAllPages(); + } else { + this.#nextMatch(); + } + }); + } + scrollMatchIntoView({ + element = null, + selectedLeft = 0, + pageIndex = -1, + matchIndex = -1 + }) { + if (!this._scrollMatches || !element) { + return; + } else if (matchIndex === -1 || matchIndex !== this._selected.matchIdx) { + return; + } else if (pageIndex === -1 || pageIndex !== this._selected.pageIdx) { + return; + } + this._scrollMatches = false; + const spot = { + top: MATCH_SCROLL_OFFSET_TOP, + left: selectedLeft + MATCH_SCROLL_OFFSET_LEFT + }; + scrollIntoView(element, spot, true); + } + #reset() { + this._highlightMatches = false; + this._scrollMatches = false; + this._pdfDocument = null; + this._pageMatches = []; + this._pageMatchesLength = []; + this.#visitedPagesCount = 0; + this.#state = null; + this._selected = { + pageIdx: -1, + matchIdx: -1 + }; + this._offset = { + pageIdx: null, + matchIdx: null, + wrapped: false + }; + this._extractTextPromises = []; + this._pageContents = []; + this._pageDiffs = []; + this._hasDiacritics = []; + this._matchesCountTotal = 0; + this._pagesToSearch = null; + this._pendingFindMatches = new Set(); + this._resumePageIdx = null; + this._dirtyMatch = false; + clearTimeout(this._findTimeout); + this._findTimeout = null; + this._firstPageCapability = Promise.withResolvers(); + } + get #query() { + const { + query + } = this.#state; + if (typeof query === "string") { + if (query !== this._rawQuery) { + this._rawQuery = query; + [this._normalizedQuery] = normalize(query); + } + return this._normalizedQuery; + } + return (query || []).filter(q => !!q).map(q => normalize(q)[0]); + } + #shouldDirtyMatch(state) { + const newQuery = state.query, + prevQuery = this.#state.query; + const newType = typeof newQuery, + prevType = typeof prevQuery; + if (newType !== prevType) { + return true; + } + if (newType === "string") { + if (newQuery !== prevQuery) { + return true; + } + } else if (JSON.stringify(newQuery) !== JSON.stringify(prevQuery)) { + return true; + } + switch (state.type) { + case "again": + const pageNumber = this._selected.pageIdx + 1; + const linkService = this._linkService; + return pageNumber >= 1 && pageNumber <= linkService.pagesCount && pageNumber !== linkService.page && !(this.onIsPageVisible?.(pageNumber) ?? true); + case "highlightallchange": + return false; + } + return true; + } + #isEntireWord(content, startIdx, length) { + let match = content.slice(0, startIdx).match(NOT_DIACRITIC_FROM_END_REG_EXP); + if (match) { + const first = content.charCodeAt(startIdx); + const limit = match[1].charCodeAt(0); + if (getCharacterType(first) === getCharacterType(limit)) { + return false; + } + } + match = content.slice(startIdx + length).match(NOT_DIACRITIC_FROM_START_REG_EXP); + if (match) { + const last = content.charCodeAt(startIdx + length - 1); + const limit = match[1].charCodeAt(0); + if (getCharacterType(last) === getCharacterType(limit)) { + return false; + } + } + return true; + } + #convertToRegExpString(query, hasDiacritics) { + const { + matchDiacritics + } = this.#state; + let isUnicode = false; + query = query.replaceAll(SPECIAL_CHARS_REG_EXP, (match, p1, p2, p3, p4, p5) => { + if (p1) { + return `[ ]*\\${p1}[ ]*`; + } + if (p2) { + return `[ ]*${p2}[ ]*`; + } + if (p3) { + return "[ ]+"; + } + if (matchDiacritics) { + return p4 || p5; + } + if (p4) { + return DIACRITICS_EXCEPTION.has(p4.charCodeAt(0)) ? p4 : ""; + } + if (hasDiacritics) { + isUnicode = true; + return `${p5}\\p{M}*`; + } + return p5; + }); + const trailingSpaces = "[ ]*"; + if (query.endsWith(trailingSpaces)) { + query = query.slice(0, query.length - trailingSpaces.length); + } + if (matchDiacritics) { + if (hasDiacritics) { + DIACRITICS_EXCEPTION_STR ||= String.fromCharCode(...DIACRITICS_EXCEPTION); + isUnicode = true; + query = `${query}(?=[${DIACRITICS_EXCEPTION_STR}]|[^\\p{M}]|$)`; + } + } + return [isUnicode, query]; + } + #calculateMatch(pageIndex) { + const query = this.#query; + if (query.length === 0) { + return; + } + const pageContent = this._pageContents[pageIndex]; + const matcherResult = this.match(query, pageContent, pageIndex); + const matches = this._pageMatches[pageIndex] = []; + const matchesLength = this._pageMatchesLength[pageIndex] = []; + const diffs = this._pageDiffs[pageIndex]; + matcherResult?.forEach(({ + index, + length + }) => { + const [matchPos, matchLen] = getOriginalIndex(diffs, index, length); + if (matchLen) { + matches.push(matchPos); + matchesLength.push(matchLen); + } + }); + if (this.#state.highlightAll) { + this.#updatePage(pageIndex); + } + if (this._resumePageIdx === pageIndex) { + this._resumePageIdx = null; + this.#nextPageMatch(); + } + const pageMatchesCount = matches.length; + this._matchesCountTotal += pageMatchesCount; + if (this.#updateMatchesCountOnProgress) { + if (pageMatchesCount > 0) { + this.#updateUIResultsCount(); + } + } else if (++this.#visitedPagesCount === this._linkService.pagesCount) { + this.#updateUIResultsCount(); + } + } + match(query, pageContent, pageIndex) { + const hasDiacritics = this._hasDiacritics[pageIndex]; + let isUnicode = false; + if (typeof query === "string") { + [isUnicode, query] = this.#convertToRegExpString(query, hasDiacritics); + } else { + query = query.sort().reverse().map(q => { + const [isUnicodePart, queryPart] = this.#convertToRegExpString(q, hasDiacritics); + isUnicode ||= isUnicodePart; + return `(${queryPart})`; + }).join("|"); + } + if (!query) { + return undefined; + } + const { + caseSensitive, + entireWord + } = this.#state; + const flags = `g${isUnicode ? "u" : ""}${caseSensitive ? "" : "i"}`; + query = new RegExp(query, flags); + const matches = []; + let match; + while ((match = query.exec(pageContent)) !== null) { + if (entireWord && !this.#isEntireWord(pageContent, match.index, match[0].length)) { + continue; + } + matches.push({ + index: match.index, + length: match[0].length + }); + } + return matches; + } + #extractText() { + if (this._extractTextPromises.length > 0) { + return; + } + let deferred = Promise.resolve(); + const textOptions = { + disableNormalization: true + }; + for (let i = 0, ii = this._linkService.pagesCount; i < ii; i++) { + const { + promise, + resolve + } = Promise.withResolvers(); + this._extractTextPromises[i] = promise; + deferred = deferred.then(() => { + return this._pdfDocument.getPage(i + 1).then(pdfPage => pdfPage.getTextContent(textOptions)).then(textContent => { + const strBuf = []; + for (const textItem of textContent.items) { + strBuf.push(textItem.str); + if (textItem.hasEOL) { + strBuf.push("\n"); + } + } + [this._pageContents[i], this._pageDiffs[i], this._hasDiacritics[i]] = normalize(strBuf.join("")); + resolve(); + }, reason => { + console.error(`Unable to get text content for page ${i + 1}`, reason); + this._pageContents[i] = ""; + this._pageDiffs[i] = null; + this._hasDiacritics[i] = false; + resolve(); + }); + }); + } + } + #updatePage(index) { + if (this._scrollMatches && this._selected.pageIdx === index) { + this._linkService.page = index + 1; + } + this._eventBus.dispatch("updatetextlayermatches", { + source: this, + pageIndex: index + }); + } + #updateAllPages() { + this._eventBus.dispatch("updatetextlayermatches", { + source: this, + pageIndex: -1 + }); + } + #nextMatch() { + const previous = this.#state.findPrevious; + const currentPageIndex = this._linkService.page - 1; + const numPages = this._linkService.pagesCount; + this._highlightMatches = true; + if (this._dirtyMatch) { + this._dirtyMatch = false; + this._selected.pageIdx = this._selected.matchIdx = -1; + this._offset.pageIdx = currentPageIndex; + this._offset.matchIdx = null; + this._offset.wrapped = false; + this._resumePageIdx = null; + this._pageMatches.length = 0; + this._pageMatchesLength.length = 0; + this.#visitedPagesCount = 0; + this._matchesCountTotal = 0; + this.#updateAllPages(); + for (let i = 0; i < numPages; i++) { + if (this._pendingFindMatches.has(i)) { + continue; + } + this._pendingFindMatches.add(i); + this._extractTextPromises[i].then(() => { + this._pendingFindMatches.delete(i); + this.#calculateMatch(i); + }); + } + } + const query = this.#query; + if (query.length === 0) { + this.#updateUIState(FindState.FOUND); + return; + } + if (this._resumePageIdx) { + return; + } + const offset = this._offset; + this._pagesToSearch = numPages; + if (offset.matchIdx !== null) { + const numPageMatches = this._pageMatches[offset.pageIdx].length; + if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) { + offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1; + this.#updateMatch(true); + return; + } + this.#advanceOffsetPage(previous); + } + this.#nextPageMatch(); + } + #matchesReady(matches) { + const offset = this._offset; + const numMatches = matches.length; + const previous = this.#state.findPrevious; + if (numMatches) { + offset.matchIdx = previous ? numMatches - 1 : 0; + this.#updateMatch(true); + return true; + } + this.#advanceOffsetPage(previous); + if (offset.wrapped) { + offset.matchIdx = null; + if (this._pagesToSearch < 0) { + this.#updateMatch(false); + return true; + } + } + return false; + } + #nextPageMatch() { + if (this._resumePageIdx !== null) { + console.error("There can only be one pending page."); + } + let matches = null; + do { + const pageIdx = this._offset.pageIdx; + matches = this._pageMatches[pageIdx]; + if (!matches) { + this._resumePageIdx = pageIdx; + break; + } + } while (!this.#matchesReady(matches)); + } + #advanceOffsetPage(previous) { + const offset = this._offset; + const numPages = this._linkService.pagesCount; + offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1; + offset.matchIdx = null; + this._pagesToSearch--; + if (offset.pageIdx >= numPages || offset.pageIdx < 0) { + offset.pageIdx = previous ? numPages - 1 : 0; + offset.wrapped = true; + } + } + #updateMatch(found = false) { + let state = FindState.NOT_FOUND; + const wrapped = this._offset.wrapped; + this._offset.wrapped = false; + if (found) { + const previousPage = this._selected.pageIdx; + this._selected.pageIdx = this._offset.pageIdx; + this._selected.matchIdx = this._offset.matchIdx; + state = wrapped ? FindState.WRAPPED : FindState.FOUND; + if (previousPage !== -1 && previousPage !== this._selected.pageIdx) { + this.#updatePage(previousPage); + } + } + this.#updateUIState(state, this.#state.findPrevious); + if (this._selected.pageIdx !== -1) { + this._scrollMatches = true; + this.#updatePage(this._selected.pageIdx); + } + } + #onFindBarClose(evt) { + const pdfDocument = this._pdfDocument; + this._firstPageCapability.promise.then(() => { + if (!this._pdfDocument || pdfDocument && this._pdfDocument !== pdfDocument) { + return; + } + if (this._findTimeout) { + clearTimeout(this._findTimeout); + this._findTimeout = null; + } + if (this._resumePageIdx) { + this._resumePageIdx = null; + this._dirtyMatch = true; + } + this.#updateUIState(FindState.FOUND); + this._highlightMatches = false; + this.#updateAllPages(); + }); + } + #requestMatchesCount() { + const { + pageIdx, + matchIdx + } = this._selected; + let current = 0, + total = this._matchesCountTotal; + if (matchIdx !== -1) { + for (let i = 0; i < pageIdx; i++) { + current += this._pageMatches[i]?.length || 0; + } + current += matchIdx + 1; + } + if (current < 1 || current > total) { + current = total = 0; + } + return { + current, + total + }; + } + #updateUIResultsCount() { + this._eventBus.dispatch("updatefindmatchescount", { + source: this, + matchesCount: this.#requestMatchesCount() + }); + } + #updateUIState(state, previous = false) { + if (!this.#updateMatchesCountOnProgress && (this.#visitedPagesCount !== this._linkService.pagesCount || state === FindState.PENDING)) { + return; + } + this._eventBus.dispatch("updatefindcontrolstate", { + source: this, + state, + previous, + entireWord: this.#state?.entireWord ?? null, + matchesCount: this.#requestMatchesCount(), + rawQuery: this.#state?.query ?? null + }); + } +} + +;// ./web/pdf_find_bar.js + + +const MATCHES_COUNT_LIMIT = 1000; +class PDFFindBar { + #mainContainer; + #resizeObserver = new ResizeObserver(this.#resizeObserverCallback.bind(this)); + constructor(options, mainContainer, eventBus) { + this.opened = false; + this.bar = options.bar; + this.toggleButton = options.toggleButton; + this.findField = options.findField; + this.highlightAll = options.highlightAllCheckbox; + this.caseSensitive = options.caseSensitiveCheckbox; + this.matchDiacritics = options.matchDiacriticsCheckbox; + this.entireWord = options.entireWordCheckbox; + this.findMsg = options.findMsg; + this.findResultsCount = options.findResultsCount; + this.findPreviousButton = options.findPreviousButton; + this.findNextButton = options.findNextButton; + this.eventBus = eventBus; + this.#mainContainer = mainContainer; + this.toggleButton.addEventListener("click", () => { + this.toggle(); + }); + this.findField.addEventListener("input", () => { + this.dispatchEvent(""); + }); + this.bar.addEventListener("keydown", e => { + switch (e.keyCode) { + case 13: + if (e.target === this.findField) { + this.dispatchEvent("again", e.shiftKey); + } + break; + case 27: + this.close(); + break; + } + }); + this.findPreviousButton.addEventListener("click", () => { + this.dispatchEvent("again", true); + }); + this.findNextButton.addEventListener("click", () => { + this.dispatchEvent("again", false); + }); + this.highlightAll.addEventListener("click", () => { + this.dispatchEvent("highlightallchange"); + }); + this.caseSensitive.addEventListener("click", () => { + this.dispatchEvent("casesensitivitychange"); + }); + this.entireWord.addEventListener("click", () => { + this.dispatchEvent("entirewordchange"); + }); + this.matchDiacritics.addEventListener("click", () => { + this.dispatchEvent("diacriticmatchingchange"); + }); + } + reset() { + this.updateUIState(); + } + dispatchEvent(type, findPrev = false) { + this.eventBus.dispatch("find", { + source: this, + type, + query: this.findField.value, + caseSensitive: this.caseSensitive.checked, + entireWord: this.entireWord.checked, + highlightAll: this.highlightAll.checked, + findPrevious: findPrev, + matchDiacritics: this.matchDiacritics.checked + }); + } + updateUIState(state, previous, matchesCount) { + const { + findField, + findMsg + } = this; + let findMsgId = "", + status = ""; + switch (state) { + case FindState.FOUND: + break; + case FindState.PENDING: + status = "pending"; + break; + case FindState.NOT_FOUND: + findMsgId = "pdfjs-find-not-found"; + status = "notFound"; + break; + case FindState.WRAPPED: + findMsgId = previous ? "pdfjs-find-reached-top" : "pdfjs-find-reached-bottom"; + break; + } + findField.setAttribute("data-status", status); + findField.setAttribute("aria-invalid", state === FindState.NOT_FOUND); + findMsg.setAttribute("data-status", status); + if (findMsgId) { + findMsg.setAttribute("data-l10n-id", findMsgId); + } else { + findMsg.removeAttribute("data-l10n-id"); + findMsg.textContent = ""; + } + this.updateResultsCount(matchesCount); + } + updateResultsCount({ + current = 0, + total = 0 + } = {}) { + const { + findResultsCount + } = this; + if (total > 0) { + const limit = MATCHES_COUNT_LIMIT; + findResultsCount.setAttribute("data-l10n-id", total > limit ? "pdfjs-find-match-count-limit" : "pdfjs-find-match-count"); + findResultsCount.setAttribute("data-l10n-args", JSON.stringify({ + limit, + current, + total + })); + } else { + findResultsCount.removeAttribute("data-l10n-id"); + findResultsCount.textContent = ""; + } + } + open() { + if (!this.opened) { + this.#resizeObserver.observe(this.#mainContainer); + this.#resizeObserver.observe(this.bar); + this.opened = true; + toggleExpandedBtn(this.toggleButton, true, this.bar); + } + this.findField.select(); + this.findField.focus(); + } + close() { + if (!this.opened) { + return; + } + this.#resizeObserver.disconnect(); + this.opened = false; + toggleExpandedBtn(this.toggleButton, false, this.bar); + this.eventBus.dispatch("findbarclose", { + source: this + }); + } + toggle() { + if (this.opened) { + this.close(); + } else { + this.open(); + } + } + #resizeObserverCallback() { + const { + bar + } = this; + bar.classList.remove("wrapContainers"); + const findbarHeight = bar.clientHeight; + const inputContainerHeight = bar.firstElementChild.clientHeight; + if (findbarHeight > inputContainerHeight) { + bar.classList.add("wrapContainers"); + } + } +} + +;// ./web/pdf_history.js + + +const HASH_CHANGE_TIMEOUT = 1000; +const POSITION_UPDATED_THRESHOLD = 50; +const UPDATE_VIEWAREA_TIMEOUT = 1000; +function getCurrentHash() { + return document.location.hash; +} +class PDFHistory { + #eventAbortController = null; + constructor({ + linkService, + eventBus + }) { + this.linkService = linkService; + this.eventBus = eventBus; + this._initialized = false; + this._fingerprint = ""; + this.reset(); + this.eventBus._on("pagesinit", () => { + this._isPagesLoaded = false; + this.eventBus._on("pagesloaded", evt => { + this._isPagesLoaded = !!evt.pagesCount; + }, { + once: true + }); + }); + } + initialize({ + fingerprint, + resetHistory = false, + updateUrl = false + }) { + if (!fingerprint || typeof fingerprint !== "string") { + console.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.'); + return; + } + if (this._initialized) { + this.reset(); + } + const reInitialized = this._fingerprint !== "" && this._fingerprint !== fingerprint; + this._fingerprint = fingerprint; + this._updateUrl = updateUrl === true; + this._initialized = true; + this.#bindEvents(); + const state = window.history.state; + this._popStateInProgress = false; + this._blockHashChange = 0; + this._currentHash = getCurrentHash(); + this._numPositionUpdates = 0; + this._uid = this._maxUid = 0; + this._destination = null; + this._position = null; + if (!this.#isValidState(state, true) || resetHistory) { + const { + hash, + page, + rotation + } = this.#parseCurrentHash(true); + if (!hash || reInitialized || resetHistory) { + this.#pushOrReplaceState(null, true); + return; + } + this.#pushOrReplaceState({ + hash, + page, + rotation + }, true); + return; + } + const destination = state.destination; + this.#updateInternalState(destination, state.uid, true); + if (destination.rotation !== undefined) { + this._initialRotation = destination.rotation; + } + if (destination.dest) { + this._initialBookmark = JSON.stringify(destination.dest); + this._destination.page = null; + } else if (destination.hash) { + this._initialBookmark = destination.hash; + } else if (destination.page) { + this._initialBookmark = `page=${destination.page}`; + } + } + reset() { + if (this._initialized) { + this.#pageHide(); + this._initialized = false; + this.#unbindEvents(); + } + if (this._updateViewareaTimeout) { + clearTimeout(this._updateViewareaTimeout); + this._updateViewareaTimeout = null; + } + this._initialBookmark = null; + this._initialRotation = null; + } + push({ + namedDest = null, + explicitDest, + pageNumber + }) { + if (!this._initialized) { + return; + } + if (namedDest && typeof namedDest !== "string") { + console.error("PDFHistory.push: " + `"${namedDest}" is not a valid namedDest parameter.`); + return; + } else if (!Array.isArray(explicitDest)) { + console.error("PDFHistory.push: " + `"${explicitDest}" is not a valid explicitDest parameter.`); + return; + } else if (!this.#isValidPage(pageNumber)) { + if (pageNumber !== null || this._destination) { + console.error("PDFHistory.push: " + `"${pageNumber}" is not a valid pageNumber parameter.`); + return; + } + } + const hash = namedDest || JSON.stringify(explicitDest); + if (!hash) { + return; + } + let forceReplace = false; + if (this._destination && (isDestHashesEqual(this._destination.hash, hash) || isDestArraysEqual(this._destination.dest, explicitDest))) { + if (this._destination.page) { + return; + } + forceReplace = true; + } + if (this._popStateInProgress && !forceReplace) { + return; + } + this.#pushOrReplaceState({ + dest: explicitDest, + hash, + page: pageNumber, + rotation: this.linkService.rotation + }, forceReplace); + if (!this._popStateInProgress) { + this._popStateInProgress = true; + Promise.resolve().then(() => { + this._popStateInProgress = false; + }); + } + } + pushPage(pageNumber) { + if (!this._initialized) { + return; + } + if (!this.#isValidPage(pageNumber)) { + console.error(`PDFHistory.pushPage: "${pageNumber}" is not a valid page number.`); + return; + } + if (this._destination?.page === pageNumber) { + return; + } + if (this._popStateInProgress) { + return; + } + this.#pushOrReplaceState({ + dest: null, + hash: `page=${pageNumber}`, + page: pageNumber, + rotation: this.linkService.rotation + }); + if (!this._popStateInProgress) { + this._popStateInProgress = true; + Promise.resolve().then(() => { + this._popStateInProgress = false; + }); + } + } + pushCurrentPosition() { + if (!this._initialized || this._popStateInProgress) { + return; + } + this.#tryPushCurrentPosition(); + } + back() { + if (!this._initialized || this._popStateInProgress) { + return; + } + const state = window.history.state; + if (this.#isValidState(state) && state.uid > 0) { + window.history.back(); + } + } + forward() { + if (!this._initialized || this._popStateInProgress) { + return; + } + const state = window.history.state; + if (this.#isValidState(state) && state.uid < this._maxUid) { + window.history.forward(); + } + } + get popStateInProgress() { + return this._initialized && (this._popStateInProgress || this._blockHashChange > 0); + } + get initialBookmark() { + return this._initialized ? this._initialBookmark : null; + } + get initialRotation() { + return this._initialized ? this._initialRotation : null; + } + #pushOrReplaceState(destination, forceReplace = false) { + const shouldReplace = forceReplace || !this._destination; + const newState = { + fingerprint: this._fingerprint, + uid: shouldReplace ? this._uid : this._uid + 1, + destination + }; + this.#updateInternalState(destination, newState.uid); + let newUrl; + if (this._updateUrl && destination?.hash) { + const baseUrl = document.location.href.split("#", 1)[0]; + if (!baseUrl.startsWith("file://")) { + newUrl = `${baseUrl}#${destination.hash}`; + } + } + if (shouldReplace) { + window.history.replaceState(newState, "", newUrl); + } else { + window.history.pushState(newState, "", newUrl); + } + } + #tryPushCurrentPosition(temporary = false) { + if (!this._position) { + return; + } + let position = this._position; + if (temporary) { + position = Object.assign(Object.create(null), this._position); + position.temporary = true; + } + if (!this._destination) { + this.#pushOrReplaceState(position); + return; + } + if (this._destination.temporary) { + this.#pushOrReplaceState(position, true); + return; + } + if (this._destination.hash === position.hash) { + return; + } + if (!this._destination.page && (POSITION_UPDATED_THRESHOLD <= 0 || this._numPositionUpdates <= POSITION_UPDATED_THRESHOLD)) { + return; + } + let forceReplace = false; + if (this._destination.page >= position.first && this._destination.page <= position.page) { + if (this._destination.dest !== undefined || !this._destination.first) { + return; + } + forceReplace = true; + } + this.#pushOrReplaceState(position, forceReplace); + } + #isValidPage(val) { + return Number.isInteger(val) && val > 0 && val <= this.linkService.pagesCount; + } + #isValidState(state, checkReload = false) { + if (!state) { + return false; + } + if (state.fingerprint !== this._fingerprint) { + if (checkReload) { + if (typeof state.fingerprint !== "string" || state.fingerprint.length !== this._fingerprint.length) { + return false; + } + const [perfEntry] = performance.getEntriesByType("navigation"); + if (perfEntry?.type !== "reload") { + return false; + } + } else { + return false; + } + } + if (!Number.isInteger(state.uid) || state.uid < 0) { + return false; + } + if (state.destination === null || typeof state.destination !== "object") { + return false; + } + return true; + } + #updateInternalState(destination, uid, removeTemporary = false) { + if (this._updateViewareaTimeout) { + clearTimeout(this._updateViewareaTimeout); + this._updateViewareaTimeout = null; + } + if (removeTemporary && destination?.temporary) { + delete destination.temporary; + } + this._destination = destination; + this._uid = uid; + this._maxUid = Math.max(this._maxUid, uid); + this._numPositionUpdates = 0; + } + #parseCurrentHash(checkNameddest = false) { + const hash = unescape(getCurrentHash()).substring(1); + const params = parseQueryString(hash); + const nameddest = params.get("nameddest") || ""; + let page = params.get("page") | 0; + if (!this.#isValidPage(page) || checkNameddest && nameddest.length > 0) { + page = null; + } + return { + hash, + page, + rotation: this.linkService.rotation + }; + } + #updateViewarea({ + location + }) { + if (this._updateViewareaTimeout) { + clearTimeout(this._updateViewareaTimeout); + this._updateViewareaTimeout = null; + } + this._position = { + hash: location.pdfOpenParams.substring(1), + page: this.linkService.page, + first: location.pageNumber, + rotation: location.rotation + }; + if (this._popStateInProgress) { + return; + } + if (POSITION_UPDATED_THRESHOLD > 0 && this._isPagesLoaded && this._destination && !this._destination.page) { + this._numPositionUpdates++; + } + if (UPDATE_VIEWAREA_TIMEOUT > 0) { + this._updateViewareaTimeout = setTimeout(() => { + if (!this._popStateInProgress) { + this.#tryPushCurrentPosition(true); + } + this._updateViewareaTimeout = null; + }, UPDATE_VIEWAREA_TIMEOUT); + } + } + #popState({ + state + }) { + const newHash = getCurrentHash(), + hashChanged = this._currentHash !== newHash; + this._currentHash = newHash; + if (!state) { + this._uid++; + const { + hash, + page, + rotation + } = this.#parseCurrentHash(); + this.#pushOrReplaceState({ + hash, + page, + rotation + }, true); + return; + } + if (!this.#isValidState(state)) { + return; + } + this._popStateInProgress = true; + if (hashChanged) { + this._blockHashChange++; + waitOnEventOrTimeout({ + target: window, + name: "hashchange", + delay: HASH_CHANGE_TIMEOUT + }).then(() => { + this._blockHashChange--; + }); + } + const destination = state.destination; + this.#updateInternalState(destination, state.uid, true); + if (isValidRotation(destination.rotation)) { + this.linkService.rotation = destination.rotation; + } + if (destination.dest) { + this.linkService.goToDestination(destination.dest); + } else if (destination.hash) { + this.linkService.setHash(destination.hash); + } else if (destination.page) { + this.linkService.page = destination.page; + } + Promise.resolve().then(() => { + this._popStateInProgress = false; + }); + } + #pageHide() { + if (!this._destination || this._destination.temporary) { + this.#tryPushCurrentPosition(); + } + } + #bindEvents() { + if (this.#eventAbortController) { + return; + } + this.#eventAbortController = new AbortController(); + const { + signal + } = this.#eventAbortController; + this.eventBus._on("updateviewarea", this.#updateViewarea.bind(this), { + signal + }); + window.addEventListener("popstate", this.#popState.bind(this), { + signal + }); + window.addEventListener("pagehide", this.#pageHide.bind(this), { + signal + }); + } + #unbindEvents() { + this.#eventAbortController?.abort(); + this.#eventAbortController = null; + } +} +function isDestHashesEqual(destHash, pushHash) { + if (typeof destHash !== "string" || typeof pushHash !== "string") { + return false; + } + if (destHash === pushHash) { + return true; + } + const nameddest = parseQueryString(destHash).get("nameddest"); + if (nameddest === pushHash) { + return true; + } + return false; +} +function isDestArraysEqual(firstDest, secondDest) { + function isEntryEqual(first, second) { + if (typeof first !== typeof second) { + return false; + } + if (Array.isArray(first) || Array.isArray(second)) { + return false; + } + if (first !== null && typeof first === "object" && second !== null) { + if (Object.keys(first).length !== Object.keys(second).length) { + return false; + } + for (const key in first) { + if (!isEntryEqual(first[key], second[key])) { + return false; + } + } + return true; + } + return first === second || Number.isNaN(first) && Number.isNaN(second); + } + if (!(Array.isArray(firstDest) && Array.isArray(secondDest))) { + return false; + } + if (firstDest.length !== secondDest.length) { + return false; + } + for (let i = 0, ii = firstDest.length; i < ii; i++) { + if (!isEntryEqual(firstDest[i], secondDest[i])) { + return false; + } + } + return true; +} + +;// ./web/pdf_layer_viewer.js + +class PDFLayerViewer extends BaseTreeViewer { + constructor(options) { + super(options); + this.eventBus._on("optionalcontentconfigchanged", evt => { + this.#updateLayers(evt.promise); + }); + this.eventBus._on("resetlayers", () => { + this.#updateLayers(); + }); + this.eventBus._on("togglelayerstree", this._toggleAllTreeItems.bind(this)); + } + reset() { + super.reset(); + this._optionalContentConfig = null; + this._optionalContentVisibility?.clear(); + this._optionalContentVisibility = null; + } + _dispatchEvent(layersCount) { + this.eventBus.dispatch("layersloaded", { + source: this, + layersCount + }); + } + _bindLink(element, { + groupId, + input + }) { + const setVisibility = () => { + const visible = input.checked; + this._optionalContentConfig.setVisibility(groupId, visible); + const cached = this._optionalContentVisibility.get(groupId); + if (cached) { + cached.visible = visible; + } + this.eventBus.dispatch("optionalcontentconfig", { + source: this, + promise: Promise.resolve(this._optionalContentConfig) + }); + }; + element.onclick = evt => { + if (evt.target === input) { + setVisibility(); + return true; + } else if (evt.target !== element) { + return true; + } + input.checked = !input.checked; + setVisibility(); + return false; + }; + } + _setNestedName(element, { + name = null + }) { + if (typeof name === "string") { + element.textContent = this._normalizeTextContent(name); + return; + } + element.setAttribute("data-l10n-id", "pdfjs-additional-layers"); + element.style.fontStyle = "italic"; + this._l10n.translateOnce(element); + } + _addToggleButton(div, { + name = null + }) { + super._addToggleButton(div, name === null); + } + _toggleAllTreeItems() { + if (!this._optionalContentConfig) { + return; + } + super._toggleAllTreeItems(); + } + render({ + optionalContentConfig, + pdfDocument + }) { + if (this._optionalContentConfig) { + this.reset(); + } + this._optionalContentConfig = optionalContentConfig || null; + this._pdfDocument = pdfDocument || null; + const groups = optionalContentConfig?.getOrder(); + if (!groups) { + this._dispatchEvent(0); + return; + } + this._optionalContentVisibility = new Map(); + const fragment = document.createDocumentFragment(), + queue = [{ + parent: fragment, + groups + }]; + let layersCount = 0, + hasAnyNesting = false; + while (queue.length > 0) { + const levelData = queue.shift(); + for (const groupId of levelData.groups) { + const div = document.createElement("div"); + div.className = "treeItem"; + const element = document.createElement("a"); + div.append(element); + if (typeof groupId === "object") { + hasAnyNesting = true; + this._addToggleButton(div, groupId); + this._setNestedName(element, groupId); + const itemsDiv = document.createElement("div"); + itemsDiv.className = "treeItems"; + div.append(itemsDiv); + queue.push({ + parent: itemsDiv, + groups: groupId.order + }); + } else { + const group = optionalContentConfig.getGroup(groupId); + const input = document.createElement("input"); + this._bindLink(element, { + groupId, + input + }); + input.type = "checkbox"; + input.checked = group.visible; + this._optionalContentVisibility.set(groupId, { + input, + visible: input.checked + }); + const label = document.createElement("label"); + label.textContent = this._normalizeTextContent(group.name); + label.append(input); + element.append(label); + layersCount++; + } + levelData.parent.append(div); + } + } + this._finishRendering(fragment, layersCount, hasAnyNesting); + } + async #updateLayers(promise = null) { + if (!this._optionalContentConfig) { + return; + } + const pdfDocument = this._pdfDocument; + const optionalContentConfig = await (promise || pdfDocument.getOptionalContentConfig({ + intent: "display" + })); + if (pdfDocument !== this._pdfDocument) { + return; + } + if (promise) { + for (const [groupId, cached] of this._optionalContentVisibility) { + const group = optionalContentConfig.getGroup(groupId); + if (group && cached.visible !== group.visible) { + cached.input.checked = cached.visible = !cached.visible; + } + } + return; + } + this.eventBus.dispatch("optionalcontentconfig", { + source: this, + promise: Promise.resolve(optionalContentConfig) + }); + this.render({ + optionalContentConfig, + pdfDocument: this._pdfDocument + }); + } +} + +;// ./web/pdf_outline_viewer.js + + +class PDFOutlineViewer extends BaseTreeViewer { + constructor(options) { + super(options); + this.linkService = options.linkService; + this.downloadManager = options.downloadManager; + this.eventBus._on("toggleoutlinetree", this._toggleAllTreeItems.bind(this)); + this.eventBus._on("currentoutlineitem", this._currentOutlineItem.bind(this)); + this.eventBus._on("pagechanging", evt => { + this._currentPageNumber = evt.pageNumber; + }); + this.eventBus._on("pagesloaded", evt => { + this._isPagesLoaded = !!evt.pagesCount; + this._currentOutlineItemCapability?.resolve(this._isPagesLoaded); + }); + this.eventBus._on("sidebarviewchanged", evt => { + this._sidebarView = evt.view; + }); + } + reset() { + super.reset(); + this._outline = null; + this._pageNumberToDestHashCapability = null; + this._currentPageNumber = 1; + this._isPagesLoaded = null; + this._currentOutlineItemCapability?.resolve(false); + this._currentOutlineItemCapability = null; + } + _dispatchEvent(outlineCount) { + this._currentOutlineItemCapability = Promise.withResolvers(); + if (outlineCount === 0 || this._pdfDocument?.loadingParams.disableAutoFetch) { + this._currentOutlineItemCapability.resolve(false); + } else if (this._isPagesLoaded !== null) { + this._currentOutlineItemCapability.resolve(this._isPagesLoaded); + } + this.eventBus.dispatch("outlineloaded", { + source: this, + outlineCount, + currentOutlineItemPromise: this._currentOutlineItemCapability.promise + }); + } + _bindLink(element, { + url, + newWindow, + action, + attachment, + dest, + setOCGState + }) { + const { + linkService + } = this; + if (url) { + linkService.addLinkAttributes(element, url, newWindow); + return; + } + if (action) { + element.href = linkService.getAnchorUrl(""); + element.onclick = () => { + linkService.executeNamedAction(action); + return false; + }; + return; + } + if (attachment) { + element.href = linkService.getAnchorUrl(""); + element.onclick = () => { + this.downloadManager.openOrDownloadData(attachment.content, attachment.filename); + return false; + }; + return; + } + if (setOCGState) { + element.href = linkService.getAnchorUrl(""); + element.onclick = () => { + linkService.executeSetOCGState(setOCGState); + return false; + }; + return; + } + element.href = linkService.getDestinationHash(dest); + element.onclick = evt => { + this._updateCurrentTreeItem(evt.target.parentNode); + if (dest) { + linkService.goToDestination(dest); + } + return false; + }; + } + _setStyles(element, { + bold, + italic + }) { + if (bold) { + element.style.fontWeight = "bold"; + } + if (italic) { + element.style.fontStyle = "italic"; + } + } + _addToggleButton(div, { + count, + items + }) { + let hidden = false; + if (count < 0) { + let totalCount = items.length; + if (totalCount > 0) { + const queue = [...items]; + while (queue.length > 0) { + const { + count: nestedCount, + items: nestedItems + } = queue.shift(); + if (nestedCount > 0 && nestedItems.length > 0) { + totalCount += nestedItems.length; + queue.push(...nestedItems); + } + } + } + if (Math.abs(count) === totalCount) { + hidden = true; + } + } + super._addToggleButton(div, hidden); + } + _toggleAllTreeItems() { + if (!this._outline) { + return; + } + super._toggleAllTreeItems(); + } + render({ + outline, + pdfDocument + }) { + if (this._outline) { + this.reset(); + } + this._outline = outline || null; + this._pdfDocument = pdfDocument || null; + if (!outline) { + this._dispatchEvent(0); + return; + } + const fragment = document.createDocumentFragment(); + const queue = [{ + parent: fragment, + items: outline + }]; + let outlineCount = 0, + hasAnyNesting = false; + while (queue.length > 0) { + const levelData = queue.shift(); + for (const item of levelData.items) { + const div = document.createElement("div"); + div.className = "treeItem"; + const element = document.createElement("a"); + this._bindLink(element, item); + this._setStyles(element, item); + element.textContent = this._normalizeTextContent(item.title); + div.append(element); + if (item.items.length > 0) { + hasAnyNesting = true; + this._addToggleButton(div, item); + const itemsDiv = document.createElement("div"); + itemsDiv.className = "treeItems"; + div.append(itemsDiv); + queue.push({ + parent: itemsDiv, + items: item.items + }); + } + levelData.parent.append(div); + outlineCount++; + } + } + this._finishRendering(fragment, outlineCount, hasAnyNesting); + } + async _currentOutlineItem() { + if (!this._isPagesLoaded) { + throw new Error("_currentOutlineItem: All pages have not been loaded."); + } + if (!this._outline || !this._pdfDocument) { + return; + } + const pageNumberToDestHash = await this._getPageNumberToDestHash(this._pdfDocument); + if (!pageNumberToDestHash) { + return; + } + this._updateCurrentTreeItem(null); + if (this._sidebarView !== SidebarView.OUTLINE) { + return; + } + for (let i = this._currentPageNumber; i > 0; i--) { + const destHash = pageNumberToDestHash.get(i); + if (!destHash) { + continue; + } + const linkElement = this.container.querySelector(`a[href="${destHash}"]`); + if (!linkElement) { + continue; + } + this._scrollToCurrentTreeItem(linkElement.parentNode); + break; + } + } + async _getPageNumberToDestHash(pdfDocument) { + if (this._pageNumberToDestHashCapability) { + return this._pageNumberToDestHashCapability.promise; + } + this._pageNumberToDestHashCapability = Promise.withResolvers(); + const pageNumberToDestHash = new Map(), + pageNumberNesting = new Map(); + const queue = [{ + nesting: 0, + items: this._outline + }]; + while (queue.length > 0) { + const levelData = queue.shift(), + currentNesting = levelData.nesting; + for (const { + dest, + items + } of levelData.items) { + let explicitDest, pageNumber; + if (typeof dest === "string") { + explicitDest = await pdfDocument.getDestination(dest); + if (pdfDocument !== this._pdfDocument) { + return null; + } + } else { + explicitDest = dest; + } + if (Array.isArray(explicitDest)) { + const [destRef] = explicitDest; + if (destRef && typeof destRef === "object") { + pageNumber = pdfDocument.cachedPageNumber(destRef); + } else if (Number.isInteger(destRef)) { + pageNumber = destRef + 1; + } + if (Number.isInteger(pageNumber) && (!pageNumberToDestHash.has(pageNumber) || currentNesting > pageNumberNesting.get(pageNumber))) { + const destHash = this.linkService.getDestinationHash(dest); + pageNumberToDestHash.set(pageNumber, destHash); + pageNumberNesting.set(pageNumber, currentNesting); + } + } + if (items.length > 0) { + queue.push({ + nesting: currentNesting + 1, + items + }); + } + } + } + this._pageNumberToDestHashCapability.resolve(pageNumberToDestHash.size > 0 ? pageNumberToDestHash : null); + return this._pageNumberToDestHashCapability.promise; + } +} + +;// ./web/pdf_presentation_mode.js + + +const DELAY_BEFORE_HIDING_CONTROLS = 3000; +const ACTIVE_SELECTOR = "pdfPresentationMode"; +const CONTROLS_SELECTOR = "pdfPresentationModeControls"; +const MOUSE_SCROLL_COOLDOWN_TIME = 50; +const PAGE_SWITCH_THRESHOLD = 0.1; +const SWIPE_MIN_DISTANCE_THRESHOLD = 50; +const SWIPE_ANGLE_THRESHOLD = Math.PI / 6; +class PDFPresentationMode { + #state = PresentationModeState.UNKNOWN; + #args = null; + #fullscreenChangeAbortController = null; + #windowAbortController = null; + constructor({ + container, + pdfViewer, + eventBus + }) { + this.container = container; + this.pdfViewer = pdfViewer; + this.eventBus = eventBus; + this.contextMenuOpen = false; + this.mouseScrollTimeStamp = 0; + this.mouseScrollDelta = 0; + this.touchSwipeState = null; + } + async request() { + const { + container, + pdfViewer + } = this; + if (this.active || !pdfViewer.pagesCount || !container.requestFullscreen) { + return false; + } + this.#addFullscreenChangeListeners(); + this.#notifyStateChange(PresentationModeState.CHANGING); + const promise = container.requestFullscreen(); + this.#args = { + pageNumber: pdfViewer.currentPageNumber, + scaleValue: pdfViewer.currentScaleValue, + scrollMode: pdfViewer.scrollMode, + spreadMode: null, + annotationEditorMode: null + }; + if (pdfViewer.spreadMode !== SpreadMode.NONE && !(pdfViewer.pageViewsReady && pdfViewer.hasEqualPageSizes)) { + console.warn("Ignoring Spread modes when entering PresentationMode, " + "since the document may contain varying page sizes."); + this.#args.spreadMode = pdfViewer.spreadMode; + } + if (pdfViewer.annotationEditorMode !== AnnotationEditorType.DISABLE) { + this.#args.annotationEditorMode = pdfViewer.annotationEditorMode; + } + try { + await promise; + pdfViewer.focus(); + return true; + } catch { + this.#removeFullscreenChangeListeners(); + this.#notifyStateChange(PresentationModeState.NORMAL); + } + return false; + } + get active() { + return this.#state === PresentationModeState.CHANGING || this.#state === PresentationModeState.FULLSCREEN; + } + #mouseWheel(evt) { + if (!this.active) { + return; + } + evt.preventDefault(); + const delta = normalizeWheelEventDelta(evt); + const currentTime = Date.now(); + const storedTime = this.mouseScrollTimeStamp; + if (currentTime > storedTime && currentTime - storedTime < MOUSE_SCROLL_COOLDOWN_TIME) { + return; + } + if (this.mouseScrollDelta > 0 && delta < 0 || this.mouseScrollDelta < 0 && delta > 0) { + this.#resetMouseScrollState(); + } + this.mouseScrollDelta += delta; + if (Math.abs(this.mouseScrollDelta) >= PAGE_SWITCH_THRESHOLD) { + const totalDelta = this.mouseScrollDelta; + this.#resetMouseScrollState(); + const success = totalDelta > 0 ? this.pdfViewer.previousPage() : this.pdfViewer.nextPage(); + if (success) { + this.mouseScrollTimeStamp = currentTime; + } + } + } + #notifyStateChange(state) { + this.#state = state; + this.eventBus.dispatch("presentationmodechanged", { + source: this, + state + }); + } + #enter() { + this.#notifyStateChange(PresentationModeState.FULLSCREEN); + this.container.classList.add(ACTIVE_SELECTOR); + setTimeout(() => { + this.pdfViewer.scrollMode = ScrollMode.PAGE; + if (this.#args.spreadMode !== null) { + this.pdfViewer.spreadMode = SpreadMode.NONE; + } + this.pdfViewer.currentPageNumber = this.#args.pageNumber; + this.pdfViewer.currentScaleValue = "page-fit"; + if (this.#args.annotationEditorMode !== null) { + this.pdfViewer.annotationEditorMode = { + mode: AnnotationEditorType.NONE + }; + } + }, 0); + this.#addWindowListeners(); + this.#showControls(); + this.contextMenuOpen = false; + document.getSelection().empty(); + } + #exit() { + const pageNumber = this.pdfViewer.currentPageNumber; + this.container.classList.remove(ACTIVE_SELECTOR); + setTimeout(() => { + this.#removeFullscreenChangeListeners(); + this.#notifyStateChange(PresentationModeState.NORMAL); + this.pdfViewer.scrollMode = this.#args.scrollMode; + if (this.#args.spreadMode !== null) { + this.pdfViewer.spreadMode = this.#args.spreadMode; + } + this.pdfViewer.currentScaleValue = this.#args.scaleValue; + this.pdfViewer.currentPageNumber = pageNumber; + if (this.#args.annotationEditorMode !== null) { + this.pdfViewer.annotationEditorMode = { + mode: this.#args.annotationEditorMode + }; + } + this.#args = null; + }, 0); + this.#removeWindowListeners(); + this.#hideControls(); + this.#resetMouseScrollState(); + this.contextMenuOpen = false; + } + #mouseDown(evt) { + if (this.contextMenuOpen) { + this.contextMenuOpen = false; + evt.preventDefault(); + return; + } + if (evt.button !== 0) { + return; + } + if (evt.target.href && evt.target.parentNode?.hasAttribute("data-internal-link")) { + return; + } + evt.preventDefault(); + if (evt.shiftKey) { + this.pdfViewer.previousPage(); + } else { + this.pdfViewer.nextPage(); + } + } + #contextMenu() { + this.contextMenuOpen = true; + } + #showControls() { + if (this.controlsTimeout) { + clearTimeout(this.controlsTimeout); + } else { + this.container.classList.add(CONTROLS_SELECTOR); + } + this.controlsTimeout = setTimeout(() => { + this.container.classList.remove(CONTROLS_SELECTOR); + delete this.controlsTimeout; + }, DELAY_BEFORE_HIDING_CONTROLS); + } + #hideControls() { + if (!this.controlsTimeout) { + return; + } + clearTimeout(this.controlsTimeout); + this.container.classList.remove(CONTROLS_SELECTOR); + delete this.controlsTimeout; + } + #resetMouseScrollState() { + this.mouseScrollTimeStamp = 0; + this.mouseScrollDelta = 0; + } + #touchSwipe(evt) { + if (!this.active) { + return; + } + if (evt.touches.length > 1) { + this.touchSwipeState = null; + return; + } + switch (evt.type) { + case "touchstart": + this.touchSwipeState = { + startX: evt.touches[0].pageX, + startY: evt.touches[0].pageY, + endX: evt.touches[0].pageX, + endY: evt.touches[0].pageY + }; + break; + case "touchmove": + if (this.touchSwipeState === null) { + return; + } + this.touchSwipeState.endX = evt.touches[0].pageX; + this.touchSwipeState.endY = evt.touches[0].pageY; + evt.preventDefault(); + break; + case "touchend": + if (this.touchSwipeState === null) { + return; + } + let delta = 0; + const dx = this.touchSwipeState.endX - this.touchSwipeState.startX; + const dy = this.touchSwipeState.endY - this.touchSwipeState.startY; + const absAngle = Math.abs(Math.atan2(dy, dx)); + if (Math.abs(dx) > SWIPE_MIN_DISTANCE_THRESHOLD && (absAngle <= SWIPE_ANGLE_THRESHOLD || absAngle >= Math.PI - SWIPE_ANGLE_THRESHOLD)) { + delta = dx; + } else if (Math.abs(dy) > SWIPE_MIN_DISTANCE_THRESHOLD && Math.abs(absAngle - Math.PI / 2) <= SWIPE_ANGLE_THRESHOLD) { + delta = dy; + } + if (delta > 0) { + this.pdfViewer.previousPage(); + } else if (delta < 0) { + this.pdfViewer.nextPage(); + } + break; + } + } + #addWindowListeners() { + if (this.#windowAbortController) { + return; + } + this.#windowAbortController = new AbortController(); + const { + signal + } = this.#windowAbortController; + const touchSwipeBind = this.#touchSwipe.bind(this); + window.addEventListener("mousemove", this.#showControls.bind(this), { + signal + }); + window.addEventListener("mousedown", this.#mouseDown.bind(this), { + signal + }); + window.addEventListener("wheel", this.#mouseWheel.bind(this), { + passive: false, + signal + }); + window.addEventListener("keydown", this.#resetMouseScrollState.bind(this), { + signal + }); + window.addEventListener("contextmenu", this.#contextMenu.bind(this), { + signal + }); + window.addEventListener("touchstart", touchSwipeBind, { + signal + }); + window.addEventListener("touchmove", touchSwipeBind, { + signal + }); + window.addEventListener("touchend", touchSwipeBind, { + signal + }); + } + #removeWindowListeners() { + this.#windowAbortController?.abort(); + this.#windowAbortController = null; + } + #addFullscreenChangeListeners() { + if (this.#fullscreenChangeAbortController) { + return; + } + this.#fullscreenChangeAbortController = new AbortController(); + window.addEventListener("fullscreenchange", () => { + if (document.fullscreenElement) { + this.#enter(); + } else { + this.#exit(); + } + }, { + signal: this.#fullscreenChangeAbortController.signal + }); + } + #removeFullscreenChangeListeners() { + this.#fullscreenChangeAbortController?.abort(); + this.#fullscreenChangeAbortController = null; + } +} + +;// ./web/xfa_layer_builder.js + +class XfaLayerBuilder { + constructor({ + pdfPage, + annotationStorage = null, + linkService, + xfaHtml = null + }) { + this.pdfPage = pdfPage; + this.annotationStorage = annotationStorage; + this.linkService = linkService; + this.xfaHtml = xfaHtml; + this.div = null; + this._cancelled = false; + } + async render(viewport, intent = "display") { + if (intent === "print") { + const parameters = { + viewport: viewport.clone({ + dontFlip: true + }), + div: this.div, + xfaHtml: this.xfaHtml, + annotationStorage: this.annotationStorage, + linkService: this.linkService, + intent + }; + this.div = document.createElement("div"); + parameters.div = this.div; + return XfaLayer.render(parameters); + } + const xfaHtml = await this.pdfPage.getXfa(); + if (this._cancelled || !xfaHtml) { + return { + textDivs: [] + }; + } + const parameters = { + viewport: viewport.clone({ + dontFlip: true + }), + div: this.div, + xfaHtml, + annotationStorage: this.annotationStorage, + linkService: this.linkService, + intent + }; + if (this.div) { + return XfaLayer.update(parameters); + } + this.div = document.createElement("div"); + parameters.div = this.div; + return XfaLayer.render(parameters); + } + cancel() { + this._cancelled = true; + } + hide() { + if (!this.div) { + return; + } + this.div.hidden = true; + } +} + +;// ./web/print_utils.js + + + +function getXfaHtmlForPrinting(printContainer, pdfDocument) { + const xfaHtml = pdfDocument.allXfaHtml; + const linkService = new SimpleLinkService(); + const scale = Math.round(PixelsPerInch.PDF_TO_CSS_UNITS * 100) / 100; + for (const xfaPage of xfaHtml.children) { + const page = document.createElement("div"); + page.className = "xfaPrintedPage"; + printContainer.append(page); + const builder = new XfaLayerBuilder({ + pdfPage: null, + annotationStorage: pdfDocument.annotationStorage, + linkService, + xfaHtml: xfaPage + }); + const viewport = getXfaPageViewport(xfaPage, { + scale + }); + builder.render(viewport, "print"); + page.append(builder.div); + } +} + +;// ./web/pdf_print_service.js + + +let activeService = null; +let dialog = null; +let overlayManager = null; +let viewerApp = { + initialized: false +}; +function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size, printResolution, optionalContentConfigPromise, printAnnotationStoragePromise) { + const scratchCanvas = activeService.scratchCanvas; + const PRINT_UNITS = printResolution / PixelsPerInch.PDF; + scratchCanvas.width = Math.floor(size.width * PRINT_UNITS); + scratchCanvas.height = Math.floor(size.height * PRINT_UNITS); + const ctx = scratchCanvas.getContext("2d"); + ctx.save(); + ctx.fillStyle = "rgb(255, 255, 255)"; + ctx.fillRect(0, 0, scratchCanvas.width, scratchCanvas.height); + ctx.restore(); + return Promise.all([pdfDocument.getPage(pageNumber), printAnnotationStoragePromise]).then(function ([pdfPage, printAnnotationStorage]) { + const renderContext = { + canvasContext: ctx, + transform: [PRINT_UNITS, 0, 0, PRINT_UNITS, 0, 0], + viewport: pdfPage.getViewport({ + scale: 1, + rotation: size.rotation + }), + intent: "print", + annotationMode: AnnotationMode.ENABLE_STORAGE, + optionalContentConfigPromise, + printAnnotationStorage + }; + const renderTask = pdfPage.render(renderContext); + return renderTask.promise.catch(reason => { + if (!(reason instanceof RenderingCancelledException)) { + console.error(reason); + } + throw reason; + }); + }); +} +class PDFPrintService { + constructor({ + pdfDocument, + pagesOverview, + printContainer, + printResolution, + printAnnotationStoragePromise = null + }) { + this.pdfDocument = pdfDocument; + this.pagesOverview = pagesOverview; + this.printContainer = printContainer; + this._printResolution = printResolution || 150; + this._optionalContentConfigPromise = pdfDocument.getOptionalContentConfig({ + intent: "print" + }); + this._printAnnotationStoragePromise = printAnnotationStoragePromise || Promise.resolve(); + this.currentPage = -1; + this.scratchCanvas = document.createElement("canvas"); + } + layout() { + this.throwIfInactive(); + const body = document.querySelector("body"); + body.setAttribute("data-pdfjsprinting", true); + const { + width, + height + } = this.pagesOverview[0]; + const hasEqualPageSizes = this.pagesOverview.every(size => size.width === width && size.height === height); + if (!hasEqualPageSizes) { + console.warn("Not all pages have the same size. The printed result may be incorrect!"); + } + this.pageStyleSheet = document.createElement("style"); + this.pageStyleSheet.textContent = `@page { size: ${width}pt ${height}pt;}`; + body.append(this.pageStyleSheet); + } + destroy() { + if (activeService !== this) { + return; + } + this.printContainer.textContent = ""; + const body = document.querySelector("body"); + body.removeAttribute("data-pdfjsprinting"); + if (this.pageStyleSheet) { + this.pageStyleSheet.remove(); + this.pageStyleSheet = null; + } + this.scratchCanvas.width = this.scratchCanvas.height = 0; + this.scratchCanvas = null; + activeService = null; + ensureOverlay().then(function () { + if (overlayManager.active === dialog) { + overlayManager.close(dialog); + } + }); + } + renderPages() { + if (this.pdfDocument.isPureXfa) { + getXfaHtmlForPrinting(this.printContainer, this.pdfDocument); + return Promise.resolve(); + } + const pageCount = this.pagesOverview.length; + const renderNextPage = (resolve, reject) => { + this.throwIfInactive(); + if (++this.currentPage >= pageCount) { + renderProgress(pageCount, pageCount); + resolve(); + return; + } + const index = this.currentPage; + renderProgress(index, pageCount); + renderPage(this, this.pdfDocument, index + 1, this.pagesOverview[index], this._printResolution, this._optionalContentConfigPromise, this._printAnnotationStoragePromise).then(this.useRenderedPage.bind(this)).then(function () { + renderNextPage(resolve, reject); + }, reject); + }; + return new Promise(renderNextPage); + } + useRenderedPage() { + this.throwIfInactive(); + const img = document.createElement("img"); + this.scratchCanvas.toBlob(blob => { + img.src = URL.createObjectURL(blob); + }); + const wrapper = document.createElement("div"); + wrapper.className = "printedPage"; + wrapper.append(img); + this.printContainer.append(wrapper); + const { + promise, + resolve, + reject + } = Promise.withResolvers(); + img.onload = resolve; + img.onerror = reject; + promise.catch(() => {}).then(() => { + URL.revokeObjectURL(img.src); + }); + return promise; + } + performPrint() { + this.throwIfInactive(); + return new Promise(resolve => { + setTimeout(() => { + if (!this.active) { + resolve(); + return; + } + print.call(window); + setTimeout(resolve, 20); + }, 0); + }); + } + get active() { + return this === activeService; + } + throwIfInactive() { + if (!this.active) { + throw new Error("This print request was cancelled or completed."); + } + } +} +const print = window.print; +window.print = function () { + if (activeService) { + console.warn("Ignored window.print() because of a pending print job."); + return; + } + ensureOverlay().then(function () { + if (activeService) { + overlayManager.open(dialog); + } + }); + try { + dispatchEvent("beforeprint"); + } finally { + if (!activeService) { + console.error("Expected print service to be initialized."); + ensureOverlay().then(function () { + if (overlayManager.active === dialog) { + overlayManager.close(dialog); + } + }); + return; + } + const activeServiceOnEntry = activeService; + activeService.renderPages().then(function () { + return activeServiceOnEntry.performPrint(); + }).catch(function () {}).then(function () { + if (activeServiceOnEntry.active) { + abort(); + } + }); + } +}; +function dispatchEvent(eventType) { + const event = new CustomEvent(eventType, { + bubbles: false, + cancelable: false, + detail: "custom" + }); + window.dispatchEvent(event); +} +function abort() { + if (activeService) { + activeService.destroy(); + dispatchEvent("afterprint"); + } +} +function renderProgress(index, total) { + dialog ||= document.getElementById("printServiceDialog"); + const progress = Math.round(100 * index / total); + const progressBar = dialog.querySelector("progress"); + const progressPerc = dialog.querySelector(".relative-progress"); + progressBar.value = progress; + progressPerc.setAttribute("data-l10n-args", JSON.stringify({ + progress + })); +} +window.addEventListener("keydown", function (event) { + if (event.keyCode === 80 && (event.ctrlKey || event.metaKey) && !event.altKey && (!event.shiftKey || window.chrome || window.opera)) { + window.print(); + event.preventDefault(); + event.stopImmediatePropagation(); + } +}, true); +if ("onbeforeprint" in window) { + const stopPropagationIfNeeded = function (event) { + if (event.detail !== "custom") { + event.stopImmediatePropagation(); + } + }; + window.addEventListener("beforeprint", stopPropagationIfNeeded); + window.addEventListener("afterprint", stopPropagationIfNeeded); +} +let overlayPromise; +function ensureOverlay() { + if (!overlayPromise) { + overlayManager = viewerApp.overlayManager; + if (!overlayManager) { + throw new Error("The overlay manager has not yet been initialized."); + } + dialog ||= document.getElementById("printServiceDialog"); + overlayPromise = overlayManager.register(dialog, true); + document.getElementById("printCancel").onclick = abort; + dialog.addEventListener("close", abort); + } + return overlayPromise; +} +class PDFPrintServiceFactory { + static initGlobals(app) { + viewerApp = app; + } + static get supportsPrinting() { + return shadow(this, "supportsPrinting", true); + } + static createPrintService(params) { + if (activeService) { + throw new Error("The print service is created and active."); + } + return activeService = new PDFPrintService(params); + } +} + +;// ./web/pdf_rendering_queue.js + + +const CLEANUP_TIMEOUT = 30000; +class PDFRenderingQueue { + constructor() { + this.pdfViewer = null; + this.pdfThumbnailViewer = null; + this.onIdle = null; + this.highestPriorityPage = null; + this.idleTimeout = null; + this.printing = false; + this.isThumbnailViewEnabled = false; + Object.defineProperty(this, "hasViewer", { + value: () => !!this.pdfViewer + }); + } + setViewer(pdfViewer) { + this.pdfViewer = pdfViewer; + } + setThumbnailViewer(pdfThumbnailViewer) { + this.pdfThumbnailViewer = pdfThumbnailViewer; + } + isHighestPriority(view) { + return this.highestPriorityPage === view.renderingId; + } + renderHighestPriority(currentlyVisiblePages) { + if (this.idleTimeout) { + clearTimeout(this.idleTimeout); + this.idleTimeout = null; + } + if (this.pdfViewer.forceRendering(currentlyVisiblePages)) { + return; + } + if (this.isThumbnailViewEnabled && this.pdfThumbnailViewer?.forceRendering()) { + return; + } + if (this.printing) { + return; + } + if (this.onIdle) { + this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT); + } + } + getHighestPriority(visible, views, scrolledDown, preRenderExtra = false) { + const visibleViews = visible.views, + numVisible = visibleViews.length; + if (numVisible === 0) { + return null; + } + for (let i = 0; i < numVisible; i++) { + const view = visibleViews[i].view; + if (!this.isViewFinished(view)) { + return view; + } + } + const firstId = visible.first.id, + lastId = visible.last.id; + if (lastId - firstId + 1 > numVisible) { + const visibleIds = visible.ids; + for (let i = 1, ii = lastId - firstId; i < ii; i++) { + const holeId = scrolledDown ? firstId + i : lastId - i; + if (visibleIds.has(holeId)) { + continue; + } + const holeView = views[holeId - 1]; + if (!this.isViewFinished(holeView)) { + return holeView; + } + } + } + let preRenderIndex = scrolledDown ? lastId : firstId - 2; + let preRenderView = views[preRenderIndex]; + if (preRenderView && !this.isViewFinished(preRenderView)) { + return preRenderView; + } + if (preRenderExtra) { + preRenderIndex += scrolledDown ? 1 : -1; + preRenderView = views[preRenderIndex]; + if (preRenderView && !this.isViewFinished(preRenderView)) { + return preRenderView; + } + } + return null; + } + isViewFinished(view) { + return view.renderingState === RenderingStates.FINISHED; + } + renderView(view) { + switch (view.renderingState) { + case RenderingStates.FINISHED: + return false; + case RenderingStates.PAUSED: + this.highestPriorityPage = view.renderingId; + view.resume(); + break; + case RenderingStates.RUNNING: + this.highestPriorityPage = view.renderingId; + break; + case RenderingStates.INITIAL: + this.highestPriorityPage = view.renderingId; + view.draw().finally(() => { + this.renderHighestPriority(); + }).catch(reason => { + if (reason instanceof RenderingCancelledException) { + return; + } + console.error(`renderView: "${reason}"`); + }); + break; + } + return true; + } +} + +;// ./web/pdf_scripting_manager.js + + +class PDFScriptingManager { + #closeCapability = null; + #destroyCapability = null; + #docProperties = null; + #eventAbortController = null; + #eventBus = null; + #externalServices = null; + #pdfDocument = null; + #pdfViewer = null; + #ready = false; + #scripting = null; + #willPrintCapability = null; + constructor({ + eventBus, + externalServices = null, + docProperties = null + }) { + this.#eventBus = eventBus; + this.#externalServices = externalServices; + this.#docProperties = docProperties; + } + setViewer(pdfViewer) { + this.#pdfViewer = pdfViewer; + } + async setDocument(pdfDocument) { + if (this.#pdfDocument) { + await this.#destroyScripting(); + } + this.#pdfDocument = pdfDocument; + if (!pdfDocument) { + return; + } + const [objects, calculationOrder, docActions] = await Promise.all([pdfDocument.getFieldObjects(), pdfDocument.getCalculationOrderIds(), pdfDocument.getJSActions()]); + if (!objects && !docActions) { + await this.#destroyScripting(); + return; + } + if (pdfDocument !== this.#pdfDocument) { + return; + } + try { + this.#scripting = this.#initScripting(); + } catch (error) { + console.error(`setDocument: "${error.message}".`); + await this.#destroyScripting(); + return; + } + const eventBus = this.#eventBus; + this.#eventAbortController = new AbortController(); + const { + signal + } = this.#eventAbortController; + eventBus._on("updatefromsandbox", event => { + if (event?.source === window) { + this.#updateFromSandbox(event.detail); + } + }, { + signal + }); + eventBus._on("dispatcheventinsandbox", event => { + this.#scripting?.dispatchEventInSandbox(event.detail); + }, { + signal + }); + eventBus._on("pagechanging", ({ + pageNumber, + previous + }) => { + if (pageNumber === previous) { + return; + } + this.#dispatchPageClose(previous); + this.#dispatchPageOpen(pageNumber); + }, { + signal + }); + eventBus._on("pagerendered", ({ + pageNumber + }) => { + if (!this._pageOpenPending.has(pageNumber)) { + return; + } + if (pageNumber !== this.#pdfViewer.currentPageNumber) { + return; + } + this.#dispatchPageOpen(pageNumber); + }, { + signal + }); + eventBus._on("pagesdestroy", async () => { + await this.#dispatchPageClose(this.#pdfViewer.currentPageNumber); + await this.#scripting?.dispatchEventInSandbox({ + id: "doc", + name: "WillClose" + }); + this.#closeCapability?.resolve(); + }, { + signal + }); + try { + const docProperties = await this.#docProperties(pdfDocument); + if (pdfDocument !== this.#pdfDocument) { + return; + } + await this.#scripting.createSandbox({ + objects, + calculationOrder, + appInfo: { + platform: navigator.platform, + language: navigator.language + }, + docInfo: { + ...docProperties, + actions: docActions + } + }); + eventBus.dispatch("sandboxcreated", { + source: this + }); + } catch (error) { + console.error(`setDocument: "${error.message}".`); + await this.#destroyScripting(); + return; + } + await this.#scripting?.dispatchEventInSandbox({ + id: "doc", + name: "Open" + }); + await this.#dispatchPageOpen(this.#pdfViewer.currentPageNumber, true); + Promise.resolve().then(() => { + if (pdfDocument === this.#pdfDocument) { + this.#ready = true; + } + }); + } + async dispatchWillSave() { + return this.#scripting?.dispatchEventInSandbox({ + id: "doc", + name: "WillSave" + }); + } + async dispatchDidSave() { + return this.#scripting?.dispatchEventInSandbox({ + id: "doc", + name: "DidSave" + }); + } + async dispatchWillPrint() { + if (!this.#scripting) { + return; + } + await this.#willPrintCapability?.promise; + this.#willPrintCapability = Promise.withResolvers(); + try { + await this.#scripting.dispatchEventInSandbox({ + id: "doc", + name: "WillPrint" + }); + } catch (ex) { + this.#willPrintCapability.resolve(); + this.#willPrintCapability = null; + throw ex; + } + await this.#willPrintCapability.promise; + } + async dispatchDidPrint() { + return this.#scripting?.dispatchEventInSandbox({ + id: "doc", + name: "DidPrint" + }); + } + get destroyPromise() { + return this.#destroyCapability?.promise || null; + } + get ready() { + return this.#ready; + } + get _pageOpenPending() { + return shadow(this, "_pageOpenPending", new Set()); + } + get _visitedPages() { + return shadow(this, "_visitedPages", new Map()); + } + async #updateFromSandbox(detail) { + const pdfViewer = this.#pdfViewer; + const isInPresentationMode = pdfViewer.isInPresentationMode || pdfViewer.isChangingPresentationMode; + const { + id, + siblings, + command, + value + } = detail; + if (!id) { + switch (command) { + case "clear": + console.clear(); + break; + case "error": + console.error(value); + break; + case "layout": + if (!isInPresentationMode) { + const modes = apiPageLayoutToViewerModes(value); + pdfViewer.spreadMode = modes.spreadMode; + } + break; + case "page-num": + pdfViewer.currentPageNumber = value + 1; + break; + case "print": + await pdfViewer.pagesPromise; + this.#eventBus.dispatch("print", { + source: this + }); + break; + case "println": + console.log(value); + break; + case "zoom": + if (!isInPresentationMode) { + pdfViewer.currentScaleValue = value; + } + break; + case "SaveAs": + this.#eventBus.dispatch("download", { + source: this + }); + break; + case "FirstPage": + pdfViewer.currentPageNumber = 1; + break; + case "LastPage": + pdfViewer.currentPageNumber = pdfViewer.pagesCount; + break; + case "NextPage": + pdfViewer.nextPage(); + break; + case "PrevPage": + pdfViewer.previousPage(); + break; + case "ZoomViewIn": + if (!isInPresentationMode) { + pdfViewer.increaseScale(); + } + break; + case "ZoomViewOut": + if (!isInPresentationMode) { + pdfViewer.decreaseScale(); + } + break; + case "WillPrintFinished": + this.#willPrintCapability?.resolve(); + this.#willPrintCapability = null; + break; + } + return; + } + if (isInPresentationMode && detail.focus) { + return; + } + delete detail.id; + delete detail.siblings; + const ids = siblings ? [id, ...siblings] : [id]; + for (const elementId of ids) { + const element = document.querySelector(`[data-element-id="${elementId}"]`); + if (element) { + element.dispatchEvent(new CustomEvent("updatefromsandbox", { + detail + })); + } else { + this.#pdfDocument?.annotationStorage.setValue(elementId, detail); + } + } + } + async #dispatchPageOpen(pageNumber, initialize = false) { + const pdfDocument = this.#pdfDocument, + visitedPages = this._visitedPages; + if (initialize) { + this.#closeCapability = Promise.withResolvers(); + } + if (!this.#closeCapability) { + return; + } + const pageView = this.#pdfViewer.getPageView(pageNumber - 1); + if (pageView?.renderingState !== RenderingStates.FINISHED) { + this._pageOpenPending.add(pageNumber); + return; + } + this._pageOpenPending.delete(pageNumber); + const actionsPromise = (async () => { + const actions = await (!visitedPages.has(pageNumber) ? pageView.pdfPage?.getJSActions() : null); + if (pdfDocument !== this.#pdfDocument) { + return; + } + await this.#scripting?.dispatchEventInSandbox({ + id: "page", + name: "PageOpen", + pageNumber, + actions + }); + })(); + visitedPages.set(pageNumber, actionsPromise); + } + async #dispatchPageClose(pageNumber) { + const pdfDocument = this.#pdfDocument, + visitedPages = this._visitedPages; + if (!this.#closeCapability) { + return; + } + if (this._pageOpenPending.has(pageNumber)) { + return; + } + const actionsPromise = visitedPages.get(pageNumber); + if (!actionsPromise) { + return; + } + visitedPages.set(pageNumber, null); + await actionsPromise; + if (pdfDocument !== this.#pdfDocument) { + return; + } + await this.#scripting?.dispatchEventInSandbox({ + id: "page", + name: "PageClose", + pageNumber + }); + } + #initScripting() { + this.#destroyCapability = Promise.withResolvers(); + if (this.#scripting) { + throw new Error("#initScripting: Scripting already exists."); + } + return this.#externalServices.createScripting(); + } + async #destroyScripting() { + if (!this.#scripting) { + this.#pdfDocument = null; + this.#destroyCapability?.resolve(); + return; + } + if (this.#closeCapability) { + await Promise.race([this.#closeCapability.promise, new Promise(resolve => { + setTimeout(resolve, 1000); + })]).catch(() => {}); + this.#closeCapability = null; + } + this.#pdfDocument = null; + try { + await this.#scripting.destroySandbox(); + } catch {} + this.#willPrintCapability?.reject(new Error("Scripting destroyed.")); + this.#willPrintCapability = null; + this.#eventAbortController?.abort(); + this.#eventAbortController = null; + this._pageOpenPending.clear(); + this._visitedPages.clear(); + this.#scripting = null; + this.#ready = false; + this.#destroyCapability?.resolve(); + } +} + +;// ./web/pdf_sidebar.js + +const SIDEBAR_WIDTH_VAR = "--sidebar-width"; +const SIDEBAR_MIN_WIDTH = 200; +const SIDEBAR_RESIZING_CLASS = "sidebarResizing"; +const UI_NOTIFICATION_CLASS = "pdfSidebarNotification"; +class PDFSidebar { + #isRTL = false; + #mouseAC = null; + #outerContainerWidth = null; + #width = null; + constructor({ + elements, + eventBus, + l10n + }) { + this.isOpen = false; + this.active = SidebarView.THUMBS; + this.isInitialViewSet = false; + this.isInitialEventDispatched = false; + this.onToggled = null; + this.onUpdateThumbnails = null; + this.outerContainer = elements.outerContainer; + this.sidebarContainer = elements.sidebarContainer; + this.toggleButton = elements.toggleButton; + this.resizer = elements.resizer; + this.thumbnailButton = elements.thumbnailButton; + this.outlineButton = elements.outlineButton; + this.attachmentsButton = elements.attachmentsButton; + this.layersButton = elements.layersButton; + this.thumbnailView = elements.thumbnailView; + this.outlineView = elements.outlineView; + this.attachmentsView = elements.attachmentsView; + this.layersView = elements.layersView; + this._currentOutlineItemButton = elements.currentOutlineItemButton; + this.eventBus = eventBus; + this.#isRTL = l10n.getDirection() === "rtl"; + this.#addEventListeners(); + } + reset() { + this.isInitialViewSet = false; + this.isInitialEventDispatched = false; + this.#hideUINotification(true); + this.switchView(SidebarView.THUMBS); + this.outlineButton.disabled = false; + this.attachmentsButton.disabled = false; + this.layersButton.disabled = false; + this._currentOutlineItemButton.disabled = true; + } + get visibleView() { + return this.isOpen ? this.active : SidebarView.NONE; + } + setInitialView(view = SidebarView.NONE) { + if (this.isInitialViewSet) { + return; + } + this.isInitialViewSet = true; + if (view === SidebarView.NONE || view === SidebarView.UNKNOWN) { + this.#dispatchEvent(); + return; + } + this.switchView(view, true); + if (!this.isInitialEventDispatched) { + this.#dispatchEvent(); + } + } + switchView(view, forceOpen = false) { + const isViewChanged = view !== this.active; + let forceRendering = false; + switch (view) { + case SidebarView.NONE: + if (this.isOpen) { + this.close(); + } + return; + case SidebarView.THUMBS: + if (this.isOpen && isViewChanged) { + forceRendering = true; + } + break; + case SidebarView.OUTLINE: + if (this.outlineButton.disabled) { + return; + } + break; + case SidebarView.ATTACHMENTS: + if (this.attachmentsButton.disabled) { + return; + } + break; + case SidebarView.LAYERS: + if (this.layersButton.disabled) { + return; + } + break; + default: + console.error(`PDFSidebar.switchView: "${view}" is not a valid view.`); + return; + } + this.active = view; + toggleCheckedBtn(this.thumbnailButton, view === SidebarView.THUMBS, this.thumbnailView); + toggleCheckedBtn(this.outlineButton, view === SidebarView.OUTLINE, this.outlineView); + toggleCheckedBtn(this.attachmentsButton, view === SidebarView.ATTACHMENTS, this.attachmentsView); + toggleCheckedBtn(this.layersButton, view === SidebarView.LAYERS, this.layersView); + if (forceOpen && !this.isOpen) { + this.open(); + return; + } + if (forceRendering) { + this.onUpdateThumbnails(); + this.onToggled(); + } + if (isViewChanged) { + this.#dispatchEvent(); + } + } + open() { + if (this.isOpen) { + return; + } + this.isOpen = true; + toggleExpandedBtn(this.toggleButton, true); + this.outerContainer.classList.add("sidebarMoving", "sidebarOpen"); + if (this.active === SidebarView.THUMBS) { + this.onUpdateThumbnails(); + } + this.onToggled(); + this.#dispatchEvent(); + this.#hideUINotification(); + } + close(evt = null) { + if (!this.isOpen) { + return; + } + this.isOpen = false; + toggleExpandedBtn(this.toggleButton, false); + this.outerContainer.classList.add("sidebarMoving"); + this.outerContainer.classList.remove("sidebarOpen"); + this.onToggled(); + this.#dispatchEvent(); + if (evt?.detail > 0) { + this.toggleButton.blur(); + } + } + toggle(evt = null) { + if (this.isOpen) { + this.close(evt); + } else { + this.open(); + } + } + #dispatchEvent() { + if (this.isInitialViewSet) { + this.isInitialEventDispatched ||= true; + } + this.eventBus.dispatch("sidebarviewchanged", { + source: this, + view: this.visibleView + }); + } + #showUINotification() { + this.toggleButton.setAttribute("data-l10n-id", "pdfjs-toggle-sidebar-notification-button"); + if (!this.isOpen) { + this.toggleButton.classList.add(UI_NOTIFICATION_CLASS); + } + } + #hideUINotification(reset = false) { + if (this.isOpen || reset) { + this.toggleButton.classList.remove(UI_NOTIFICATION_CLASS); + } + if (reset) { + this.toggleButton.setAttribute("data-l10n-id", "pdfjs-toggle-sidebar-button"); + } + } + #addEventListeners() { + const { + eventBus, + outerContainer + } = this; + this.sidebarContainer.addEventListener("transitionend", evt => { + if (evt.target === this.sidebarContainer) { + outerContainer.classList.remove("sidebarMoving"); + eventBus.dispatch("resize", { + source: this + }); + } + }); + this.toggleButton.addEventListener("click", evt => { + this.toggle(evt); + }); + this.thumbnailButton.addEventListener("click", () => { + this.switchView(SidebarView.THUMBS); + }); + this.outlineButton.addEventListener("click", () => { + this.switchView(SidebarView.OUTLINE); + }); + this.outlineButton.addEventListener("dblclick", () => { + eventBus.dispatch("toggleoutlinetree", { + source: this + }); + }); + this.attachmentsButton.addEventListener("click", () => { + this.switchView(SidebarView.ATTACHMENTS); + }); + this.layersButton.addEventListener("click", () => { + this.switchView(SidebarView.LAYERS); + }); + this.layersButton.addEventListener("dblclick", () => { + eventBus.dispatch("resetlayers", { + source: this + }); + }); + this._currentOutlineItemButton.addEventListener("click", () => { + eventBus.dispatch("currentoutlineitem", { + source: this + }); + }); + const onTreeLoaded = (count, button, view) => { + button.disabled = !count; + if (count) { + this.#showUINotification(); + } else if (this.active === view) { + this.switchView(SidebarView.THUMBS); + } + }; + eventBus._on("outlineloaded", evt => { + onTreeLoaded(evt.outlineCount, this.outlineButton, SidebarView.OUTLINE); + evt.currentOutlineItemPromise.then(enabled => { + if (!this.isInitialViewSet) { + return; + } + this._currentOutlineItemButton.disabled = !enabled; + }); + }); + eventBus._on("attachmentsloaded", evt => { + onTreeLoaded(evt.attachmentsCount, this.attachmentsButton, SidebarView.ATTACHMENTS); + }); + eventBus._on("layersloaded", evt => { + onTreeLoaded(evt.layersCount, this.layersButton, SidebarView.LAYERS); + }); + eventBus._on("presentationmodechanged", evt => { + if (evt.state === PresentationModeState.NORMAL && this.visibleView === SidebarView.THUMBS) { + this.onUpdateThumbnails(); + } + }); + this.resizer.addEventListener("mousedown", evt => { + if (evt.button !== 0) { + return; + } + outerContainer.classList.add(SIDEBAR_RESIZING_CLASS); + this.#mouseAC = new AbortController(); + const opts = { + signal: this.#mouseAC.signal + }; + window.addEventListener("mousemove", this.#mouseMove.bind(this), opts); + window.addEventListener("mouseup", this.#mouseUp.bind(this), opts); + window.addEventListener("blur", this.#mouseUp.bind(this), opts); + }); + eventBus._on("resize", evt => { + if (evt.source !== window) { + return; + } + this.#outerContainerWidth = null; + if (!this.#width) { + return; + } + if (!this.isOpen) { + this.#updateWidth(this.#width); + return; + } + outerContainer.classList.add(SIDEBAR_RESIZING_CLASS); + const updated = this.#updateWidth(this.#width); + Promise.resolve().then(() => { + outerContainer.classList.remove(SIDEBAR_RESIZING_CLASS); + if (updated) { + eventBus.dispatch("resize", { + source: this + }); + } + }); + }); + } + get outerContainerWidth() { + return this.#outerContainerWidth ||= this.outerContainer.clientWidth; + } + #updateWidth(width = 0) { + const maxWidth = Math.floor(this.outerContainerWidth / 2); + if (width > maxWidth) { + width = maxWidth; + } + if (width < SIDEBAR_MIN_WIDTH) { + width = SIDEBAR_MIN_WIDTH; + } + if (width === this.#width) { + return false; + } + this.#width = width; + docStyle.setProperty(SIDEBAR_WIDTH_VAR, `${width}px`); + return true; + } + #mouseMove(evt) { + let width = evt.clientX; + if (this.#isRTL) { + width = this.outerContainerWidth - width; + } + this.#updateWidth(width); + } + #mouseUp(evt) { + this.outerContainer.classList.remove(SIDEBAR_RESIZING_CLASS); + this.eventBus.dispatch("resize", { + source: this + }); + this.#mouseAC?.abort(); + this.#mouseAC = null; + } +} + +;// ./web/pdf_thumbnail_view.js + + +const DRAW_UPSCALE_FACTOR = 2; +const MAX_NUM_SCALING_STEPS = 3; +const THUMBNAIL_WIDTH = 98; +class TempImageFactory { + static #tempCanvas = null; + static getCanvas(width, height) { + const tempCanvas = this.#tempCanvas ||= document.createElement("canvas"); + tempCanvas.width = width; + tempCanvas.height = height; + const ctx = tempCanvas.getContext("2d", { + alpha: false + }); + ctx.save(); + ctx.fillStyle = "rgb(255, 255, 255)"; + ctx.fillRect(0, 0, width, height); + ctx.restore(); + return [tempCanvas, tempCanvas.getContext("2d")]; + } + static destroyCanvas() { + const tempCanvas = this.#tempCanvas; + if (tempCanvas) { + tempCanvas.width = 0; + tempCanvas.height = 0; + } + this.#tempCanvas = null; + } +} +class PDFThumbnailView { + constructor({ + container, + eventBus, + id, + defaultViewport, + optionalContentConfigPromise, + linkService, + renderingQueue, + pageColors, + enableHWA + }) { + this.id = id; + this.renderingId = "thumbnail" + id; + this.pageLabel = null; + this.pdfPage = null; + this.rotation = 0; + this.viewport = defaultViewport; + this.pdfPageRotate = defaultViewport.rotation; + this._optionalContentConfigPromise = optionalContentConfigPromise || null; + this.pageColors = pageColors || null; + this.enableHWA = enableHWA || false; + this.eventBus = eventBus; + this.linkService = linkService; + this.renderingQueue = renderingQueue; + this.renderTask = null; + this.renderingState = RenderingStates.INITIAL; + this.resume = null; + const anchor = document.createElement("a"); + anchor.href = linkService.getAnchorUrl("#page=" + id); + anchor.setAttribute("data-l10n-id", "pdfjs-thumb-page-title"); + anchor.setAttribute("data-l10n-args", this.#pageL10nArgs); + anchor.onclick = function () { + linkService.goToPage(id); + return false; + }; + this.anchor = anchor; + const div = document.createElement("div"); + div.className = "thumbnail"; + div.setAttribute("data-page-number", this.id); + this.div = div; + this.#updateDims(); + const img = document.createElement("div"); + img.className = "thumbnailImage"; + this._placeholderImg = img; + div.append(img); + anchor.append(div); + container.append(anchor); + } + #updateDims() { + const { + width, + height + } = this.viewport; + const ratio = width / height; + this.canvasWidth = THUMBNAIL_WIDTH; + this.canvasHeight = this.canvasWidth / ratio | 0; + this.scale = this.canvasWidth / width; + const { + style + } = this.div; + style.setProperty("--thumbnail-width", `${this.canvasWidth}px`); + style.setProperty("--thumbnail-height", `${this.canvasHeight}px`); + } + setPdfPage(pdfPage) { + this.pdfPage = pdfPage; + this.pdfPageRotate = pdfPage.rotate; + const totalRotation = (this.rotation + this.pdfPageRotate) % 360; + this.viewport = pdfPage.getViewport({ + scale: 1, + rotation: totalRotation + }); + this.reset(); + } + reset() { + this.cancelRendering(); + this.renderingState = RenderingStates.INITIAL; + this.div.removeAttribute("data-loaded"); + this.image?.replaceWith(this._placeholderImg); + this.#updateDims(); + if (this.image) { + this.image.removeAttribute("src"); + delete this.image; + } + } + update({ + rotation = null + }) { + if (typeof rotation === "number") { + this.rotation = rotation; + } + const totalRotation = (this.rotation + this.pdfPageRotate) % 360; + this.viewport = this.viewport.clone({ + scale: 1, + rotation: totalRotation + }); + this.reset(); + } + cancelRendering() { + if (this.renderTask) { + this.renderTask.cancel(); + this.renderTask = null; + } + this.resume = null; + } + #getPageDrawContext(upscaleFactor = 1, enableHWA = this.enableHWA) { + const canvas = document.createElement("canvas"); + const ctx = canvas.getContext("2d", { + alpha: false, + willReadFrequently: !enableHWA + }); + const outputScale = new OutputScale(); + canvas.width = upscaleFactor * this.canvasWidth * outputScale.sx | 0; + canvas.height = upscaleFactor * this.canvasHeight * outputScale.sy | 0; + const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null; + return { + ctx, + canvas, + transform + }; + } + #convertCanvasToImage(canvas) { + if (this.renderingState !== RenderingStates.FINISHED) { + throw new Error("#convertCanvasToImage: Rendering has not finished."); + } + const reducedCanvas = this.#reduceImage(canvas); + const image = document.createElement("img"); + image.className = "thumbnailImage"; + image.setAttribute("data-l10n-id", "pdfjs-thumb-page-canvas"); + image.setAttribute("data-l10n-args", this.#pageL10nArgs); + image.src = reducedCanvas.toDataURL(); + this.image = image; + this.div.setAttribute("data-loaded", true); + this._placeholderImg.replaceWith(image); + reducedCanvas.width = 0; + reducedCanvas.height = 0; + } + async #finishRenderTask(renderTask, canvas, error = null) { + if (renderTask === this.renderTask) { + this.renderTask = null; + } + if (error instanceof RenderingCancelledException) { + return; + } + this.renderingState = RenderingStates.FINISHED; + this.#convertCanvasToImage(canvas); + if (error) { + throw error; + } + } + async draw() { + if (this.renderingState !== RenderingStates.INITIAL) { + console.error("Must be in new state before drawing"); + return undefined; + } + const { + pdfPage + } = this; + if (!pdfPage) { + this.renderingState = RenderingStates.FINISHED; + throw new Error("pdfPage is not loaded"); + } + this.renderingState = RenderingStates.RUNNING; + const { + ctx, + canvas, + transform + } = this.#getPageDrawContext(DRAW_UPSCALE_FACTOR); + const drawViewport = this.viewport.clone({ + scale: DRAW_UPSCALE_FACTOR * this.scale + }); + const renderContinueCallback = cont => { + if (!this.renderingQueue.isHighestPriority(this)) { + this.renderingState = RenderingStates.PAUSED; + this.resume = () => { + this.renderingState = RenderingStates.RUNNING; + cont(); + }; + return; + } + cont(); + }; + const renderContext = { + canvasContext: ctx, + transform, + viewport: drawViewport, + optionalContentConfigPromise: this._optionalContentConfigPromise, + pageColors: this.pageColors + }; + const renderTask = this.renderTask = pdfPage.render(renderContext); + renderTask.onContinue = renderContinueCallback; + const resultPromise = renderTask.promise.then(() => this.#finishRenderTask(renderTask, canvas), error => this.#finishRenderTask(renderTask, canvas, error)); + resultPromise.finally(() => { + canvas.width = 0; + canvas.height = 0; + this.eventBus.dispatch("thumbnailrendered", { + source: this, + pageNumber: this.id, + pdfPage: this.pdfPage + }); + }); + return resultPromise; + } + setImage(pageView) { + if (this.renderingState !== RenderingStates.INITIAL) { + return; + } + const { + thumbnailCanvas: canvas, + pdfPage, + scale + } = pageView; + if (!canvas) { + return; + } + if (!this.pdfPage) { + this.setPdfPage(pdfPage); + } + if (scale < this.scale) { + return; + } + this.renderingState = RenderingStates.FINISHED; + this.#convertCanvasToImage(canvas); + } + #reduceImage(img) { + const { + ctx, + canvas + } = this.#getPageDrawContext(1, true); + if (img.width <= 2 * canvas.width) { + ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height); + return canvas; + } + let reducedWidth = canvas.width << MAX_NUM_SCALING_STEPS; + let reducedHeight = canvas.height << MAX_NUM_SCALING_STEPS; + const [reducedImage, reducedImageCtx] = TempImageFactory.getCanvas(reducedWidth, reducedHeight); + while (reducedWidth > img.width || reducedHeight > img.height) { + reducedWidth >>= 1; + reducedHeight >>= 1; + } + reducedImageCtx.drawImage(img, 0, 0, img.width, img.height, 0, 0, reducedWidth, reducedHeight); + while (reducedWidth > 2 * canvas.width) { + reducedImageCtx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight, 0, 0, reducedWidth >> 1, reducedHeight >> 1); + reducedWidth >>= 1; + reducedHeight >>= 1; + } + ctx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight, 0, 0, canvas.width, canvas.height); + return canvas; + } + get #pageL10nArgs() { + return JSON.stringify({ + page: this.pageLabel ?? this.id + }); + } + setPageLabel(label) { + this.pageLabel = typeof label === "string" ? label : null; + this.anchor.setAttribute("data-l10n-args", this.#pageL10nArgs); + if (this.renderingState !== RenderingStates.FINISHED) { + return; + } + this.image?.setAttribute("data-l10n-args", this.#pageL10nArgs); + } +} + +;// ./web/pdf_thumbnail_viewer.js + + +const THUMBNAIL_SCROLL_MARGIN = -19; +const THUMBNAIL_SELECTED_CLASS = "selected"; +class PDFThumbnailViewer { + constructor({ + container, + eventBus, + linkService, + renderingQueue, + pageColors, + abortSignal, + enableHWA + }) { + this.container = container; + this.eventBus = eventBus; + this.linkService = linkService; + this.renderingQueue = renderingQueue; + this.pageColors = pageColors || null; + this.enableHWA = enableHWA || false; + this.scroll = watchScroll(this.container, this.#scrollUpdated.bind(this), abortSignal); + this.#resetView(); + } + #scrollUpdated() { + this.renderingQueue.renderHighestPriority(); + } + getThumbnail(index) { + return this._thumbnails[index]; + } + #getVisibleThumbs() { + return getVisibleElements({ + scrollEl: this.container, + views: this._thumbnails + }); + } + scrollThumbnailIntoView(pageNumber) { + if (!this.pdfDocument) { + return; + } + const thumbnailView = this._thumbnails[pageNumber - 1]; + if (!thumbnailView) { + console.error('scrollThumbnailIntoView: Invalid "pageNumber" parameter.'); + return; + } + if (pageNumber !== this._currentPageNumber) { + const prevThumbnailView = this._thumbnails[this._currentPageNumber - 1]; + prevThumbnailView.div.classList.remove(THUMBNAIL_SELECTED_CLASS); + thumbnailView.div.classList.add(THUMBNAIL_SELECTED_CLASS); + } + const { + first, + last, + views + } = this.#getVisibleThumbs(); + if (views.length > 0) { + let shouldScroll = false; + if (pageNumber <= first.id || pageNumber >= last.id) { + shouldScroll = true; + } else { + for (const { + id, + percent + } of views) { + if (id !== pageNumber) { + continue; + } + shouldScroll = percent < 100; + break; + } + } + if (shouldScroll) { + scrollIntoView(thumbnailView.div, { + top: THUMBNAIL_SCROLL_MARGIN + }); + } + } + this._currentPageNumber = pageNumber; + } + get pagesRotation() { + return this._pagesRotation; + } + set pagesRotation(rotation) { + if (!isValidRotation(rotation)) { + throw new Error("Invalid thumbnails rotation angle."); + } + if (!this.pdfDocument) { + return; + } + if (this._pagesRotation === rotation) { + return; + } + this._pagesRotation = rotation; + const updateArgs = { + rotation + }; + for (const thumbnail of this._thumbnails) { + thumbnail.update(updateArgs); + } + } + cleanup() { + for (const thumbnail of this._thumbnails) { + if (thumbnail.renderingState !== RenderingStates.FINISHED) { + thumbnail.reset(); + } + } + TempImageFactory.destroyCanvas(); + } + #resetView() { + this._thumbnails = []; + this._currentPageNumber = 1; + this._pageLabels = null; + this._pagesRotation = 0; + this.container.textContent = ""; + } + setDocument(pdfDocument) { + if (this.pdfDocument) { + this.#cancelRendering(); + this.#resetView(); + } + this.pdfDocument = pdfDocument; + if (!pdfDocument) { + return; + } + const firstPagePromise = pdfDocument.getPage(1); + const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig({ + intent: "display" + }); + firstPagePromise.then(firstPdfPage => { + const pagesCount = pdfDocument.numPages; + const viewport = firstPdfPage.getViewport({ + scale: 1 + }); + for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) { + const thumbnail = new PDFThumbnailView({ + container: this.container, + eventBus: this.eventBus, + id: pageNum, + defaultViewport: viewport.clone(), + optionalContentConfigPromise, + linkService: this.linkService, + renderingQueue: this.renderingQueue, + pageColors: this.pageColors, + enableHWA: this.enableHWA + }); + this._thumbnails.push(thumbnail); + } + this._thumbnails[0]?.setPdfPage(firstPdfPage); + const thumbnailView = this._thumbnails[this._currentPageNumber - 1]; + thumbnailView.div.classList.add(THUMBNAIL_SELECTED_CLASS); + }).catch(reason => { + console.error("Unable to initialize thumbnail viewer", reason); + }); + } + #cancelRendering() { + for (const thumbnail of this._thumbnails) { + thumbnail.cancelRendering(); + } + } + setPageLabels(labels) { + if (!this.pdfDocument) { + return; + } + if (!labels) { + this._pageLabels = null; + } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) { + this._pageLabels = null; + console.error("PDFThumbnailViewer_setPageLabels: Invalid page labels."); + } else { + this._pageLabels = labels; + } + for (let i = 0, ii = this._thumbnails.length; i < ii; i++) { + this._thumbnails[i].setPageLabel(this._pageLabels?.[i] ?? null); + } + } + async #ensurePdfPageLoaded(thumbView) { + if (thumbView.pdfPage) { + return thumbView.pdfPage; + } + try { + const pdfPage = await this.pdfDocument.getPage(thumbView.id); + if (!thumbView.pdfPage) { + thumbView.setPdfPage(pdfPage); + } + return pdfPage; + } catch (reason) { + console.error("Unable to get page for thumb view", reason); + return null; + } + } + #getScrollAhead(visible) { + if (visible.first?.id === 1) { + return true; + } else if (visible.last?.id === this._thumbnails.length) { + return false; + } + return this.scroll.down; + } + forceRendering() { + const visibleThumbs = this.#getVisibleThumbs(); + const scrollAhead = this.#getScrollAhead(visibleThumbs); + const thumbView = this.renderingQueue.getHighestPriority(visibleThumbs, this._thumbnails, scrollAhead); + if (thumbView) { + this.#ensurePdfPageLoaded(thumbView).then(() => { + this.renderingQueue.renderView(thumbView); + }); + return true; + } + return false; + } +} + +;// ./web/annotation_editor_layer_builder.js + + +class AnnotationEditorLayerBuilder { + #annotationLayer = null; + #drawLayer = null; + #onAppend = null; + #structTreeLayer = null; + #textLayer = null; + #uiManager; + constructor(options) { + this.pdfPage = options.pdfPage; + this.accessibilityManager = options.accessibilityManager; + this.l10n = options.l10n; + this.l10n ||= new genericl10n_GenericL10n(); + this.annotationEditorLayer = null; + this.div = null; + this._cancelled = false; + this.#uiManager = options.uiManager; + this.#annotationLayer = options.annotationLayer || null; + this.#textLayer = options.textLayer || null; + this.#drawLayer = options.drawLayer || null; + this.#onAppend = options.onAppend || null; + this.#structTreeLayer = options.structTreeLayer || null; + } + async render(viewport, intent = "display") { + if (intent !== "display") { + return; + } + if (this._cancelled) { + return; + } + const clonedViewport = viewport.clone({ + dontFlip: true + }); + if (this.div) { + this.annotationEditorLayer.update({ + viewport: clonedViewport + }); + this.show(); + return; + } + const div = this.div = document.createElement("div"); + div.className = "annotationEditorLayer"; + div.hidden = true; + div.dir = this.#uiManager.direction; + this.#onAppend?.(div); + this.annotationEditorLayer = new AnnotationEditorLayer({ + uiManager: this.#uiManager, + div, + structTreeLayer: this.#structTreeLayer, + accessibilityManager: this.accessibilityManager, + pageIndex: this.pdfPage.pageNumber - 1, + l10n: this.l10n, + viewport: clonedViewport, + annotationLayer: this.#annotationLayer, + textLayer: this.#textLayer, + drawLayer: this.#drawLayer + }); + const parameters = { + viewport: clonedViewport, + div, + annotations: null, + intent + }; + this.annotationEditorLayer.render(parameters); + this.show(); + } + cancel() { + this._cancelled = true; + if (!this.div) { + return; + } + this.annotationEditorLayer.destroy(); + } + hide() { + if (!this.div) { + return; + } + this.div.hidden = true; + } + show() { + if (!this.div || this.annotationEditorLayer.isInvisible) { + return; + } + this.div.hidden = false; + } +} + +;// ./web/annotation_layer_builder.js + + +class AnnotationLayerBuilder { + #onAppend = null; + #eventAbortController = null; + constructor({ + pdfPage, + linkService, + downloadManager, + annotationStorage = null, + imageResourcesPath = "", + renderForms = true, + enableScripting = false, + hasJSActionsPromise = null, + fieldObjectsPromise = null, + annotationCanvasMap = null, + accessibilityManager = null, + annotationEditorUIManager = null, + onAppend = null + }) { + this.pdfPage = pdfPage; + this.linkService = linkService; + this.downloadManager = downloadManager; + this.imageResourcesPath = imageResourcesPath; + this.renderForms = renderForms; + this.annotationStorage = annotationStorage; + this.enableScripting = enableScripting; + this._hasJSActionsPromise = hasJSActionsPromise || Promise.resolve(false); + this._fieldObjectsPromise = fieldObjectsPromise || Promise.resolve(null); + this._annotationCanvasMap = annotationCanvasMap; + this._accessibilityManager = accessibilityManager; + this._annotationEditorUIManager = annotationEditorUIManager; + this.#onAppend = onAppend; + this.annotationLayer = null; + this.div = null; + this._cancelled = false; + this._eventBus = linkService.eventBus; + } + async render(viewport, options, intent = "display") { + if (this.div) { + if (this._cancelled || !this.annotationLayer) { + return; + } + this.annotationLayer.update({ + viewport: viewport.clone({ + dontFlip: true + }) + }); + return; + } + const [annotations, hasJSActions, fieldObjects] = await Promise.all([this.pdfPage.getAnnotations({ + intent + }), this._hasJSActionsPromise, this._fieldObjectsPromise]); + if (this._cancelled) { + return; + } + const div = this.div = document.createElement("div"); + div.className = "annotationLayer"; + this.#onAppend?.(div); + if (annotations.length === 0) { + this.hide(); + return; + } + this.annotationLayer = new AnnotationLayer({ + div, + accessibilityManager: this._accessibilityManager, + annotationCanvasMap: this._annotationCanvasMap, + annotationEditorUIManager: this._annotationEditorUIManager, + page: this.pdfPage, + viewport: viewport.clone({ + dontFlip: true + }), + structTreeLayer: options?.structTreeLayer || null + }); + await this.annotationLayer.render({ + annotations, + imageResourcesPath: this.imageResourcesPath, + renderForms: this.renderForms, + linkService: this.linkService, + downloadManager: this.downloadManager, + annotationStorage: this.annotationStorage, + enableScripting: this.enableScripting, + hasJSActions, + fieldObjects + }); + if (this.linkService.isInPresentationMode) { + this.#updatePresentationModeState(PresentationModeState.FULLSCREEN); + } + if (!this.#eventAbortController) { + this.#eventAbortController = new AbortController(); + this._eventBus?._on("presentationmodechanged", evt => { + this.#updatePresentationModeState(evt.state); + }, { + signal: this.#eventAbortController.signal + }); + } + } + cancel() { + this._cancelled = true; + this.#eventAbortController?.abort(); + this.#eventAbortController = null; + } + hide() { + if (!this.div) { + return; + } + this.div.hidden = true; + } + hasEditableAnnotations() { + return !!this.annotationLayer?.hasEditableAnnotations(); + } + #updatePresentationModeState(state) { + if (!this.div) { + return; + } + let disableFormElements = false; + switch (state) { + case PresentationModeState.FULLSCREEN: + disableFormElements = true; + break; + case PresentationModeState.NORMAL: + break; + default: + return; + } + for (const section of this.div.childNodes) { + if (section.hasAttribute("data-internal-link")) { + continue; + } + section.inert = disableFormElements; + } + } +} + +;// ./web/draw_layer_builder.js + +class DrawLayerBuilder { + #drawLayer = null; + constructor(options) { + this.pageIndex = options.pageIndex; + } + async render(intent = "display") { + if (intent !== "display" || this.#drawLayer || this._cancelled) { + return; + } + this.#drawLayer = new DrawLayer({ + pageIndex: this.pageIndex + }); + } + cancel() { + this._cancelled = true; + if (!this.#drawLayer) { + return; + } + this.#drawLayer.destroy(); + this.#drawLayer = null; + } + setParent(parent) { + this.#drawLayer?.setParent(parent); + } + getDrawLayer() { + return this.#drawLayer; + } +} + +;// ./web/struct_tree_layer_builder.js + +const PDF_ROLE_TO_HTML_ROLE = { + Document: null, + DocumentFragment: null, + Part: "group", + Sect: "group", + Div: "group", + Aside: "note", + NonStruct: "none", + P: null, + H: "heading", + Title: null, + FENote: "note", + Sub: "group", + Lbl: null, + Span: null, + Em: null, + Strong: null, + Link: "link", + Annot: "note", + Form: "form", + Ruby: null, + RB: null, + RT: null, + RP: null, + Warichu: null, + WT: null, + WP: null, + L: "list", + LI: "listitem", + LBody: null, + Table: "table", + TR: "row", + TH: "columnheader", + TD: "cell", + THead: "columnheader", + TBody: null, + TFoot: null, + Caption: null, + Figure: "figure", + Formula: null, + Artifact: null +}; +const HEADING_PATTERN = /^H(\d+)$/; +class StructTreeLayerBuilder { + #promise; + #treeDom = null; + #treePromise; + #elementAttributes = new Map(); + #rawDims; + #elementsToAddToTextLayer = null; + constructor(pdfPage, rawDims) { + this.#promise = pdfPage.getStructTree(); + this.#rawDims = rawDims; + } + async render() { + if (this.#treePromise) { + return this.#treePromise; + } + const { + promise, + resolve, + reject + } = Promise.withResolvers(); + this.#treePromise = promise; + try { + this.#treeDom = this.#walk(await this.#promise); + } catch (ex) { + reject(ex); + } + this.#promise = null; + this.#treeDom?.classList.add("structTree"); + resolve(this.#treeDom); + return promise; + } + async getAriaAttributes(annotationId) { + try { + await this.render(); + return this.#elementAttributes.get(annotationId); + } catch {} + return null; + } + hide() { + if (this.#treeDom && !this.#treeDom.hidden) { + this.#treeDom.hidden = true; + } + } + show() { + if (this.#treeDom?.hidden) { + this.#treeDom.hidden = false; + } + } + #setAttributes(structElement, htmlElement) { + const { + alt, + id, + lang + } = structElement; + if (alt !== undefined) { + let added = false; + const label = removeNullCharacters(alt); + for (const child of structElement.children) { + if (child.type === "annotation") { + let attrs = this.#elementAttributes.get(child.id); + if (!attrs) { + attrs = new Map(); + this.#elementAttributes.set(child.id, attrs); + } + attrs.set("aria-label", label); + added = true; + } + } + if (!added) { + htmlElement.setAttribute("aria-label", label); + } + } + if (id !== undefined) { + htmlElement.setAttribute("aria-owns", id); + } + if (lang !== undefined) { + htmlElement.setAttribute("lang", removeNullCharacters(lang, true)); + } + } + #addImageInTextLayer(node, element) { + const { + alt, + bbox, + children + } = node; + const child = children?.[0]; + if (!this.#rawDims || !alt || !bbox || child?.type !== "content") { + return false; + } + const { + id + } = child; + if (!id) { + return false; + } + element.setAttribute("aria-owns", id); + const img = document.createElement("span"); + (this.#elementsToAddToTextLayer ||= new Map()).set(id, img); + img.setAttribute("role", "img"); + img.setAttribute("aria-label", removeNullCharacters(alt)); + const { + pageHeight, + pageX, + pageY + } = this.#rawDims; + const calc = "calc(var(--scale-factor)*"; + const { + style + } = img; + style.width = `${calc}${bbox[2] - bbox[0]}px)`; + style.height = `${calc}${bbox[3] - bbox[1]}px)`; + style.left = `${calc}${bbox[0] - pageX}px)`; + style.top = `${calc}${pageHeight - bbox[3] + pageY}px)`; + return true; + } + addElementsToTextLayer() { + if (!this.#elementsToAddToTextLayer) { + return; + } + for (const [id, img] of this.#elementsToAddToTextLayer) { + document.getElementById(id)?.append(img); + } + this.#elementsToAddToTextLayer.clear(); + this.#elementsToAddToTextLayer = null; + } + #walk(node) { + if (!node) { + return null; + } + const element = document.createElement("span"); + if ("role" in node) { + const { + role + } = node; + const match = role.match(HEADING_PATTERN); + if (match) { + element.setAttribute("role", "heading"); + element.setAttribute("aria-level", match[1]); + } else if (PDF_ROLE_TO_HTML_ROLE[role]) { + element.setAttribute("role", PDF_ROLE_TO_HTML_ROLE[role]); + } + if (role === "Figure" && this.#addImageInTextLayer(node, element)) { + return element; + } + } + this.#setAttributes(node, element); + if (node.children) { + if (node.children.length === 1 && "id" in node.children[0]) { + this.#setAttributes(node.children[0], element); + } else { + for (const kid of node.children) { + element.append(this.#walk(kid)); + } + } + } + return element; + } +} + +;// ./web/text_accessibility.js + +class TextAccessibilityManager { + #enabled = false; + #textChildren = null; + #textNodes = new Map(); + #waitingElements = new Map(); + setTextMapping(textDivs) { + this.#textChildren = textDivs; + } + static #compareElementPositions(e1, e2) { + const rect1 = e1.getBoundingClientRect(); + const rect2 = e2.getBoundingClientRect(); + if (rect1.width === 0 && rect1.height === 0) { + return +1; + } + if (rect2.width === 0 && rect2.height === 0) { + return -1; + } + const top1 = rect1.y; + const bot1 = rect1.y + rect1.height; + const mid1 = rect1.y + rect1.height / 2; + const top2 = rect2.y; + const bot2 = rect2.y + rect2.height; + const mid2 = rect2.y + rect2.height / 2; + if (mid1 <= top2 && mid2 >= bot1) { + return -1; + } + if (mid2 <= top1 && mid1 >= bot2) { + return +1; + } + const centerX1 = rect1.x + rect1.width / 2; + const centerX2 = rect2.x + rect2.width / 2; + return centerX1 - centerX2; + } + enable() { + if (this.#enabled) { + throw new Error("TextAccessibilityManager is already enabled."); + } + if (!this.#textChildren) { + throw new Error("Text divs and strings have not been set."); + } + this.#enabled = true; + this.#textChildren = this.#textChildren.slice(); + this.#textChildren.sort(TextAccessibilityManager.#compareElementPositions); + if (this.#textNodes.size > 0) { + const textChildren = this.#textChildren; + for (const [id, nodeIndex] of this.#textNodes) { + const element = document.getElementById(id); + if (!element) { + this.#textNodes.delete(id); + continue; + } + this.#addIdToAriaOwns(id, textChildren[nodeIndex]); + } + } + for (const [element, isRemovable] of this.#waitingElements) { + this.addPointerInTextLayer(element, isRemovable); + } + this.#waitingElements.clear(); + } + disable() { + if (!this.#enabled) { + return; + } + this.#waitingElements.clear(); + this.#textChildren = null; + this.#enabled = false; + } + removePointerInTextLayer(element) { + if (!this.#enabled) { + this.#waitingElements.delete(element); + return; + } + const children = this.#textChildren; + if (!children || children.length === 0) { + return; + } + const { + id + } = element; + const nodeIndex = this.#textNodes.get(id); + if (nodeIndex === undefined) { + return; + } + const node = children[nodeIndex]; + this.#textNodes.delete(id); + let owns = node.getAttribute("aria-owns"); + if (owns?.includes(id)) { + owns = owns.split(" ").filter(x => x !== id).join(" "); + if (owns) { + node.setAttribute("aria-owns", owns); + } else { + node.removeAttribute("aria-owns"); + node.setAttribute("role", "presentation"); + } + } + } + #addIdToAriaOwns(id, node) { + const owns = node.getAttribute("aria-owns"); + if (!owns?.includes(id)) { + node.setAttribute("aria-owns", owns ? `${owns} ${id}` : id); + } + node.removeAttribute("role"); + } + addPointerInTextLayer(element, isRemovable) { + const { + id + } = element; + if (!id) { + return null; + } + if (!this.#enabled) { + this.#waitingElements.set(element, isRemovable); + return null; + } + if (isRemovable) { + this.removePointerInTextLayer(element); + } + const children = this.#textChildren; + if (!children || children.length === 0) { + return null; + } + const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(element, node) < 0); + const nodeIndex = Math.max(0, index - 1); + const child = children[nodeIndex]; + this.#addIdToAriaOwns(id, child); + this.#textNodes.set(id, nodeIndex); + const parent = child.parentNode; + return parent?.classList.contains("markedContent") ? parent.id : null; + } + moveElementInDOM(container, element, contentElement, isRemovable) { + const id = this.addPointerInTextLayer(contentElement, isRemovable); + if (!container.hasChildNodes()) { + container.append(element); + return id; + } + const children = Array.from(container.childNodes).filter(node => node !== element); + if (children.length === 0) { + return id; + } + const elementToCompare = contentElement || element; + const index = binarySearchFirstItem(children, node => TextAccessibilityManager.#compareElementPositions(elementToCompare, node) < 0); + if (index === 0) { + children[0].before(element); + } else { + children[index - 1].after(element); + } + return id; + } +} + +;// ./web/text_highlighter.js +class TextHighlighter { + #eventAbortController = null; + constructor({ + findController, + eventBus, + pageIndex + }) { + this.findController = findController; + this.matches = []; + this.eventBus = eventBus; + this.pageIdx = pageIndex; + this.textDivs = null; + this.textContentItemsStr = null; + this.enabled = false; + } + setTextMapping(divs, texts) { + this.textDivs = divs; + this.textContentItemsStr = texts; + } + enable() { + if (!this.textDivs || !this.textContentItemsStr) { + throw new Error("Text divs and strings have not been set."); + } + if (this.enabled) { + throw new Error("TextHighlighter is already enabled."); + } + this.enabled = true; + if (!this.#eventAbortController) { + this.#eventAbortController = new AbortController(); + this.eventBus._on("updatetextlayermatches", evt => { + if (evt.pageIndex === this.pageIdx || evt.pageIndex === -1) { + this._updateMatches(); + } + }, { + signal: this.#eventAbortController.signal + }); + } + this._updateMatches(); + } + disable() { + if (!this.enabled) { + return; + } + this.enabled = false; + this.#eventAbortController?.abort(); + this.#eventAbortController = null; + this._updateMatches(true); + } + _convertMatches(matches, matchesLength) { + if (!matches) { + return []; + } + const { + textContentItemsStr + } = this; + let i = 0, + iIndex = 0; + const end = textContentItemsStr.length - 1; + const result = []; + for (let m = 0, mm = matches.length; m < mm; m++) { + let matchIdx = matches[m]; + while (i !== end && matchIdx >= iIndex + textContentItemsStr[i].length) { + iIndex += textContentItemsStr[i].length; + i++; + } + if (i === textContentItemsStr.length) { + console.error("Could not find a matching mapping"); + } + const match = { + begin: { + divIdx: i, + offset: matchIdx - iIndex + } + }; + matchIdx += matchesLength[m]; + while (i !== end && matchIdx > iIndex + textContentItemsStr[i].length) { + iIndex += textContentItemsStr[i].length; + i++; + } + match.end = { + divIdx: i, + offset: matchIdx - iIndex + }; + result.push(match); + } + return result; + } + _renderMatches(matches) { + if (matches.length === 0) { + return; + } + const { + findController, + pageIdx + } = this; + const { + textContentItemsStr, + textDivs + } = this; + const isSelectedPage = pageIdx === findController.selected.pageIdx; + const selectedMatchIdx = findController.selected.matchIdx; + const highlightAll = findController.state.highlightAll; + let prevEnd = null; + const infinity = { + divIdx: -1, + offset: undefined + }; + function beginText(begin, className) { + const divIdx = begin.divIdx; + textDivs[divIdx].textContent = ""; + return appendTextToDiv(divIdx, 0, begin.offset, className); + } + function appendTextToDiv(divIdx, fromOffset, toOffset, className) { + let div = textDivs[divIdx]; + if (div.nodeType === Node.TEXT_NODE) { + const span = document.createElement("span"); + div.before(span); + span.append(div); + textDivs[divIdx] = span; + div = span; + } + const content = textContentItemsStr[divIdx].substring(fromOffset, toOffset); + const node = document.createTextNode(content); + if (className) { + const span = document.createElement("span"); + span.className = `${className} appended`; + span.append(node); + div.append(span); + return className.includes("selected") ? span.offsetLeft : 0; + } + div.append(node); + return 0; + } + let i0 = selectedMatchIdx, + i1 = i0 + 1; + if (highlightAll) { + i0 = 0; + i1 = matches.length; + } else if (!isSelectedPage) { + return; + } + let lastDivIdx = -1; + let lastOffset = -1; + for (let i = i0; i < i1; i++) { + const match = matches[i]; + const begin = match.begin; + if (begin.divIdx === lastDivIdx && begin.offset === lastOffset) { + continue; + } + lastDivIdx = begin.divIdx; + lastOffset = begin.offset; + const end = match.end; + const isSelected = isSelectedPage && i === selectedMatchIdx; + const highlightSuffix = isSelected ? " selected" : ""; + let selectedLeft = 0; + if (!prevEnd || begin.divIdx !== prevEnd.divIdx) { + if (prevEnd !== null) { + appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); + } + beginText(begin); + } else { + appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset); + } + if (begin.divIdx === end.divIdx) { + selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, end.offset, "highlight" + highlightSuffix); + } else { + selectedLeft = appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, "highlight begin" + highlightSuffix); + for (let n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) { + textDivs[n0].className = "highlight middle" + highlightSuffix; + } + beginText(end, "highlight end" + highlightSuffix); + } + prevEnd = end; + if (isSelected) { + findController.scrollMatchIntoView({ + element: textDivs[begin.divIdx], + selectedLeft, + pageIndex: pageIdx, + matchIndex: selectedMatchIdx + }); + } + } + if (prevEnd) { + appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); + } + } + _updateMatches(reset = false) { + if (!this.enabled && !reset) { + return; + } + const { + findController, + matches, + pageIdx + } = this; + const { + textContentItemsStr, + textDivs + } = this; + let clearedUntilDivIdx = -1; + for (const match of matches) { + const begin = Math.max(clearedUntilDivIdx, match.begin.divIdx); + for (let n = begin, end = match.end.divIdx; n <= end; n++) { + const div = textDivs[n]; + div.textContent = textContentItemsStr[n]; + div.className = ""; + } + clearedUntilDivIdx = match.end.divIdx + 1; + } + if (!findController?.highlightMatches || reset) { + return; + } + const pageMatches = findController.pageMatches[pageIdx] || null; + const pageMatchesLength = findController.pageMatchesLength[pageIdx] || null; + this.matches = this._convertMatches(pageMatches, pageMatchesLength); + this._renderMatches(this.matches); + } +} + +;// ./web/text_layer_builder.js + + +class TextLayerBuilder { + #enablePermissions = false; + #onAppend = null; + #renderingDone = false; + #textLayer = null; + static #textLayers = new Map(); + static #selectionChangeAbortController = null; + constructor({ + pdfPage, + highlighter = null, + accessibilityManager = null, + enablePermissions = false, + onAppend = null + }) { + this.pdfPage = pdfPage; + this.highlighter = highlighter; + this.accessibilityManager = accessibilityManager; + this.#enablePermissions = enablePermissions === true; + this.#onAppend = onAppend; + this.div = document.createElement("div"); + this.div.tabIndex = 0; + this.div.className = "textLayer"; + } + async render(viewport, textContentParams = null) { + if (this.#renderingDone && this.#textLayer) { + this.#textLayer.update({ + viewport, + onBefore: this.hide.bind(this) + }); + this.show(); + return; + } + this.cancel(); + this.#textLayer = new TextLayer({ + textContentSource: this.pdfPage.streamTextContent(textContentParams || { + includeMarkedContent: true, + disableNormalization: true + }), + container: this.div, + viewport + }); + const { + textDivs, + textContentItemsStr + } = this.#textLayer; + this.highlighter?.setTextMapping(textDivs, textContentItemsStr); + this.accessibilityManager?.setTextMapping(textDivs); + await this.#textLayer.render(); + this.#renderingDone = true; + const endOfContent = document.createElement("div"); + endOfContent.className = "endOfContent"; + this.div.append(endOfContent); + this.#bindMouse(endOfContent); + this.#onAppend?.(this.div); + this.highlighter?.enable(); + this.accessibilityManager?.enable(); + } + hide() { + if (!this.div.hidden && this.#renderingDone) { + this.highlighter?.disable(); + this.div.hidden = true; + } + } + show() { + if (this.div.hidden && this.#renderingDone) { + this.div.hidden = false; + this.highlighter?.enable(); + } + } + cancel() { + this.#textLayer?.cancel(); + this.#textLayer = null; + this.highlighter?.disable(); + this.accessibilityManager?.disable(); + TextLayerBuilder.#removeGlobalSelectionListener(this.div); + } + #bindMouse(end) { + const { + div + } = this; + div.addEventListener("mousedown", () => { + div.classList.add("selecting"); + }); + div.addEventListener("copy", event => { + if (!this.#enablePermissions) { + const selection = document.getSelection(); + event.clipboardData.setData("text/plain", removeNullCharacters(normalizeUnicode(selection.toString()))); + } + stopEvent(event); + }); + TextLayerBuilder.#textLayers.set(div, end); + TextLayerBuilder.#enableGlobalSelectionListener(); + } + static #removeGlobalSelectionListener(textLayerDiv) { + this.#textLayers.delete(textLayerDiv); + if (this.#textLayers.size === 0) { + this.#selectionChangeAbortController?.abort(); + this.#selectionChangeAbortController = null; + } + } + static #enableGlobalSelectionListener() { + if (this.#selectionChangeAbortController) { + return; + } + this.#selectionChangeAbortController = new AbortController(); + const { + signal + } = this.#selectionChangeAbortController; + const reset = (end, textLayer) => { + textLayer.append(end); + end.style.width = ""; + end.style.height = ""; + textLayer.classList.remove("selecting"); + }; + let isPointerDown = false; + document.addEventListener("pointerdown", () => { + isPointerDown = true; + }, { + signal + }); + document.addEventListener("pointerup", () => { + isPointerDown = false; + this.#textLayers.forEach(reset); + }, { + signal + }); + window.addEventListener("blur", () => { + isPointerDown = false; + this.#textLayers.forEach(reset); + }, { + signal + }); + document.addEventListener("keyup", () => { + if (!isPointerDown) { + this.#textLayers.forEach(reset); + } + }, { + signal + }); + var isFirefox, prevRange; + document.addEventListener("selectionchange", () => { + const selection = document.getSelection(); + if (selection.rangeCount === 0) { + this.#textLayers.forEach(reset); + return; + } + const activeTextLayers = new Set(); + for (let i = 0; i < selection.rangeCount; i++) { + const range = selection.getRangeAt(i); + for (const textLayerDiv of this.#textLayers.keys()) { + if (!activeTextLayers.has(textLayerDiv) && range.intersectsNode(textLayerDiv)) { + activeTextLayers.add(textLayerDiv); + } + } + } + for (const [textLayerDiv, endDiv] of this.#textLayers) { + if (activeTextLayers.has(textLayerDiv)) { + textLayerDiv.classList.add("selecting"); + } else { + reset(endDiv, textLayerDiv); + } + } + isFirefox ??= getComputedStyle(this.#textLayers.values().next().value).getPropertyValue("-moz-user-select") === "none"; + if (isFirefox) { + return; + } + const range = selection.getRangeAt(0); + const modifyStart = prevRange && (range.compareBoundaryPoints(Range.END_TO_END, prevRange) === 0 || range.compareBoundaryPoints(Range.START_TO_END, prevRange) === 0); + let anchor = modifyStart ? range.startContainer : range.endContainer; + if (anchor.nodeType === Node.TEXT_NODE) { + anchor = anchor.parentNode; + } + const parentTextLayer = anchor.parentElement?.closest(".textLayer"); + const endDiv = this.#textLayers.get(parentTextLayer); + if (endDiv) { + endDiv.style.width = parentTextLayer.style.width; + endDiv.style.height = parentTextLayer.style.height; + anchor.parentElement.insertBefore(endDiv, modifyStart ? anchor : anchor.nextSibling); + } + prevRange = range.cloneRange(); + }, { + signal + }); + } +} + +;// ./web/pdf_page_view.js + + + + + + + + + + + + + +const DEFAULT_LAYER_PROPERTIES = null; +const LAYERS_ORDER = new Map([["canvasWrapper", 0], ["textLayer", 1], ["annotationLayer", 2], ["annotationEditorLayer", 3], ["xfaLayer", 3]]); +class PDFPageView { + #annotationMode = AnnotationMode.ENABLE_FORMS; + #enableHWA = false; + #hasRestrictedScaling = false; + #isEditing = false; + #layerProperties = null; + #loadingId = null; + #previousRotation = null; + #scaleRoundX = 1; + #scaleRoundY = 1; + #renderError = null; + #renderingState = RenderingStates.INITIAL; + #textLayerMode = TextLayerMode.ENABLE; + #useThumbnailCanvas = { + directDrawing: true, + initialOptionalContent: true, + regularAnnotations: true + }; + #viewportMap = new WeakMap(); + #layers = [null, null, null, null]; + constructor(options) { + const container = options.container; + const defaultViewport = options.defaultViewport; + this.id = options.id; + this.renderingId = "page" + this.id; + this.#layerProperties = options.layerProperties || DEFAULT_LAYER_PROPERTIES; + this.pdfPage = null; + this.pageLabel = null; + this.rotation = 0; + this.scale = options.scale || DEFAULT_SCALE; + this.viewport = defaultViewport; + this.pdfPageRotate = defaultViewport.rotation; + this._optionalContentConfigPromise = options.optionalContentConfigPromise || null; + this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE; + this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS; + this.imageResourcesPath = options.imageResourcesPath || ""; + this.maxCanvasPixels = options.maxCanvasPixels ?? AppOptions.get("maxCanvasPixels"); + this.pageColors = options.pageColors || null; + this.#enableHWA = options.enableHWA || false; + this.eventBus = options.eventBus; + this.renderingQueue = options.renderingQueue; + this.l10n = options.l10n; + this.l10n ||= new genericl10n_GenericL10n(); + this.renderTask = null; + this.resume = null; + this._isStandalone = !this.renderingQueue?.hasViewer(); + this._container = container; + this._annotationCanvasMap = null; + this.annotationLayer = null; + this.annotationEditorLayer = null; + this.textLayer = null; + this.zoomLayer = null; + this.xfaLayer = null; + this.structTreeLayer = null; + this.drawLayer = null; + const div = document.createElement("div"); + div.className = "page"; + div.setAttribute("data-page-number", this.id); + div.setAttribute("role", "region"); + div.setAttribute("data-l10n-id", "pdfjs-page-landmark"); + div.setAttribute("data-l10n-args", JSON.stringify({ + page: this.id + })); + this.div = div; + this.#setDimensions(); + container?.append(div); + if (this._isStandalone) { + container?.style.setProperty("--scale-factor", this.scale * PixelsPerInch.PDF_TO_CSS_UNITS); + if (this.pageColors?.background) { + container?.style.setProperty("--page-bg-color", this.pageColors.background); + } + const { + optionalContentConfigPromise + } = options; + if (optionalContentConfigPromise) { + optionalContentConfigPromise.then(optionalContentConfig => { + if (optionalContentConfigPromise !== this._optionalContentConfigPromise) { + return; + } + this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility; + }); + } + if (!options.l10n) { + this.l10n.translate(this.div); + } + } + } + #addLayer(div, name) { + const pos = LAYERS_ORDER.get(name); + const oldDiv = this.#layers[pos]; + this.#layers[pos] = div; + if (oldDiv) { + oldDiv.replaceWith(div); + return; + } + for (let i = pos - 1; i >= 0; i--) { + const layer = this.#layers[i]; + if (layer) { + layer.after(div); + return; + } + } + this.div.prepend(div); + } + get renderingState() { + return this.#renderingState; + } + set renderingState(state) { + if (state === this.#renderingState) { + return; + } + this.#renderingState = state; + if (this.#loadingId) { + clearTimeout(this.#loadingId); + this.#loadingId = null; + } + switch (state) { + case RenderingStates.PAUSED: + this.div.classList.remove("loading"); + break; + case RenderingStates.RUNNING: + this.div.classList.add("loadingIcon"); + this.#loadingId = setTimeout(() => { + this.div.classList.add("loading"); + this.#loadingId = null; + }, 0); + break; + case RenderingStates.INITIAL: + case RenderingStates.FINISHED: + this.div.classList.remove("loadingIcon", "loading"); + break; + } + } + #setDimensions() { + const { + viewport + } = this; + if (this.pdfPage) { + if (this.#previousRotation === viewport.rotation) { + return; + } + this.#previousRotation = viewport.rotation; + } + setLayerDimensions(this.div, viewport, true, false); + } + setPdfPage(pdfPage) { + if (this._isStandalone && (this.pageColors?.foreground === "CanvasText" || this.pageColors?.background === "Canvas")) { + this._container?.style.setProperty("--hcm-highlight-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight")); + this._container?.style.setProperty("--hcm-highlight-selected-filter", pdfPage.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "Highlight")); + } + this.pdfPage = pdfPage; + this.pdfPageRotate = pdfPage.rotate; + const totalRotation = (this.rotation + this.pdfPageRotate) % 360; + this.viewport = pdfPage.getViewport({ + scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS, + rotation: totalRotation + }); + this.#setDimensions(); + this.reset(); + } + destroy() { + this.reset(); + this.pdfPage?.cleanup(); + } + hasEditableAnnotations() { + return !!this.annotationLayer?.hasEditableAnnotations(); + } + get _textHighlighter() { + return shadow(this, "_textHighlighter", new TextHighlighter({ + pageIndex: this.id - 1, + eventBus: this.eventBus, + findController: this.#layerProperties.findController + })); + } + #dispatchLayerRendered(name, error) { + this.eventBus.dispatch(name, { + source: this, + pageNumber: this.id, + error + }); + } + async #renderAnnotationLayer() { + let error = null; + try { + await this.annotationLayer.render(this.viewport, { + structTreeLayer: this.structTreeLayer + }, "display"); + } catch (ex) { + console.error(`#renderAnnotationLayer: "${ex}".`); + error = ex; + } finally { + this.#dispatchLayerRendered("annotationlayerrendered", error); + } + } + async #renderAnnotationEditorLayer() { + let error = null; + try { + await this.annotationEditorLayer.render(this.viewport, "display"); + } catch (ex) { + console.error(`#renderAnnotationEditorLayer: "${ex}".`); + error = ex; + } finally { + this.#dispatchLayerRendered("annotationeditorlayerrendered", error); + } + } + async #renderDrawLayer() { + try { + await this.drawLayer.render("display"); + } catch (ex) { + console.error(`#renderDrawLayer: "${ex}".`); + } + } + async #renderXfaLayer() { + let error = null; + try { + const result = await this.xfaLayer.render(this.viewport, "display"); + if (result?.textDivs && this._textHighlighter) { + this.#buildXfaTextContentItems(result.textDivs); + } + } catch (ex) { + console.error(`#renderXfaLayer: "${ex}".`); + error = ex; + } finally { + if (this.xfaLayer?.div) { + this.l10n.pause(); + this.#addLayer(this.xfaLayer.div, "xfaLayer"); + this.l10n.resume(); + } + this.#dispatchLayerRendered("xfalayerrendered", error); + } + } + async #renderTextLayer() { + if (!this.textLayer) { + return; + } + let error = null; + try { + await this.textLayer.render(this.viewport); + } catch (ex) { + if (ex instanceof AbortException) { + return; + } + console.error(`#renderTextLayer: "${ex}".`); + error = ex; + } + this.#dispatchLayerRendered("textlayerrendered", error); + this.#renderStructTreeLayer(); + } + async #renderStructTreeLayer() { + if (!this.textLayer) { + return; + } + const treeDom = await this.structTreeLayer?.render(); + if (treeDom) { + this.l10n.pause(); + this.structTreeLayer?.addElementsToTextLayer(); + if (this.canvas && treeDom.parentNode !== this.canvas) { + this.canvas.append(treeDom); + } + this.l10n.resume(); + } + this.structTreeLayer?.show(); + } + async #buildXfaTextContentItems(textDivs) { + const text = await this.pdfPage.getTextContent(); + const items = []; + for (const item of text.items) { + items.push(item.str); + } + this._textHighlighter.setTextMapping(textDivs, items); + this._textHighlighter.enable(); + } + _resetZoomLayer(removeFromDOM = false) { + if (!this.zoomLayer) { + return; + } + const zoomLayerCanvas = this.zoomLayer.firstChild; + this.#viewportMap.delete(zoomLayerCanvas); + zoomLayerCanvas.width = 0; + zoomLayerCanvas.height = 0; + if (removeFromDOM) { + this.zoomLayer.remove(); + } + this.zoomLayer = null; + } + reset({ + keepZoomLayer = false, + keepAnnotationLayer = false, + keepAnnotationEditorLayer = false, + keepXfaLayer = false, + keepTextLayer = false + } = {}) { + this.cancelRendering({ + keepAnnotationLayer, + keepAnnotationEditorLayer, + keepXfaLayer, + keepTextLayer + }); + this.renderingState = RenderingStates.INITIAL; + const div = this.div; + const childNodes = div.childNodes, + zoomLayerNode = keepZoomLayer && this.zoomLayer || null, + annotationLayerNode = keepAnnotationLayer && this.annotationLayer?.div || null, + annotationEditorLayerNode = keepAnnotationEditorLayer && this.annotationEditorLayer?.div || null, + xfaLayerNode = keepXfaLayer && this.xfaLayer?.div || null, + textLayerNode = keepTextLayer && this.textLayer?.div || null; + for (let i = childNodes.length - 1; i >= 0; i--) { + const node = childNodes[i]; + switch (node) { + case zoomLayerNode: + case annotationLayerNode: + case annotationEditorLayerNode: + case xfaLayerNode: + case textLayerNode: + continue; + } + node.remove(); + const layerIndex = this.#layers.indexOf(node); + if (layerIndex >= 0) { + this.#layers[layerIndex] = null; + } + } + div.removeAttribute("data-loaded"); + if (annotationLayerNode) { + this.annotationLayer.hide(); + } + if (annotationEditorLayerNode) { + this.annotationEditorLayer.hide(); + } + if (xfaLayerNode) { + this.xfaLayer.hide(); + } + if (textLayerNode) { + this.textLayer.hide(); + } + this.structTreeLayer?.hide(); + if (!zoomLayerNode) { + if (this.canvas) { + this.#viewportMap.delete(this.canvas); + this.canvas.width = 0; + this.canvas.height = 0; + delete this.canvas; + } + this._resetZoomLayer(); + } + } + toggleEditingMode(isEditing) { + if (!this.hasEditableAnnotations()) { + return; + } + this.#isEditing = isEditing; + this.reset({ + keepZoomLayer: true, + keepAnnotationLayer: true, + keepAnnotationEditorLayer: true, + keepXfaLayer: true, + keepTextLayer: true + }); + } + update({ + scale = 0, + rotation = null, + optionalContentConfigPromise = null, + drawingDelay = -1 + }) { + this.scale = scale || this.scale; + if (typeof rotation === "number") { + this.rotation = rotation; + } + if (optionalContentConfigPromise instanceof Promise) { + this._optionalContentConfigPromise = optionalContentConfigPromise; + optionalContentConfigPromise.then(optionalContentConfig => { + if (optionalContentConfigPromise !== this._optionalContentConfigPromise) { + return; + } + this.#useThumbnailCanvas.initialOptionalContent = optionalContentConfig.hasInitialVisibility; + }); + } + this.#useThumbnailCanvas.directDrawing = true; + const totalRotation = (this.rotation + this.pdfPageRotate) % 360; + this.viewport = this.viewport.clone({ + scale: this.scale * PixelsPerInch.PDF_TO_CSS_UNITS, + rotation: totalRotation + }); + this.#setDimensions(); + if (this._isStandalone) { + this._container?.style.setProperty("--scale-factor", this.viewport.scale); + } + if (this.canvas) { + let onlyCssZoom = false; + if (this.#hasRestrictedScaling) { + if (this.maxCanvasPixels === 0) { + onlyCssZoom = true; + } else if (this.maxCanvasPixels > 0) { + const { + width, + height + } = this.viewport; + const { + sx, + sy + } = this.outputScale; + onlyCssZoom = (Math.floor(width) * sx | 0) * (Math.floor(height) * sy | 0) > this.maxCanvasPixels; + } + } + const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000; + if (postponeDrawing || onlyCssZoom) { + if (postponeDrawing && !onlyCssZoom && this.renderingState !== RenderingStates.FINISHED) { + this.cancelRendering({ + keepZoomLayer: true, + keepAnnotationLayer: true, + keepAnnotationEditorLayer: true, + keepXfaLayer: true, + keepTextLayer: true, + cancelExtraDelay: drawingDelay + }); + this.renderingState = RenderingStates.FINISHED; + this.#useThumbnailCanvas.directDrawing = false; + } + this.cssTransform({ + target: this.canvas, + redrawAnnotationLayer: true, + redrawAnnotationEditorLayer: true, + redrawXfaLayer: true, + redrawTextLayer: !postponeDrawing, + hideTextLayer: postponeDrawing + }); + if (postponeDrawing) { + return; + } + this.eventBus.dispatch("pagerendered", { + source: this, + pageNumber: this.id, + cssTransform: true, + timestamp: performance.now(), + error: this.#renderError + }); + return; + } + if (!this.zoomLayer && !this.canvas.hidden) { + this.zoomLayer = this.canvas.parentNode; + this.zoomLayer.style.position = "absolute"; + } + } + if (this.zoomLayer) { + this.cssTransform({ + target: this.zoomLayer.firstChild + }); + } + this.reset({ + keepZoomLayer: true, + keepAnnotationLayer: true, + keepAnnotationEditorLayer: true, + keepXfaLayer: true, + keepTextLayer: true + }); + } + cancelRendering({ + keepAnnotationLayer = false, + keepAnnotationEditorLayer = false, + keepXfaLayer = false, + keepTextLayer = false, + cancelExtraDelay = 0 + } = {}) { + if (this.renderTask) { + this.renderTask.cancel(cancelExtraDelay); + this.renderTask = null; + } + this.resume = null; + if (this.textLayer && (!keepTextLayer || !this.textLayer.div)) { + this.textLayer.cancel(); + this.textLayer = null; + } + if (this.annotationLayer && (!keepAnnotationLayer || !this.annotationLayer.div)) { + this.annotationLayer.cancel(); + this.annotationLayer = null; + this._annotationCanvasMap = null; + } + if (this.structTreeLayer && !this.textLayer) { + this.structTreeLayer = null; + } + if (this.annotationEditorLayer && (!keepAnnotationEditorLayer || !this.annotationEditorLayer.div)) { + if (this.drawLayer) { + this.drawLayer.cancel(); + this.drawLayer = null; + } + this.annotationEditorLayer.cancel(); + this.annotationEditorLayer = null; + } + if (this.xfaLayer && (!keepXfaLayer || !this.xfaLayer.div)) { + this.xfaLayer.cancel(); + this.xfaLayer = null; + this._textHighlighter?.disable(); + } + } + cssTransform({ + target, + redrawAnnotationLayer = false, + redrawAnnotationEditorLayer = false, + redrawXfaLayer = false, + redrawTextLayer = false, + hideTextLayer = false + }) { + if (!target.hasAttribute("zooming")) { + target.setAttribute("zooming", true); + const { + style + } = target; + style.width = style.height = ""; + } + const originalViewport = this.#viewportMap.get(target); + if (this.viewport !== originalViewport) { + const relativeRotation = this.viewport.rotation - originalViewport.rotation; + const absRotation = Math.abs(relativeRotation); + let scaleX = 1, + scaleY = 1; + if (absRotation === 90 || absRotation === 270) { + const { + width, + height + } = this.viewport; + scaleX = height / width; + scaleY = width / height; + } + target.style.transform = `rotate(${relativeRotation}deg) scale(${scaleX}, ${scaleY})`; + } + if (redrawAnnotationLayer && this.annotationLayer) { + this.#renderAnnotationLayer(); + } + if (redrawAnnotationEditorLayer && this.annotationEditorLayer) { + if (this.drawLayer) { + this.#renderDrawLayer(); + } + this.#renderAnnotationEditorLayer(); + } + if (redrawXfaLayer && this.xfaLayer) { + this.#renderXfaLayer(); + } + if (this.textLayer) { + if (hideTextLayer) { + this.textLayer.hide(); + this.structTreeLayer?.hide(); + } else if (redrawTextLayer) { + this.#renderTextLayer(); + } + } + } + get width() { + return this.viewport.width; + } + get height() { + return this.viewport.height; + } + getPagePoint(x, y) { + return this.viewport.convertToPdfPoint(x, y); + } + async #finishRenderTask(renderTask, error = null) { + if (renderTask === this.renderTask) { + this.renderTask = null; + } + if (error instanceof RenderingCancelledException) { + this.#renderError = null; + return; + } + this.#renderError = error; + this.renderingState = RenderingStates.FINISHED; + this._resetZoomLayer(true); + this.#useThumbnailCanvas.regularAnnotations = !renderTask.separateAnnots; + this.eventBus.dispatch("pagerendered", { + source: this, + pageNumber: this.id, + cssTransform: false, + timestamp: performance.now(), + error: this.#renderError + }); + if (error) { + throw error; + } + } + async draw() { + if (this.renderingState !== RenderingStates.INITIAL) { + console.error("Must be in new state before drawing"); + this.reset(); + } + const { + div, + l10n, + pageColors, + pdfPage, + viewport + } = this; + if (!pdfPage) { + this.renderingState = RenderingStates.FINISHED; + throw new Error("pdfPage is not loaded"); + } + this.renderingState = RenderingStates.RUNNING; + const canvasWrapper = document.createElement("div"); + canvasWrapper.classList.add("canvasWrapper"); + this.#addLayer(canvasWrapper, "canvasWrapper"); + if (!this.textLayer && this.#textLayerMode !== TextLayerMode.DISABLE && !pdfPage.isPureXfa) { + this._accessibilityManager ||= new TextAccessibilityManager(); + this.textLayer = new TextLayerBuilder({ + pdfPage, + highlighter: this._textHighlighter, + accessibilityManager: this._accessibilityManager, + enablePermissions: this.#textLayerMode === TextLayerMode.ENABLE_PERMISSIONS, + onAppend: textLayerDiv => { + this.l10n.pause(); + this.#addLayer(textLayerDiv, "textLayer"); + this.l10n.resume(); + } + }); + } + if (!this.annotationLayer && this.#annotationMode !== AnnotationMode.DISABLE) { + const { + annotationStorage, + annotationEditorUIManager, + downloadManager, + enableScripting, + fieldObjectsPromise, + hasJSActionsPromise, + linkService + } = this.#layerProperties; + this._annotationCanvasMap ||= new Map(); + this.annotationLayer = new AnnotationLayerBuilder({ + pdfPage, + annotationStorage, + imageResourcesPath: this.imageResourcesPath, + renderForms: this.#annotationMode === AnnotationMode.ENABLE_FORMS, + linkService, + downloadManager, + enableScripting, + hasJSActionsPromise, + fieldObjectsPromise, + annotationCanvasMap: this._annotationCanvasMap, + accessibilityManager: this._accessibilityManager, + annotationEditorUIManager, + onAppend: annotationLayerDiv => { + this.#addLayer(annotationLayerDiv, "annotationLayer"); + } + }); + } + const renderContinueCallback = cont => { + showCanvas?.(false); + if (this.renderingQueue && !this.renderingQueue.isHighestPriority(this)) { + this.renderingState = RenderingStates.PAUSED; + this.resume = () => { + this.renderingState = RenderingStates.RUNNING; + cont(); + }; + return; + } + cont(); + }; + const { + width, + height + } = viewport; + const canvas = document.createElement("canvas"); + canvas.setAttribute("role", "presentation"); + canvas.hidden = true; + const hasHCM = !!(pageColors?.background && pageColors?.foreground); + let showCanvas = isLastShow => { + if (!hasHCM || isLastShow) { + canvas.hidden = false; + showCanvas = null; + } + }; + canvasWrapper.append(canvas); + this.canvas = canvas; + const ctx = canvas.getContext("2d", { + alpha: false, + willReadFrequently: !this.#enableHWA + }); + const outputScale = this.outputScale = new OutputScale(); + if (this.maxCanvasPixels === 0) { + const invScale = 1 / this.scale; + outputScale.sx *= invScale; + outputScale.sy *= invScale; + this.#hasRestrictedScaling = true; + } else if (this.maxCanvasPixels > 0) { + const pixelsInViewport = width * height; + const maxScale = Math.sqrt(this.maxCanvasPixels / pixelsInViewport); + if (outputScale.sx > maxScale || outputScale.sy > maxScale) { + outputScale.sx = maxScale; + outputScale.sy = maxScale; + this.#hasRestrictedScaling = true; + } else { + this.#hasRestrictedScaling = false; + } + } + const sfx = approximateFraction(outputScale.sx); + const sfy = approximateFraction(outputScale.sy); + const canvasWidth = canvas.width = floorToDivide(calcRound(width * outputScale.sx), sfx[0]); + const canvasHeight = canvas.height = floorToDivide(calcRound(height * outputScale.sy), sfy[0]); + const pageWidth = floorToDivide(calcRound(width), sfx[1]); + const pageHeight = floorToDivide(calcRound(height), sfy[1]); + outputScale.sx = canvasWidth / pageWidth; + outputScale.sy = canvasHeight / pageHeight; + if (this.#scaleRoundX !== sfx[1]) { + div.style.setProperty("--scale-round-x", `${sfx[1]}px`); + this.#scaleRoundX = sfx[1]; + } + if (this.#scaleRoundY !== sfy[1]) { + div.style.setProperty("--scale-round-y", `${sfy[1]}px`); + this.#scaleRoundY = sfy[1]; + } + this.#viewportMap.set(canvas, viewport); + const transform = outputScale.scaled ? [outputScale.sx, 0, 0, outputScale.sy, 0, 0] : null; + const renderContext = { + canvasContext: ctx, + transform, + viewport, + annotationMode: this.#annotationMode, + optionalContentConfigPromise: this._optionalContentConfigPromise, + annotationCanvasMap: this._annotationCanvasMap, + pageColors, + isEditing: this.#isEditing + }; + const renderTask = this.renderTask = pdfPage.render(renderContext); + renderTask.onContinue = renderContinueCallback; + const resultPromise = renderTask.promise.then(async () => { + showCanvas?.(true); + await this.#finishRenderTask(renderTask); + this.structTreeLayer ||= new StructTreeLayerBuilder(pdfPage, viewport.rawDims); + this.#renderTextLayer(); + if (this.annotationLayer) { + await this.#renderAnnotationLayer(); + } + const { + annotationEditorUIManager + } = this.#layerProperties; + if (!annotationEditorUIManager) { + return; + } + this.drawLayer ||= new DrawLayerBuilder({ + pageIndex: this.id + }); + await this.#renderDrawLayer(); + this.drawLayer.setParent(canvasWrapper); + this.annotationEditorLayer ||= new AnnotationEditorLayerBuilder({ + uiManager: annotationEditorUIManager, + pdfPage, + l10n, + structTreeLayer: this.structTreeLayer, + accessibilityManager: this._accessibilityManager, + annotationLayer: this.annotationLayer?.annotationLayer, + textLayer: this.textLayer, + drawLayer: this.drawLayer.getDrawLayer(), + onAppend: annotationEditorLayerDiv => { + this.#addLayer(annotationEditorLayerDiv, "annotationEditorLayer"); + } + }); + this.#renderAnnotationEditorLayer(); + }, error => { + if (!(error instanceof RenderingCancelledException)) { + showCanvas?.(true); + } + return this.#finishRenderTask(renderTask, error); + }); + if (pdfPage.isPureXfa) { + if (!this.xfaLayer) { + const { + annotationStorage, + linkService + } = this.#layerProperties; + this.xfaLayer = new XfaLayerBuilder({ + pdfPage, + annotationStorage, + linkService + }); + } + this.#renderXfaLayer(); + } + div.setAttribute("data-loaded", true); + this.eventBus.dispatch("pagerender", { + source: this, + pageNumber: this.id + }); + return resultPromise; + } + setPageLabel(label) { + this.pageLabel = typeof label === "string" ? label : null; + this.div.setAttribute("data-l10n-args", JSON.stringify({ + page: this.pageLabel ?? this.id + })); + if (this.pageLabel !== null) { + this.div.setAttribute("data-page-label", this.pageLabel); + } else { + this.div.removeAttribute("data-page-label"); + } + } + get thumbnailCanvas() { + const { + directDrawing, + initialOptionalContent, + regularAnnotations + } = this.#useThumbnailCanvas; + return directDrawing && initialOptionalContent && regularAnnotations ? this.canvas : null; + } +} + +;// ./web/pdf_viewer.js + + + + + + +const DEFAULT_CACHE_SIZE = 10; +const PagesCountLimit = { + FORCE_SCROLL_MODE_PAGE: 10000, + FORCE_LAZY_PAGE_INIT: 5000, + PAUSE_EAGER_PAGE_INIT: 250 +}; +function isValidAnnotationEditorMode(mode) { + return Object.values(AnnotationEditorType).includes(mode) && mode !== AnnotationEditorType.DISABLE; +} +class PDFPageViewBuffer { + #buf = new Set(); + #size = 0; + constructor(size) { + this.#size = size; + } + push(view) { + const buf = this.#buf; + if (buf.has(view)) { + buf.delete(view); + } + buf.add(view); + if (buf.size > this.#size) { + this.#destroyFirstView(); + } + } + resize(newSize, idsToKeep = null) { + this.#size = newSize; + const buf = this.#buf; + if (idsToKeep) { + const ii = buf.size; + let i = 1; + for (const view of buf) { + if (idsToKeep.has(view.id)) { + buf.delete(view); + buf.add(view); + } + if (++i > ii) { + break; + } + } + } + while (buf.size > this.#size) { + this.#destroyFirstView(); + } + } + has(view) { + return this.#buf.has(view); + } + [Symbol.iterator]() { + return this.#buf.keys(); + } + #destroyFirstView() { + const firstView = this.#buf.keys().next().value; + firstView?.destroy(); + this.#buf.delete(firstView); + } +} +class PDFViewer { + #buffer = null; + #altTextManager = null; + #annotationEditorHighlightColors = null; + #annotationEditorMode = AnnotationEditorType.NONE; + #annotationEditorUIManager = null; + #annotationMode = AnnotationMode.ENABLE_FORMS; + #containerTopLeft = null; + #editorUndoBar = null; + #enableHWA = false; + #enableHighlightFloatingButton = false; + #enablePermissions = false; + #enableUpdatedAddImage = false; + #enableNewAltTextWhenAddingImage = false; + #eventAbortController = null; + #mlManager = null; + #switchAnnotationEditorModeAC = null; + #switchAnnotationEditorModeTimeoutId = null; + #getAllTextInProgress = false; + #hiddenCopyElement = null; + #interruptCopyCondition = false; + #previousContainerHeight = 0; + #resizeObserver = new ResizeObserver(this.#resizeObserverCallback.bind(this)); + #scrollModePageState = null; + #scaleTimeoutId = null; + #textLayerMode = TextLayerMode.ENABLE; + constructor(options) { + const viewerVersion = "4.9.155"; + if (version !== viewerVersion) { + throw new Error(`The API version "${version}" does not match the Viewer version "${viewerVersion}".`); + } + this.container = options.container; + this.viewer = options.viewer || options.container.firstElementChild; + if (this.container?.tagName !== "DIV" || this.viewer?.tagName !== "DIV") { + throw new Error("Invalid `container` and/or `viewer` option."); + } + if (this.container.offsetParent && getComputedStyle(this.container).position !== "absolute") { + throw new Error("The `container` must be absolutely positioned."); + } + this.#resizeObserver.observe(this.container); + this.eventBus = options.eventBus; + this.linkService = options.linkService || new SimpleLinkService(); + this.downloadManager = options.downloadManager || null; + this.findController = options.findController || null; + this.#altTextManager = options.altTextManager || null; + this.#editorUndoBar = options.editorUndoBar || null; + if (this.findController) { + this.findController.onIsPageVisible = pageNumber => this._getVisiblePages().ids.has(pageNumber); + } + this._scriptingManager = options.scriptingManager || null; + this.#textLayerMode = options.textLayerMode ?? TextLayerMode.ENABLE; + this.#annotationMode = options.annotationMode ?? AnnotationMode.ENABLE_FORMS; + this.#annotationEditorMode = options.annotationEditorMode ?? AnnotationEditorType.NONE; + this.#annotationEditorHighlightColors = options.annotationEditorHighlightColors || null; + this.#enableHighlightFloatingButton = options.enableHighlightFloatingButton === true; + this.#enableUpdatedAddImage = options.enableUpdatedAddImage === true; + this.#enableNewAltTextWhenAddingImage = options.enableNewAltTextWhenAddingImage === true; + this.imageResourcesPath = options.imageResourcesPath || ""; + this.enablePrintAutoRotate = options.enablePrintAutoRotate || false; + this.removePageBorders = options.removePageBorders || false; + this.maxCanvasPixels = options.maxCanvasPixels; + this.l10n = options.l10n; + this.l10n ||= new genericl10n_GenericL10n(); + this.#enablePermissions = options.enablePermissions || false; + this.pageColors = options.pageColors || null; + this.#mlManager = options.mlManager || null; + this.#enableHWA = options.enableHWA || false; + this.defaultRenderingQueue = !options.renderingQueue; + if (this.defaultRenderingQueue) { + this.renderingQueue = new PDFRenderingQueue(); + this.renderingQueue.setViewer(this); + } else { + this.renderingQueue = options.renderingQueue; + } + const { + abortSignal + } = options; + abortSignal?.addEventListener("abort", () => { + this.#resizeObserver.disconnect(); + this.#resizeObserver = null; + }, { + once: true + }); + this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this), abortSignal); + this.presentationModeState = PresentationModeState.UNKNOWN; + this._resetView(); + if (this.removePageBorders) { + this.viewer.classList.add("removePageBorders"); + } + this.#updateContainerHeightCss(); + this.eventBus._on("thumbnailrendered", ({ + pageNumber, + pdfPage + }) => { + const pageView = this._pages[pageNumber - 1]; + if (!this.#buffer.has(pageView)) { + pdfPage?.cleanup(); + } + }); + if (!options.l10n) { + this.l10n.translate(this.container); + } + } + get pagesCount() { + return this._pages.length; + } + getPageView(index) { + return this._pages[index]; + } + getCachedPageViews() { + return new Set(this.#buffer); + } + get pageViewsReady() { + return this._pages.every(pageView => pageView?.pdfPage); + } + get renderForms() { + return this.#annotationMode === AnnotationMode.ENABLE_FORMS; + } + get enableScripting() { + return !!this._scriptingManager; + } + get currentPageNumber() { + return this._currentPageNumber; + } + set currentPageNumber(val) { + if (!Number.isInteger(val)) { + throw new Error("Invalid page number."); + } + if (!this.pdfDocument) { + return; + } + if (!this._setCurrentPageNumber(val, true)) { + console.error(`currentPageNumber: "${val}" is not a valid page.`); + } + } + _setCurrentPageNumber(val, resetCurrentPageView = false) { + if (this._currentPageNumber === val) { + if (resetCurrentPageView) { + this.#resetCurrentPageView(); + } + return true; + } + if (!(0 < val && val <= this.pagesCount)) { + return false; + } + const previous = this._currentPageNumber; + this._currentPageNumber = val; + this.eventBus.dispatch("pagechanging", { + source: this, + pageNumber: val, + pageLabel: this._pageLabels?.[val - 1] ?? null, + previous + }); + if (resetCurrentPageView) { + this.#resetCurrentPageView(); + } + return true; + } + get currentPageLabel() { + return this._pageLabels?.[this._currentPageNumber - 1] ?? null; + } + set currentPageLabel(val) { + if (!this.pdfDocument) { + return; + } + let page = val | 0; + if (this._pageLabels) { + const i = this._pageLabels.indexOf(val); + if (i >= 0) { + page = i + 1; + } + } + if (!this._setCurrentPageNumber(page, true)) { + console.error(`currentPageLabel: "${val}" is not a valid page.`); + } + } + get currentScale() { + return this._currentScale !== UNKNOWN_SCALE ? this._currentScale : DEFAULT_SCALE; + } + set currentScale(val) { + if (isNaN(val)) { + throw new Error("Invalid numeric scale."); + } + if (!this.pdfDocument) { + return; + } + this.#setScale(val, { + noScroll: false + }); + } + get currentScaleValue() { + return this._currentScaleValue; + } + set currentScaleValue(val) { + if (!this.pdfDocument) { + return; + } + this.#setScale(val, { + noScroll: false + }); + } + get pagesRotation() { + return this._pagesRotation; + } + set pagesRotation(rotation) { + if (!isValidRotation(rotation)) { + throw new Error("Invalid pages rotation angle."); + } + if (!this.pdfDocument) { + return; + } + rotation %= 360; + if (rotation < 0) { + rotation += 360; + } + if (this._pagesRotation === rotation) { + return; + } + this._pagesRotation = rotation; + const pageNumber = this._currentPageNumber; + this.refresh(true, { + rotation + }); + if (this._currentScaleValue) { + this.#setScale(this._currentScaleValue, { + noScroll: true + }); + } + this.eventBus.dispatch("rotationchanging", { + source: this, + pagesRotation: rotation, + pageNumber + }); + if (this.defaultRenderingQueue) { + this.update(); + } + } + get firstPagePromise() { + return this.pdfDocument ? this._firstPageCapability.promise : null; + } + get onePageRendered() { + return this.pdfDocument ? this._onePageRenderedCapability.promise : null; + } + get pagesPromise() { + return this.pdfDocument ? this._pagesCapability.promise : null; + } + get _layerProperties() { + const self = this; + return shadow(this, "_layerProperties", { + get annotationEditorUIManager() { + return self.#annotationEditorUIManager; + }, + get annotationStorage() { + return self.pdfDocument?.annotationStorage; + }, + get downloadManager() { + return self.downloadManager; + }, + get enableScripting() { + return !!self._scriptingManager; + }, + get fieldObjectsPromise() { + return self.pdfDocument?.getFieldObjects(); + }, + get findController() { + return self.findController; + }, + get hasJSActionsPromise() { + return self.pdfDocument?.hasJSActions(); + }, + get linkService() { + return self.linkService; + } + }); + } + #initializePermissions(permissions) { + const params = { + annotationEditorMode: this.#annotationEditorMode, + annotationMode: this.#annotationMode, + textLayerMode: this.#textLayerMode + }; + if (!permissions) { + return params; + } + if (!permissions.includes(PermissionFlag.COPY) && this.#textLayerMode === TextLayerMode.ENABLE) { + params.textLayerMode = TextLayerMode.ENABLE_PERMISSIONS; + } + if (!permissions.includes(PermissionFlag.MODIFY_CONTENTS)) { + params.annotationEditorMode = AnnotationEditorType.DISABLE; + } + if (!permissions.includes(PermissionFlag.MODIFY_ANNOTATIONS) && !permissions.includes(PermissionFlag.FILL_INTERACTIVE_FORMS) && this.#annotationMode === AnnotationMode.ENABLE_FORMS) { + params.annotationMode = AnnotationMode.ENABLE; + } + return params; + } + async #onePageRenderedOrForceFetch(signal) { + if (document.visibilityState === "hidden" || !this.container.offsetParent || this._getVisiblePages().views.length === 0) { + return; + } + const hiddenCapability = Promise.withResolvers(), + ac = new AbortController(); + document.addEventListener("visibilitychange", () => { + if (document.visibilityState === "hidden") { + hiddenCapability.resolve(); + } + }, { + signal: typeof AbortSignal.any === "function" ? AbortSignal.any([signal, ac.signal]) : signal + }); + await Promise.race([this._onePageRenderedCapability.promise, hiddenCapability.promise]); + ac.abort(); + } + async getAllText() { + const texts = []; + const buffer = []; + for (let pageNum = 1, pagesCount = this.pdfDocument.numPages; pageNum <= pagesCount; ++pageNum) { + if (this.#interruptCopyCondition) { + return null; + } + buffer.length = 0; + const page = await this.pdfDocument.getPage(pageNum); + const { + items + } = await page.getTextContent(); + for (const item of items) { + if (item.str) { + buffer.push(item.str); + } + if (item.hasEOL) { + buffer.push("\n"); + } + } + texts.push(removeNullCharacters(buffer.join(""))); + } + return texts.join("\n"); + } + #copyCallback(textLayerMode, event) { + const selection = document.getSelection(); + const { + focusNode, + anchorNode + } = selection; + if (anchorNode && focusNode && selection.containsNode(this.#hiddenCopyElement)) { + if (this.#getAllTextInProgress || textLayerMode === TextLayerMode.ENABLE_PERMISSIONS) { + stopEvent(event); + return; + } + this.#getAllTextInProgress = true; + const { + classList + } = this.viewer; + classList.add("copyAll"); + const ac = new AbortController(); + window.addEventListener("keydown", ev => this.#interruptCopyCondition = ev.key === "Escape", { + signal: ac.signal + }); + this.getAllText().then(async text => { + if (text !== null) { + await navigator.clipboard.writeText(text); + } + }).catch(reason => { + console.warn(`Something goes wrong when extracting the text: ${reason.message}`); + }).finally(() => { + this.#getAllTextInProgress = false; + this.#interruptCopyCondition = false; + ac.abort(); + classList.remove("copyAll"); + }); + stopEvent(event); + } + } + setDocument(pdfDocument) { + if (this.pdfDocument) { + this.eventBus.dispatch("pagesdestroy", { + source: this + }); + this._cancelRendering(); + this._resetView(); + this.findController?.setDocument(null); + this._scriptingManager?.setDocument(null); + this.#annotationEditorUIManager?.destroy(); + this.#annotationEditorUIManager = null; + } + this.pdfDocument = pdfDocument; + if (!pdfDocument) { + return; + } + const pagesCount = pdfDocument.numPages; + const firstPagePromise = pdfDocument.getPage(1); + const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig({ + intent: "display" + }); + const permissionsPromise = this.#enablePermissions ? pdfDocument.getPermissions() : Promise.resolve(); + const { + eventBus, + pageColors, + viewer + } = this; + this.#eventAbortController = new AbortController(); + const { + signal + } = this.#eventAbortController; + if (pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) { + console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document."); + const mode = this._scrollMode = ScrollMode.PAGE; + eventBus.dispatch("scrollmodechanged", { + source: this, + mode + }); + } + this._pagesCapability.promise.then(() => { + eventBus.dispatch("pagesloaded", { + source: this, + pagesCount + }); + }, () => {}); + const onBeforeDraw = evt => { + const pageView = this._pages[evt.pageNumber - 1]; + if (!pageView) { + return; + } + this.#buffer.push(pageView); + }; + eventBus._on("pagerender", onBeforeDraw, { + signal + }); + const onAfterDraw = evt => { + if (evt.cssTransform) { + return; + } + this._onePageRenderedCapability.resolve({ + timestamp: evt.timestamp + }); + eventBus._off("pagerendered", onAfterDraw); + }; + eventBus._on("pagerendered", onAfterDraw, { + signal + }); + Promise.all([firstPagePromise, permissionsPromise]).then(([firstPdfPage, permissions]) => { + if (pdfDocument !== this.pdfDocument) { + return; + } + this._firstPageCapability.resolve(firstPdfPage); + this._optionalContentConfigPromise = optionalContentConfigPromise; + const { + annotationEditorMode, + annotationMode, + textLayerMode + } = this.#initializePermissions(permissions); + if (textLayerMode !== TextLayerMode.DISABLE) { + const element = this.#hiddenCopyElement = document.createElement("div"); + element.id = "hiddenCopyElement"; + viewer.before(element); + } + if (typeof AbortSignal.any === "function" && annotationEditorMode !== AnnotationEditorType.DISABLE) { + const mode = annotationEditorMode; + if (pdfDocument.isPureXfa) { + console.warn("Warning: XFA-editing is not implemented."); + } else if (isValidAnnotationEditorMode(mode)) { + this.#annotationEditorUIManager = new AnnotationEditorUIManager(this.container, viewer, this.#altTextManager, eventBus, pdfDocument, pageColors, this.#annotationEditorHighlightColors, this.#enableHighlightFloatingButton, this.#enableUpdatedAddImage, this.#enableNewAltTextWhenAddingImage, this.#mlManager, this.#editorUndoBar); + eventBus.dispatch("annotationeditoruimanager", { + source: this, + uiManager: this.#annotationEditorUIManager + }); + if (mode !== AnnotationEditorType.NONE) { + if (mode === AnnotationEditorType.STAMP) { + this.#mlManager?.loadModel("altText"); + } + this.#annotationEditorUIManager.updateMode(mode); + } + } else { + console.error(`Invalid AnnotationEditor mode: ${mode}`); + } + } + const viewerElement = this._scrollMode === ScrollMode.PAGE ? null : viewer; + const scale = this.currentScale; + const viewport = firstPdfPage.getViewport({ + scale: scale * PixelsPerInch.PDF_TO_CSS_UNITS + }); + viewer.style.setProperty("--scale-factor", viewport.scale); + if (pageColors?.background) { + viewer.style.setProperty("--page-bg-color", pageColors.background); + } + if (pageColors?.foreground === "CanvasText" || pageColors?.background === "Canvas") { + viewer.style.setProperty("--hcm-highlight-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight", "CanvasText", "Canvas", "HighlightText", "Highlight")); + viewer.style.setProperty("--hcm-highlight-selected-filter", pdfDocument.filterFactory.addHighlightHCMFilter("highlight_selected", "CanvasText", "Canvas", "HighlightText", "ButtonText")); + } + for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) { + const pageView = new PDFPageView({ + container: viewerElement, + eventBus, + id: pageNum, + scale, + defaultViewport: viewport.clone(), + optionalContentConfigPromise, + renderingQueue: this.renderingQueue, + textLayerMode, + annotationMode, + imageResourcesPath: this.imageResourcesPath, + maxCanvasPixels: this.maxCanvasPixels, + pageColors, + l10n: this.l10n, + layerProperties: this._layerProperties, + enableHWA: this.#enableHWA + }); + this._pages.push(pageView); + } + this._pages[0]?.setPdfPage(firstPdfPage); + if (this._scrollMode === ScrollMode.PAGE) { + this.#ensurePageViewVisible(); + } else if (this._spreadMode !== SpreadMode.NONE) { + this._updateSpreadMode(); + } + this.#onePageRenderedOrForceFetch(signal).then(async () => { + if (pdfDocument !== this.pdfDocument) { + return; + } + this.findController?.setDocument(pdfDocument); + this._scriptingManager?.setDocument(pdfDocument); + if (this.#hiddenCopyElement) { + document.addEventListener("copy", this.#copyCallback.bind(this, textLayerMode), { + signal + }); + } + if (this.#annotationEditorUIManager) { + eventBus.dispatch("annotationeditormodechanged", { + source: this, + mode: this.#annotationEditorMode + }); + } + if (pdfDocument.loadingParams.disableAutoFetch || pagesCount > PagesCountLimit.FORCE_LAZY_PAGE_INIT) { + this._pagesCapability.resolve(); + return; + } + let getPagesLeft = pagesCount - 1; + if (getPagesLeft <= 0) { + this._pagesCapability.resolve(); + return; + } + for (let pageNum = 2; pageNum <= pagesCount; ++pageNum) { + const promise = pdfDocument.getPage(pageNum).then(pdfPage => { + const pageView = this._pages[pageNum - 1]; + if (!pageView.pdfPage) { + pageView.setPdfPage(pdfPage); + } + if (--getPagesLeft === 0) { + this._pagesCapability.resolve(); + } + }, reason => { + console.error(`Unable to get page ${pageNum} to initialize viewer`, reason); + if (--getPagesLeft === 0) { + this._pagesCapability.resolve(); + } + }); + if (pageNum % PagesCountLimit.PAUSE_EAGER_PAGE_INIT === 0) { + await promise; + } + } + }); + eventBus.dispatch("pagesinit", { + source: this + }); + pdfDocument.getMetadata().then(({ + info + }) => { + if (pdfDocument !== this.pdfDocument) { + return; + } + if (info.Language) { + viewer.lang = info.Language; + } + }); + if (this.defaultRenderingQueue) { + this.update(); + } + }).catch(reason => { + console.error("Unable to initialize viewer", reason); + this._pagesCapability.reject(reason); + }); + } + setPageLabels(labels) { + if (!this.pdfDocument) { + return; + } + if (!labels) { + this._pageLabels = null; + } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) { + this._pageLabels = null; + console.error(`setPageLabels: Invalid page labels.`); + } else { + this._pageLabels = labels; + } + for (let i = 0, ii = this._pages.length; i < ii; i++) { + this._pages[i].setPageLabel(this._pageLabels?.[i] ?? null); + } + } + _resetView() { + this._pages = []; + this._currentPageNumber = 1; + this._currentScale = UNKNOWN_SCALE; + this._currentScaleValue = null; + this._pageLabels = null; + this.#buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE); + this._location = null; + this._pagesRotation = 0; + this._optionalContentConfigPromise = null; + this._firstPageCapability = Promise.withResolvers(); + this._onePageRenderedCapability = Promise.withResolvers(); + this._pagesCapability = Promise.withResolvers(); + this._scrollMode = ScrollMode.VERTICAL; + this._previousScrollMode = ScrollMode.UNKNOWN; + this._spreadMode = SpreadMode.NONE; + this.#scrollModePageState = { + previousPageNumber: 1, + scrollDown: true, + pages: [] + }; + this.#eventAbortController?.abort(); + this.#eventAbortController = null; + this.viewer.textContent = ""; + this._updateScrollMode(); + this.viewer.removeAttribute("lang"); + this.#hiddenCopyElement?.remove(); + this.#hiddenCopyElement = null; + this.#cleanupSwitchAnnotationEditorMode(); + } + #ensurePageViewVisible() { + if (this._scrollMode !== ScrollMode.PAGE) { + throw new Error("#ensurePageViewVisible: Invalid scrollMode value."); + } + const pageNumber = this._currentPageNumber, + state = this.#scrollModePageState, + viewer = this.viewer; + viewer.textContent = ""; + state.pages.length = 0; + if (this._spreadMode === SpreadMode.NONE && !this.isInPresentationMode) { + const pageView = this._pages[pageNumber - 1]; + viewer.append(pageView.div); + state.pages.push(pageView); + } else { + const pageIndexSet = new Set(), + parity = this._spreadMode - 1; + if (parity === -1) { + pageIndexSet.add(pageNumber - 1); + } else if (pageNumber % 2 !== parity) { + pageIndexSet.add(pageNumber - 1); + pageIndexSet.add(pageNumber); + } else { + pageIndexSet.add(pageNumber - 2); + pageIndexSet.add(pageNumber - 1); + } + const spread = document.createElement("div"); + spread.className = "spread"; + if (this.isInPresentationMode) { + const dummyPage = document.createElement("div"); + dummyPage.className = "dummyPage"; + spread.append(dummyPage); + } + for (const i of pageIndexSet) { + const pageView = this._pages[i]; + if (!pageView) { + continue; + } + spread.append(pageView.div); + state.pages.push(pageView); + } + viewer.append(spread); + } + state.scrollDown = pageNumber >= state.previousPageNumber; + state.previousPageNumber = pageNumber; + } + _scrollUpdate() { + if (this.pagesCount === 0) { + return; + } + this.update(); + } + #scrollIntoView(pageView, pageSpot = null) { + const { + div, + id + } = pageView; + if (this._currentPageNumber !== id) { + this._setCurrentPageNumber(id); + } + if (this._scrollMode === ScrollMode.PAGE) { + this.#ensurePageViewVisible(); + this.update(); + } + if (!pageSpot && !this.isInPresentationMode) { + const left = div.offsetLeft + div.clientLeft, + right = left + div.clientWidth; + const { + scrollLeft, + clientWidth + } = this.container; + if (this._scrollMode === ScrollMode.HORIZONTAL || left < scrollLeft || right > scrollLeft + clientWidth) { + pageSpot = { + left: 0, + top: 0 + }; + } + } + scrollIntoView(div, pageSpot); + if (!this._currentScaleValue && this._location) { + this._location = null; + } + } + #isSameScale(newScale) { + return newScale === this._currentScale || Math.abs(newScale - this._currentScale) < 1e-15; + } + #setScaleUpdatePages(newScale, newValue, { + noScroll = false, + preset = false, + drawingDelay = -1, + origin = null + }) { + this._currentScaleValue = newValue.toString(); + if (this.#isSameScale(newScale)) { + if (preset) { + this.eventBus.dispatch("scalechanging", { + source: this, + scale: newScale, + presetValue: newValue + }); + } + return; + } + this.viewer.style.setProperty("--scale-factor", newScale * PixelsPerInch.PDF_TO_CSS_UNITS); + const postponeDrawing = drawingDelay >= 0 && drawingDelay < 1000; + this.refresh(true, { + scale: newScale, + drawingDelay: postponeDrawing ? drawingDelay : -1 + }); + if (postponeDrawing) { + this.#scaleTimeoutId = setTimeout(() => { + this.#scaleTimeoutId = null; + this.refresh(); + }, drawingDelay); + } + const previousScale = this._currentScale; + this._currentScale = newScale; + if (!noScroll) { + let page = this._currentPageNumber, + dest; + if (this._location && !(this.isInPresentationMode || this.isChangingPresentationMode)) { + page = this._location.pageNumber; + dest = [null, { + name: "XYZ" + }, this._location.left, this._location.top, null]; + } + this.scrollPageIntoView({ + pageNumber: page, + destArray: dest, + allowNegativeOffset: true + }); + if (Array.isArray(origin)) { + const scaleDiff = newScale / previousScale - 1; + const [top, left] = this.containerTopLeft; + this.container.scrollLeft += (origin[0] - left) * scaleDiff; + this.container.scrollTop += (origin[1] - top) * scaleDiff; + } + } + this.eventBus.dispatch("scalechanging", { + source: this, + scale: newScale, + presetValue: preset ? newValue : undefined + }); + if (this.defaultRenderingQueue) { + this.update(); + } + } + get #pageWidthScaleFactor() { + if (this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL) { + return 2; + } + return 1; + } + #setScale(value, options) { + let scale = parseFloat(value); + if (scale > 0) { + options.preset = false; + this.#setScaleUpdatePages(scale, value, options); + } else { + const currentPage = this._pages[this._currentPageNumber - 1]; + if (!currentPage) { + return; + } + let hPadding = SCROLLBAR_PADDING, + vPadding = VERTICAL_PADDING; + if (this.isInPresentationMode) { + hPadding = vPadding = 4; + if (this._spreadMode !== SpreadMode.NONE) { + hPadding *= 2; + } + } else if (this.removePageBorders) { + hPadding = vPadding = 0; + } else if (this._scrollMode === ScrollMode.HORIZONTAL) { + [hPadding, vPadding] = [vPadding, hPadding]; + } + const pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale / this.#pageWidthScaleFactor; + const pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale; + switch (value) { + case "page-actual": + scale = 1; + break; + case "page-width": + scale = pageWidthScale; + break; + case "page-height": + scale = pageHeightScale; + break; + case "page-fit": + scale = Math.min(pageWidthScale, pageHeightScale); + break; + case "auto": + const horizontalScale = isPortraitOrientation(currentPage) ? pageWidthScale : Math.min(pageHeightScale, pageWidthScale); + scale = Math.min(MAX_AUTO_SCALE, horizontalScale); + break; + default: + console.error(`#setScale: "${value}" is an unknown zoom value.`); + return; + } + options.preset = true; + this.#setScaleUpdatePages(scale, value, options); + } + } + #resetCurrentPageView() { + const pageView = this._pages[this._currentPageNumber - 1]; + if (this.isInPresentationMode) { + this.#setScale(this._currentScaleValue, { + noScroll: true + }); + } + this.#scrollIntoView(pageView); + } + pageLabelToPageNumber(label) { + if (!this._pageLabels) { + return null; + } + const i = this._pageLabels.indexOf(label); + if (i < 0) { + return null; + } + return i + 1; + } + scrollPageIntoView({ + pageNumber, + destArray = null, + allowNegativeOffset = false, + ignoreDestinationZoom = false + }) { + if (!this.pdfDocument) { + return; + } + const pageView = Number.isInteger(pageNumber) && this._pages[pageNumber - 1]; + if (!pageView) { + console.error(`scrollPageIntoView: "${pageNumber}" is not a valid pageNumber parameter.`); + return; + } + if (this.isInPresentationMode || !destArray) { + this._setCurrentPageNumber(pageNumber, true); + return; + } + let x = 0, + y = 0; + let width = 0, + height = 0, + widthScale, + heightScale; + const changeOrientation = pageView.rotation % 180 !== 0; + const pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS; + const pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / PixelsPerInch.PDF_TO_CSS_UNITS; + let scale = 0; + switch (destArray[1].name) { + case "XYZ": + x = destArray[2]; + y = destArray[3]; + scale = destArray[4]; + x = x !== null ? x : 0; + y = y !== null ? y : pageHeight; + break; + case "Fit": + case "FitB": + scale = "page-fit"; + break; + case "FitH": + case "FitBH": + y = destArray[2]; + scale = "page-width"; + if (y === null && this._location) { + x = this._location.left; + y = this._location.top; + } else if (typeof y !== "number" || y < 0) { + y = pageHeight; + } + break; + case "FitV": + case "FitBV": + x = destArray[2]; + width = pageWidth; + height = pageHeight; + scale = "page-height"; + break; + case "FitR": + x = destArray[2]; + y = destArray[3]; + width = destArray[4] - x; + height = destArray[5] - y; + let hPadding = SCROLLBAR_PADDING, + vPadding = VERTICAL_PADDING; + if (this.removePageBorders) { + hPadding = vPadding = 0; + } + widthScale = (this.container.clientWidth - hPadding) / width / PixelsPerInch.PDF_TO_CSS_UNITS; + heightScale = (this.container.clientHeight - vPadding) / height / PixelsPerInch.PDF_TO_CSS_UNITS; + scale = Math.min(Math.abs(widthScale), Math.abs(heightScale)); + break; + default: + console.error(`scrollPageIntoView: "${destArray[1].name}" is not a valid destination type.`); + return; + } + if (!ignoreDestinationZoom) { + if (scale && scale !== this._currentScale) { + this.currentScaleValue = scale; + } else if (this._currentScale === UNKNOWN_SCALE) { + this.currentScaleValue = DEFAULT_SCALE_VALUE; + } + } + if (scale === "page-fit" && !destArray[4]) { + this.#scrollIntoView(pageView); + return; + } + const boundingRect = [pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height)]; + let left = Math.min(boundingRect[0][0], boundingRect[1][0]); + let top = Math.min(boundingRect[0][1], boundingRect[1][1]); + if (!allowNegativeOffset) { + left = Math.max(left, 0); + top = Math.max(top, 0); + } + this.#scrollIntoView(pageView, { + left, + top + }); + } + _updateLocation(firstPage) { + const currentScale = this._currentScale; + const currentScaleValue = this._currentScaleValue; + const normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue; + const pageNumber = firstPage.id; + const currentPageView = this._pages[pageNumber - 1]; + const container = this.container; + const topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y); + const intLeft = Math.round(topLeft[0]); + const intTop = Math.round(topLeft[1]); + let pdfOpenParams = `#page=${pageNumber}`; + if (!this.isInPresentationMode) { + pdfOpenParams += `&zoom=${normalizedScaleValue},${intLeft},${intTop}`; + } + this._location = { + pageNumber, + scale: normalizedScaleValue, + top: intTop, + left: intLeft, + rotation: this._pagesRotation, + pdfOpenParams + }; + } + update() { + const visible = this._getVisiblePages(); + const visiblePages = visible.views, + numVisiblePages = visiblePages.length; + if (numVisiblePages === 0) { + return; + } + const newCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * numVisiblePages + 1); + this.#buffer.resize(newCacheSize, visible.ids); + this.renderingQueue.renderHighestPriority(visible); + const isSimpleLayout = this._spreadMode === SpreadMode.NONE && (this._scrollMode === ScrollMode.PAGE || this._scrollMode === ScrollMode.VERTICAL); + const currentId = this._currentPageNumber; + let stillFullyVisible = false; + for (const page of visiblePages) { + if (page.percent < 100) { + break; + } + if (page.id === currentId && isSimpleLayout) { + stillFullyVisible = true; + break; + } + } + this._setCurrentPageNumber(stillFullyVisible ? currentId : visiblePages[0].id); + this._updateLocation(visible.first); + this.eventBus.dispatch("updateviewarea", { + source: this, + location: this._location + }); + } + #switchToEditAnnotationMode() { + const visible = this._getVisiblePages(); + const pagesToRefresh = []; + const { + ids, + views + } = visible; + for (const page of views) { + const { + view + } = page; + if (!view.hasEditableAnnotations()) { + ids.delete(view.id); + continue; + } + pagesToRefresh.push(page); + } + if (pagesToRefresh.length === 0) { + return null; + } + this.renderingQueue.renderHighestPriority({ + first: pagesToRefresh[0], + last: pagesToRefresh.at(-1), + views: pagesToRefresh, + ids + }); + return ids; + } + containsElement(element) { + return this.container.contains(element); + } + focus() { + this.container.focus(); + } + get _isContainerRtl() { + return getComputedStyle(this.container).direction === "rtl"; + } + get isInPresentationMode() { + return this.presentationModeState === PresentationModeState.FULLSCREEN; + } + get isChangingPresentationMode() { + return this.presentationModeState === PresentationModeState.CHANGING; + } + get isHorizontalScrollbarEnabled() { + return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth; + } + get isVerticalScrollbarEnabled() { + return this.isInPresentationMode ? false : this.container.scrollHeight > this.container.clientHeight; + } + _getVisiblePages() { + const views = this._scrollMode === ScrollMode.PAGE ? this.#scrollModePageState.pages : this._pages, + horizontal = this._scrollMode === ScrollMode.HORIZONTAL, + rtl = horizontal && this._isContainerRtl; + return getVisibleElements({ + scrollEl: this.container, + views, + sortByVisibility: true, + horizontal, + rtl + }); + } + cleanup() { + for (const pageView of this._pages) { + if (pageView.renderingState !== RenderingStates.FINISHED) { + pageView.reset(); + } + } + } + _cancelRendering() { + for (const pageView of this._pages) { + pageView.cancelRendering(); + } + } + async #ensurePdfPageLoaded(pageView) { + if (pageView.pdfPage) { + return pageView.pdfPage; + } + try { + const pdfPage = await this.pdfDocument.getPage(pageView.id); + if (!pageView.pdfPage) { + pageView.setPdfPage(pdfPage); + } + return pdfPage; + } catch (reason) { + console.error("Unable to get page for page view", reason); + return null; + } + } + #getScrollAhead(visible) { + if (visible.first?.id === 1) { + return true; + } else if (visible.last?.id === this.pagesCount) { + return false; + } + switch (this._scrollMode) { + case ScrollMode.PAGE: + return this.#scrollModePageState.scrollDown; + case ScrollMode.HORIZONTAL: + return this.scroll.right; + } + return this.scroll.down; + } + forceRendering(currentlyVisiblePages) { + const visiblePages = currentlyVisiblePages || this._getVisiblePages(); + const scrollAhead = this.#getScrollAhead(visiblePages); + const preRenderExtra = this._spreadMode !== SpreadMode.NONE && this._scrollMode !== ScrollMode.HORIZONTAL; + const pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, scrollAhead, preRenderExtra); + if (pageView) { + this.#ensurePdfPageLoaded(pageView).then(() => { + this.renderingQueue.renderView(pageView); + }); + return true; + } + return false; + } + get hasEqualPageSizes() { + const firstPageView = this._pages[0]; + for (let i = 1, ii = this._pages.length; i < ii; ++i) { + const pageView = this._pages[i]; + if (pageView.width !== firstPageView.width || pageView.height !== firstPageView.height) { + return false; + } + } + return true; + } + getPagesOverview() { + let initialOrientation; + return this._pages.map(pageView => { + const viewport = pageView.pdfPage.getViewport({ + scale: 1 + }); + const orientation = isPortraitOrientation(viewport); + if (initialOrientation === undefined) { + initialOrientation = orientation; + } else if (this.enablePrintAutoRotate && orientation !== initialOrientation) { + return { + width: viewport.height, + height: viewport.width, + rotation: (viewport.rotation - 90) % 360 + }; + } + return { + width: viewport.width, + height: viewport.height, + rotation: viewport.rotation + }; + }); + } + get optionalContentConfigPromise() { + if (!this.pdfDocument) { + return Promise.resolve(null); + } + if (!this._optionalContentConfigPromise) { + console.error("optionalContentConfigPromise: Not initialized yet."); + return this.pdfDocument.getOptionalContentConfig({ + intent: "display" + }); + } + return this._optionalContentConfigPromise; + } + set optionalContentConfigPromise(promise) { + if (!(promise instanceof Promise)) { + throw new Error(`Invalid optionalContentConfigPromise: ${promise}`); + } + if (!this.pdfDocument) { + return; + } + if (!this._optionalContentConfigPromise) { + return; + } + this._optionalContentConfigPromise = promise; + this.refresh(false, { + optionalContentConfigPromise: promise + }); + this.eventBus.dispatch("optionalcontentconfigchanged", { + source: this, + promise + }); + } + get scrollMode() { + return this._scrollMode; + } + set scrollMode(mode) { + if (this._scrollMode === mode) { + return; + } + if (!isValidScrollMode(mode)) { + throw new Error(`Invalid scroll mode: ${mode}`); + } + if (this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) { + return; + } + this._previousScrollMode = this._scrollMode; + this._scrollMode = mode; + this.eventBus.dispatch("scrollmodechanged", { + source: this, + mode + }); + this._updateScrollMode(this._currentPageNumber); + } + _updateScrollMode(pageNumber = null) { + const scrollMode = this._scrollMode, + viewer = this.viewer; + viewer.classList.toggle("scrollHorizontal", scrollMode === ScrollMode.HORIZONTAL); + viewer.classList.toggle("scrollWrapped", scrollMode === ScrollMode.WRAPPED); + if (!this.pdfDocument || !pageNumber) { + return; + } + if (scrollMode === ScrollMode.PAGE) { + this.#ensurePageViewVisible(); + } else if (this._previousScrollMode === ScrollMode.PAGE) { + this._updateSpreadMode(); + } + if (this._currentScaleValue && isNaN(this._currentScaleValue)) { + this.#setScale(this._currentScaleValue, { + noScroll: true + }); + } + this._setCurrentPageNumber(pageNumber, true); + this.update(); + } + get spreadMode() { + return this._spreadMode; + } + set spreadMode(mode) { + if (this._spreadMode === mode) { + return; + } + if (!isValidSpreadMode(mode)) { + throw new Error(`Invalid spread mode: ${mode}`); + } + this._spreadMode = mode; + this.eventBus.dispatch("spreadmodechanged", { + source: this, + mode + }); + this._updateSpreadMode(this._currentPageNumber); + } + _updateSpreadMode(pageNumber = null) { + if (!this.pdfDocument) { + return; + } + const viewer = this.viewer, + pages = this._pages; + if (this._scrollMode === ScrollMode.PAGE) { + this.#ensurePageViewVisible(); + } else { + viewer.textContent = ""; + if (this._spreadMode === SpreadMode.NONE) { + for (const pageView of this._pages) { + viewer.append(pageView.div); + } + } else { + const parity = this._spreadMode - 1; + let spread = null; + for (let i = 0, ii = pages.length; i < ii; ++i) { + if (spread === null) { + spread = document.createElement("div"); + spread.className = "spread"; + viewer.append(spread); + } else if (i % 2 === parity) { + spread = spread.cloneNode(false); + viewer.append(spread); + } + spread.append(pages[i].div); + } + } + } + if (!pageNumber) { + return; + } + if (this._currentScaleValue && isNaN(this._currentScaleValue)) { + this.#setScale(this._currentScaleValue, { + noScroll: true + }); + } + this._setCurrentPageNumber(pageNumber, true); + this.update(); + } + _getPageAdvance(currentPageNumber, previous = false) { + switch (this._scrollMode) { + case ScrollMode.WRAPPED: + { + const { + views + } = this._getVisiblePages(), + pageLayout = new Map(); + for (const { + id, + y, + percent, + widthPercent + } of views) { + if (percent === 0 || widthPercent < 100) { + continue; + } + let yArray = pageLayout.get(y); + if (!yArray) { + pageLayout.set(y, yArray ||= []); + } + yArray.push(id); + } + for (const yArray of pageLayout.values()) { + const currentIndex = yArray.indexOf(currentPageNumber); + if (currentIndex === -1) { + continue; + } + const numPages = yArray.length; + if (numPages === 1) { + break; + } + if (previous) { + for (let i = currentIndex - 1, ii = 0; i >= ii; i--) { + const currentId = yArray[i], + expectedId = yArray[i + 1] - 1; + if (currentId < expectedId) { + return currentPageNumber - expectedId; + } + } + } else { + for (let i = currentIndex + 1, ii = numPages; i < ii; i++) { + const currentId = yArray[i], + expectedId = yArray[i - 1] + 1; + if (currentId > expectedId) { + return expectedId - currentPageNumber; + } + } + } + if (previous) { + const firstId = yArray[0]; + if (firstId < currentPageNumber) { + return currentPageNumber - firstId + 1; + } + } else { + const lastId = yArray[numPages - 1]; + if (lastId > currentPageNumber) { + return lastId - currentPageNumber + 1; + } + } + break; + } + break; + } + case ScrollMode.HORIZONTAL: + { + break; + } + case ScrollMode.PAGE: + case ScrollMode.VERTICAL: + { + if (this._spreadMode === SpreadMode.NONE) { + break; + } + const parity = this._spreadMode - 1; + if (previous && currentPageNumber % 2 !== parity) { + break; + } else if (!previous && currentPageNumber % 2 === parity) { + break; + } + const { + views + } = this._getVisiblePages(), + expectedId = previous ? currentPageNumber - 1 : currentPageNumber + 1; + for (const { + id, + percent, + widthPercent + } of views) { + if (id !== expectedId) { + continue; + } + if (percent > 0 && widthPercent === 100) { + return 2; + } + break; + } + break; + } + } + return 1; + } + nextPage() { + const currentPageNumber = this._currentPageNumber, + pagesCount = this.pagesCount; + if (currentPageNumber >= pagesCount) { + return false; + } + const advance = this._getPageAdvance(currentPageNumber, false) || 1; + this.currentPageNumber = Math.min(currentPageNumber + advance, pagesCount); + return true; + } + previousPage() { + const currentPageNumber = this._currentPageNumber; + if (currentPageNumber <= 1) { + return false; + } + const advance = this._getPageAdvance(currentPageNumber, true) || 1; + this.currentPageNumber = Math.max(currentPageNumber - advance, 1); + return true; + } + updateScale({ + drawingDelay, + scaleFactor = null, + steps = null, + origin + }) { + if (steps === null && scaleFactor === null) { + throw new Error("Invalid updateScale options: either `steps` or `scaleFactor` must be provided."); + } + if (!this.pdfDocument) { + return; + } + let newScale = this._currentScale; + if (scaleFactor > 0 && scaleFactor !== 1) { + newScale = Math.round(newScale * scaleFactor * 100) / 100; + } else if (steps) { + const delta = steps > 0 ? DEFAULT_SCALE_DELTA : 1 / DEFAULT_SCALE_DELTA; + const round = steps > 0 ? Math.ceil : Math.floor; + steps = Math.abs(steps); + do { + newScale = round((newScale * delta).toFixed(2) * 10) / 10; + } while (--steps > 0); + } + newScale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, newScale)); + this.#setScale(newScale, { + noScroll: false, + drawingDelay, + origin + }); + } + increaseScale(options = {}) { + this.updateScale({ + ...options, + steps: options.steps ?? 1 + }); + } + decreaseScale(options = {}) { + this.updateScale({ + ...options, + steps: -(options.steps ?? 1) + }); + } + #updateContainerHeightCss(height = this.container.clientHeight) { + if (height !== this.#previousContainerHeight) { + this.#previousContainerHeight = height; + docStyle.setProperty("--viewer-container-height", `${height}px`); + } + } + #resizeObserverCallback(entries) { + for (const entry of entries) { + if (entry.target === this.container) { + this.#updateContainerHeightCss(Math.floor(entry.borderBoxSize[0].blockSize)); + this.#containerTopLeft = null; + break; + } + } + } + get containerTopLeft() { + return this.#containerTopLeft ||= [this.container.offsetTop, this.container.offsetLeft]; + } + #cleanupSwitchAnnotationEditorMode() { + this.#switchAnnotationEditorModeAC?.abort(); + this.#switchAnnotationEditorModeAC = null; + if (this.#switchAnnotationEditorModeTimeoutId !== null) { + clearTimeout(this.#switchAnnotationEditorModeTimeoutId); + this.#switchAnnotationEditorModeTimeoutId = null; + } + } + get annotationEditorMode() { + return this.#annotationEditorUIManager ? this.#annotationEditorMode : AnnotationEditorType.DISABLE; + } + set annotationEditorMode({ + mode, + editId = null, + isFromKeyboard = false + }) { + if (!this.#annotationEditorUIManager) { + throw new Error(`The AnnotationEditor is not enabled.`); + } + if (this.#annotationEditorMode === mode) { + return; + } + if (!isValidAnnotationEditorMode(mode)) { + throw new Error(`Invalid AnnotationEditor mode: ${mode}`); + } + if (!this.pdfDocument) { + return; + } + if (mode === AnnotationEditorType.STAMP) { + this.#mlManager?.loadModel("altText"); + } + const { + eventBus + } = this; + const updater = () => { + this.#cleanupSwitchAnnotationEditorMode(); + this.#annotationEditorMode = mode; + this.#annotationEditorUIManager.updateMode(mode, editId, isFromKeyboard); + eventBus.dispatch("annotationeditormodechanged", { + source: this, + mode + }); + }; + if (mode === AnnotationEditorType.NONE || this.#annotationEditorMode === AnnotationEditorType.NONE) { + const isEditing = mode !== AnnotationEditorType.NONE; + if (!isEditing) { + this.pdfDocument.annotationStorage.resetModifiedIds(); + } + for (const pageView of this._pages) { + pageView.toggleEditingMode(isEditing); + } + const idsToRefresh = this.#switchToEditAnnotationMode(); + if (isEditing && idsToRefresh) { + this.#cleanupSwitchAnnotationEditorMode(); + this.#switchAnnotationEditorModeAC = new AbortController(); + const signal = AbortSignal.any([this.#eventAbortController.signal, this.#switchAnnotationEditorModeAC.signal]); + eventBus._on("pagerendered", ({ + pageNumber + }) => { + idsToRefresh.delete(pageNumber); + if (idsToRefresh.size === 0) { + this.#switchAnnotationEditorModeTimeoutId = setTimeout(updater, 0); + } + }, { + signal + }); + return; + } + } + updater(); + } + refresh(noUpdate = false, updateArgs = Object.create(null)) { + if (!this.pdfDocument) { + return; + } + for (const pageView of this._pages) { + pageView.update(updateArgs); + } + if (this.#scaleTimeoutId !== null) { + clearTimeout(this.#scaleTimeoutId); + this.#scaleTimeoutId = null; + } + if (!noUpdate) { + this.update(); + } + } +} + +;// ./web/secondary_toolbar.js + + +class SecondaryToolbar { + #opts; + constructor(options, eventBus) { + this.#opts = options; + const buttons = [{ + element: options.presentationModeButton, + eventName: "presentationmode", + close: true + }, { + element: options.printButton, + eventName: "print", + close: true + }, { + element: options.downloadButton, + eventName: "download", + close: true + }, { + element: options.viewBookmarkButton, + eventName: null, + close: true + }, { + element: options.firstPageButton, + eventName: "firstpage", + close: true + }, { + element: options.lastPageButton, + eventName: "lastpage", + close: true + }, { + element: options.pageRotateCwButton, + eventName: "rotatecw", + close: false + }, { + element: options.pageRotateCcwButton, + eventName: "rotateccw", + close: false + }, { + element: options.cursorSelectToolButton, + eventName: "switchcursortool", + eventDetails: { + tool: CursorTool.SELECT + }, + close: true + }, { + element: options.cursorHandToolButton, + eventName: "switchcursortool", + eventDetails: { + tool: CursorTool.HAND + }, + close: true + }, { + element: options.scrollPageButton, + eventName: "switchscrollmode", + eventDetails: { + mode: ScrollMode.PAGE + }, + close: true + }, { + element: options.scrollVerticalButton, + eventName: "switchscrollmode", + eventDetails: { + mode: ScrollMode.VERTICAL + }, + close: true + }, { + element: options.scrollHorizontalButton, + eventName: "switchscrollmode", + eventDetails: { + mode: ScrollMode.HORIZONTAL + }, + close: true + }, { + element: options.scrollWrappedButton, + eventName: "switchscrollmode", + eventDetails: { + mode: ScrollMode.WRAPPED + }, + close: true + }, { + element: options.spreadNoneButton, + eventName: "switchspreadmode", + eventDetails: { + mode: SpreadMode.NONE + }, + close: true + }, { + element: options.spreadOddButton, + eventName: "switchspreadmode", + eventDetails: { + mode: SpreadMode.ODD + }, + close: true + }, { + element: options.spreadEvenButton, + eventName: "switchspreadmode", + eventDetails: { + mode: SpreadMode.EVEN + }, + close: true + }, { + element: options.imageAltTextSettingsButton, + eventName: "imagealttextsettings", + close: true + }, { + element: options.documentPropertiesButton, + eventName: "documentproperties", + close: true + }]; + buttons.push({ + element: options.openFileButton, + eventName: "openfile", + close: true + }); + this.eventBus = eventBus; + this.opened = false; + this.#bindListeners(buttons); + this.reset(); + } + get isOpen() { + return this.opened; + } + setPageNumber(pageNumber) { + this.pageNumber = pageNumber; + this.#updateUIState(); + } + setPagesCount(pagesCount) { + this.pagesCount = pagesCount; + this.#updateUIState(); + } + reset() { + this.pageNumber = 0; + this.pagesCount = 0; + this.#updateUIState(); + this.eventBus.dispatch("switchcursortool", { + source: this, + reset: true + }); + this.#scrollModeChanged({ + mode: ScrollMode.VERTICAL + }); + this.#spreadModeChanged({ + mode: SpreadMode.NONE + }); + } + #updateUIState() { + const { + firstPageButton, + lastPageButton, + pageRotateCwButton, + pageRotateCcwButton + } = this.#opts; + firstPageButton.disabled = this.pageNumber <= 1; + lastPageButton.disabled = this.pageNumber >= this.pagesCount; + pageRotateCwButton.disabled = this.pagesCount === 0; + pageRotateCcwButton.disabled = this.pagesCount === 0; + } + #bindListeners(buttons) { + const { + eventBus + } = this; + const { + toggleButton + } = this.#opts; + toggleButton.addEventListener("click", this.toggle.bind(this)); + for (const { + element, + eventName, + close, + eventDetails + } of buttons) { + element.addEventListener("click", evt => { + if (eventName !== null) { + eventBus.dispatch(eventName, { + source: this, + ...eventDetails + }); + } + if (close) { + this.close(); + } + eventBus.dispatch("reporttelemetry", { + source: this, + details: { + type: "buttons", + data: { + id: element.id + } + } + }); + }); + } + eventBus._on("cursortoolchanged", this.#cursorToolChanged.bind(this)); + eventBus._on("scrollmodechanged", this.#scrollModeChanged.bind(this)); + eventBus._on("spreadmodechanged", this.#spreadModeChanged.bind(this)); + } + #cursorToolChanged({ + tool, + disabled + }) { + const { + cursorSelectToolButton, + cursorHandToolButton + } = this.#opts; + toggleCheckedBtn(cursorSelectToolButton, tool === CursorTool.SELECT); + toggleCheckedBtn(cursorHandToolButton, tool === CursorTool.HAND); + cursorSelectToolButton.disabled = disabled; + cursorHandToolButton.disabled = disabled; + } + #scrollModeChanged({ + mode + }) { + const { + scrollPageButton, + scrollVerticalButton, + scrollHorizontalButton, + scrollWrappedButton, + spreadNoneButton, + spreadOddButton, + spreadEvenButton + } = this.#opts; + toggleCheckedBtn(scrollPageButton, mode === ScrollMode.PAGE); + toggleCheckedBtn(scrollVerticalButton, mode === ScrollMode.VERTICAL); + toggleCheckedBtn(scrollHorizontalButton, mode === ScrollMode.HORIZONTAL); + toggleCheckedBtn(scrollWrappedButton, mode === ScrollMode.WRAPPED); + const forceScrollModePage = this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE; + scrollPageButton.disabled = forceScrollModePage; + scrollVerticalButton.disabled = forceScrollModePage; + scrollHorizontalButton.disabled = forceScrollModePage; + scrollWrappedButton.disabled = forceScrollModePage; + const isHorizontal = mode === ScrollMode.HORIZONTAL; + spreadNoneButton.disabled = isHorizontal; + spreadOddButton.disabled = isHorizontal; + spreadEvenButton.disabled = isHorizontal; + } + #spreadModeChanged({ + mode + }) { + const { + spreadNoneButton, + spreadOddButton, + spreadEvenButton + } = this.#opts; + toggleCheckedBtn(spreadNoneButton, mode === SpreadMode.NONE); + toggleCheckedBtn(spreadOddButton, mode === SpreadMode.ODD); + toggleCheckedBtn(spreadEvenButton, mode === SpreadMode.EVEN); + } + open() { + if (this.opened) { + return; + } + this.opened = true; + const { + toggleButton, + toolbar + } = this.#opts; + toggleExpandedBtn(toggleButton, true, toolbar); + } + close() { + if (!this.opened) { + return; + } + this.opened = false; + const { + toggleButton, + toolbar + } = this.#opts; + toggleExpandedBtn(toggleButton, false, toolbar); + } + toggle() { + if (this.opened) { + this.close(); + } else { + this.open(); + } + } +} + +;// ./web/toolbar.js + + +class Toolbar { + #opts; + constructor(options, eventBus, toolbarDensity = 0) { + this.#opts = options; + this.eventBus = eventBus; + const buttons = [{ + element: options.previous, + eventName: "previouspage" + }, { + element: options.next, + eventName: "nextpage" + }, { + element: options.zoomIn, + eventName: "zoomin" + }, { + element: options.zoomOut, + eventName: "zoomout" + }, { + element: options.print, + eventName: "print" + }, { + element: options.download, + eventName: "download" + }, { + element: options.editorFreeTextButton, + eventName: "switchannotationeditormode", + eventDetails: { + get mode() { + const { + classList + } = options.editorFreeTextButton; + return classList.contains("toggled") ? AnnotationEditorType.NONE : AnnotationEditorType.FREETEXT; + } + } + }, { + element: options.editorHighlightButton, + eventName: "switchannotationeditormode", + eventDetails: { + get mode() { + const { + classList + } = options.editorHighlightButton; + return classList.contains("toggled") ? AnnotationEditorType.NONE : AnnotationEditorType.HIGHLIGHT; + } + } + }, { + element: options.editorInkButton, + eventName: "switchannotationeditormode", + eventDetails: { + get mode() { + const { + classList + } = options.editorInkButton; + return classList.contains("toggled") ? AnnotationEditorType.NONE : AnnotationEditorType.INK; + } + } + }, { + element: options.editorStampButton, + eventName: "switchannotationeditormode", + eventDetails: { + get mode() { + const { + classList + } = options.editorStampButton; + return classList.contains("toggled") ? AnnotationEditorType.NONE : AnnotationEditorType.STAMP; + } + }, + telemetry: { + type: "editing", + data: { + action: "pdfjs.image.icon_click" + } + } + }]; + this.#bindListeners(buttons); + this.#updateToolbarDensity({ + value: toolbarDensity + }); + this.reset(); + } + #updateToolbarDensity({ + value + }) { + let name = "normal"; + switch (value) { + case 1: + name = "compact"; + break; + case 2: + name = "touch"; + break; + } + document.documentElement.setAttribute("data-toolbar-density", name); + } + #setAnnotationEditorUIManager(uiManager, parentContainer) { + const colorPicker = new ColorPicker({ + uiManager + }); + uiManager.setMainHighlightColorPicker(colorPicker); + parentContainer.append(colorPicker.renderMainDropdown()); + } + setPageNumber(pageNumber, pageLabel) { + this.pageNumber = pageNumber; + this.pageLabel = pageLabel; + this.#updateUIState(false); + } + setPagesCount(pagesCount, hasPageLabels) { + this.pagesCount = pagesCount; + this.hasPageLabels = hasPageLabels; + this.#updateUIState(true); + } + setPageScale(pageScaleValue, pageScale) { + this.pageScaleValue = (pageScaleValue || pageScale).toString(); + this.pageScale = pageScale; + this.#updateUIState(false); + } + reset() { + this.pageNumber = 0; + this.pageLabel = null; + this.hasPageLabels = false; + this.pagesCount = 0; + this.pageScaleValue = DEFAULT_SCALE_VALUE; + this.pageScale = DEFAULT_SCALE; + this.#updateUIState(true); + this.updateLoadingIndicatorState(); + this.#editorModeChanged({ + mode: AnnotationEditorType.DISABLE + }); + } + #bindListeners(buttons) { + const { + eventBus + } = this; + const { + editorHighlightColorPicker, + editorHighlightButton, + pageNumber, + scaleSelect + } = this.#opts; + const self = this; + for (const { + element, + eventName, + eventDetails, + telemetry + } of buttons) { + element.addEventListener("click", evt => { + if (eventName !== null) { + eventBus.dispatch(eventName, { + source: this, + ...eventDetails, + isFromKeyboard: evt.detail === 0 + }); + } + if (telemetry) { + eventBus.dispatch("reporttelemetry", { + source: this, + details: telemetry + }); + } + }); + } + pageNumber.addEventListener("click", function () { + this.select(); + }); + pageNumber.addEventListener("change", function () { + eventBus.dispatch("pagenumberchanged", { + source: self, + value: this.value + }); + }); + scaleSelect.addEventListener("change", function () { + if (this.value === "custom") { + return; + } + eventBus.dispatch("scalechanged", { + source: self, + value: this.value + }); + }); + scaleSelect.addEventListener("click", function ({ + target + }) { + if (this.value === self.pageScaleValue && target.tagName.toUpperCase() === "OPTION") { + this.blur(); + } + }); + scaleSelect.oncontextmenu = noContextMenu; + eventBus._on("annotationeditormodechanged", this.#editorModeChanged.bind(this)); + eventBus._on("showannotationeditorui", ({ + mode + }) => { + switch (mode) { + case AnnotationEditorType.HIGHLIGHT: + editorHighlightButton.click(); + break; + } + }); + eventBus._on("toolbardensity", this.#updateToolbarDensity.bind(this)); + if (editorHighlightColorPicker) { + eventBus._on("annotationeditoruimanager", ({ + uiManager + }) => { + this.#setAnnotationEditorUIManager(uiManager, editorHighlightColorPicker); + }, { + once: true + }); + } + } + #editorModeChanged({ + mode + }) { + const { + editorFreeTextButton, + editorFreeTextParamsToolbar, + editorHighlightButton, + editorHighlightParamsToolbar, + editorInkButton, + editorInkParamsToolbar, + editorStampButton, + editorStampParamsToolbar + } = this.#opts; + toggleExpandedBtn(editorFreeTextButton, mode === AnnotationEditorType.FREETEXT, editorFreeTextParamsToolbar); + toggleExpandedBtn(editorHighlightButton, mode === AnnotationEditorType.HIGHLIGHT, editorHighlightParamsToolbar); + toggleExpandedBtn(editorInkButton, mode === AnnotationEditorType.INK, editorInkParamsToolbar); + toggleExpandedBtn(editorStampButton, mode === AnnotationEditorType.STAMP, editorStampParamsToolbar); + const isDisable = mode === AnnotationEditorType.DISABLE; + editorFreeTextButton.disabled = isDisable; + editorHighlightButton.disabled = isDisable; + editorInkButton.disabled = isDisable; + editorStampButton.disabled = isDisable; + } + #updateUIState(resetNumPages = false) { + const { + pageNumber, + pagesCount, + pageScaleValue, + pageScale + } = this; + const opts = this.#opts; + if (resetNumPages) { + if (this.hasPageLabels) { + opts.pageNumber.type = "text"; + opts.numPages.setAttribute("data-l10n-id", "pdfjs-page-of-pages"); + } else { + opts.pageNumber.type = "number"; + opts.numPages.setAttribute("data-l10n-id", "pdfjs-of-pages"); + opts.numPages.setAttribute("data-l10n-args", JSON.stringify({ + pagesCount + })); + } + opts.pageNumber.max = pagesCount; + } + if (this.hasPageLabels) { + opts.pageNumber.value = this.pageLabel; + opts.numPages.setAttribute("data-l10n-args", JSON.stringify({ + pageNumber, + pagesCount + })); + } else { + opts.pageNumber.value = pageNumber; + } + opts.previous.disabled = pageNumber <= 1; + opts.next.disabled = pageNumber >= pagesCount; + opts.zoomOut.disabled = pageScale <= MIN_SCALE; + opts.zoomIn.disabled = pageScale >= MAX_SCALE; + let predefinedValueFound = false; + for (const option of opts.scaleSelect.options) { + if (option.value !== pageScaleValue) { + option.selected = false; + continue; + } + option.selected = true; + predefinedValueFound = true; + } + if (!predefinedValueFound) { + opts.customScaleOption.selected = true; + opts.customScaleOption.setAttribute("data-l10n-args", JSON.stringify({ + scale: Math.round(pageScale * 10000) / 100 + })); + } + } + updateLoadingIndicatorState(loading = false) { + const { + pageNumber + } = this.#opts; + pageNumber.classList.toggle("loading", loading); + } +} + +;// ./web/view_history.js +const DEFAULT_VIEW_HISTORY_CACHE_SIZE = 20; +class ViewHistory { + constructor(fingerprint, cacheSize = DEFAULT_VIEW_HISTORY_CACHE_SIZE) { + this.fingerprint = fingerprint; + this.cacheSize = cacheSize; + this._initializedPromise = this._readFromStorage().then(databaseStr => { + const database = JSON.parse(databaseStr || "{}"); + let index = -1; + if (!Array.isArray(database.files)) { + database.files = []; + } else { + while (database.files.length >= this.cacheSize) { + database.files.shift(); + } + for (let i = 0, ii = database.files.length; i < ii; i++) { + const branch = database.files[i]; + if (branch.fingerprint === this.fingerprint) { + index = i; + break; + } + } + } + if (index === -1) { + index = database.files.push({ + fingerprint: this.fingerprint + }) - 1; + } + this.file = database.files[index]; + this.database = database; + }); + } + async _writeToStorage() { + const databaseStr = JSON.stringify(this.database); + localStorage.setItem("pdfjs.history", databaseStr); + } + async _readFromStorage() { + return localStorage.getItem("pdfjs.history"); + } + async set(name, val) { + await this._initializedPromise; + this.file[name] = val; + return this._writeToStorage(); + } + async setMultiple(properties) { + await this._initializedPromise; + for (const name in properties) { + this.file[name] = properties[name]; + } + return this._writeToStorage(); + } + async get(name, defaultValue) { + await this._initializedPromise; + const val = this.file[name]; + return val !== undefined ? val : defaultValue; + } + async getMultiple(properties) { + await this._initializedPromise; + const values = Object.create(null); + for (const name in properties) { + const val = this.file[name]; + values[name] = val !== undefined ? val : properties[name]; + } + return values; + } +} + +;// ./web/app.js + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +const FORCE_PAGES_LOADED_TIMEOUT = 10000; +const MIN_TOUCH_DISTANCE_TO_PINCH = 35 / (window.devicePixelRatio || 1); +const ViewOnLoad = { + UNKNOWN: -1, + PREVIOUS: 0, + INITIAL: 1 +}; +const PDFViewerApplication = { + initialBookmark: document.location.hash.substring(1), + _initializedCapability: { + ...Promise.withResolvers(), + settled: false + }, + appConfig: null, + pdfDocument: null, + pdfLoadingTask: null, + printService: null, + pdfViewer: null, + pdfThumbnailViewer: null, + pdfRenderingQueue: null, + pdfPresentationMode: null, + pdfDocumentProperties: null, + pdfLinkService: null, + pdfHistory: null, + pdfSidebar: null, + pdfOutlineViewer: null, + pdfAttachmentViewer: null, + pdfLayerViewer: null, + pdfCursorTools: null, + pdfScriptingManager: null, + store: null, + downloadManager: null, + overlayManager: null, + preferences: new Preferences(), + toolbar: null, + secondaryToolbar: null, + eventBus: null, + l10n: null, + annotationEditorParams: null, + imageAltTextSettings: null, + isInitialViewSet: false, + isViewerEmbedded: window.parent !== window, + url: "", + baseUrl: "", + mlManager: null, + _downloadUrl: "", + _eventBusAbortController: null, + _windowAbortController: null, + _globalAbortController: new AbortController(), + documentInfo: null, + metadata: null, + _contentDispositionFilename: null, + _contentLength: null, + _saveInProgress: false, + _wheelUnusedTicks: 0, + _wheelUnusedFactor: 1, + _touchUnusedTicks: 0, + _touchUnusedFactor: 1, + _PDFBug: null, + _hasAnnotationEditors: false, + _title: document.title, + _printAnnotationStoragePromise: null, + _touchInfo: null, + _isPinching: false, + _isCtrlKeyDown: false, + _caretBrowsing: null, + _isScrolling: false, + editorUndoBar: null, + async initialize(appConfig) { + this.appConfig = appConfig; + try { + await this.preferences.initializedPromise; + } catch (ex) { + console.error(`initialize: "${ex.message}".`); + } + if (AppOptions.get("pdfBugEnabled")) { + await this._parseHashParams(); + } + let mode; + switch (AppOptions.get("viewerCssTheme")) { + case 1: + mode = "is-light"; + break; + case 2: + mode = "is-dark"; + break; + } + if (mode) { + document.documentElement.classList.add(mode); + } + this.l10n = await this.externalServices.createL10n(); + document.getElementsByTagName("html")[0].dir = this.l10n.getDirection(); + this.l10n.translate(appConfig.appContainer || document.documentElement); + if (this.isViewerEmbedded && AppOptions.get("externalLinkTarget") === LinkTarget.NONE) { + AppOptions.set("externalLinkTarget", LinkTarget.TOP); + } + await this._initializeViewerComponents(); + this.bindEvents(); + this.bindWindowEvents(); + this._initializedCapability.settled = true; + this._initializedCapability.resolve(); + }, + async _parseHashParams() { + const hash = document.location.hash.substring(1); + if (!hash) { + return; + } + const { + mainContainer, + viewerContainer + } = this.appConfig, + params = parseQueryString(hash); + const loadPDFBug = async () => { + if (this._PDFBug) { + return; + } + const { + PDFBug + } = await import(/*webpackIgnore: true*/AppOptions.get("debuggerSrc")); + this._PDFBug = PDFBug; + }; + if (params.get("disableworker") === "true") { + try { + GlobalWorkerOptions.workerSrc ||= AppOptions.get("workerSrc"); + await import(/*webpackIgnore: true*/PDFWorker.workerSrc); + } catch (ex) { + console.error(`_parseHashParams: "${ex.message}".`); + } + } + if (params.has("textlayer")) { + switch (params.get("textlayer")) { + case "off": + AppOptions.set("textLayerMode", TextLayerMode.DISABLE); + break; + case "visible": + case "shadow": + case "hover": + viewerContainer.classList.add(`textLayer-${params.get("textlayer")}`); + try { + await loadPDFBug(); + this._PDFBug.loadCSS(); + } catch (ex) { + console.error(`_parseHashParams: "${ex.message}".`); + } + break; + } + } + if (params.has("pdfbug")) { + AppOptions.setAll({ + pdfBug: true, + fontExtraProperties: true + }); + const enabled = params.get("pdfbug").split(","); + try { + await loadPDFBug(); + this._PDFBug.init(mainContainer, enabled); + } catch (ex) { + console.error(`_parseHashParams: "${ex.message}".`); + } + } + if (params.has("locale")) { + AppOptions.set("localeProperties", { + lang: params.get("locale") + }); + } + const opts = { + disableAutoFetch: x => x === "true", + disableFontFace: x => x === "true", + disableHistory: x => x === "true", + disableRange: x => x === "true", + disableStream: x => x === "true", + verbosity: x => x | 0 + }; + for (const name in opts) { + const check = opts[name], + key = name.toLowerCase(); + if (params.has(key)) { + AppOptions.set(name, check(params.get(key))); + } + } + }, + async _initializeViewerComponents() { + const { + appConfig, + externalServices, + l10n + } = this; + const eventBus = new EventBus(); + this.eventBus = AppOptions.eventBus = eventBus; + this.mlManager?.setEventBus(eventBus, this._globalAbortController.signal); + this.overlayManager = new OverlayManager(); + const pdfRenderingQueue = new PDFRenderingQueue(); + pdfRenderingQueue.onIdle = this._cleanup.bind(this); + this.pdfRenderingQueue = pdfRenderingQueue; + const pdfLinkService = new PDFLinkService({ + eventBus, + externalLinkTarget: AppOptions.get("externalLinkTarget"), + externalLinkRel: AppOptions.get("externalLinkRel"), + ignoreDestinationZoom: AppOptions.get("ignoreDestinationZoom") + }); + this.pdfLinkService = pdfLinkService; + const downloadManager = this.downloadManager = new DownloadManager(); + const findController = new PDFFindController({ + linkService: pdfLinkService, + eventBus, + updateMatchesCountOnProgress: true + }); + this.findController = findController; + const pdfScriptingManager = new PDFScriptingManager({ + eventBus, + externalServices, + docProperties: this._scriptingDocProperties.bind(this) + }); + this.pdfScriptingManager = pdfScriptingManager; + const container = appConfig.mainContainer, + viewer = appConfig.viewerContainer; + const annotationEditorMode = AppOptions.get("annotationEditorMode"); + const pageColors = AppOptions.get("forcePageColors") || window.matchMedia("(forced-colors: active)").matches ? { + background: AppOptions.get("pageColorsBackground"), + foreground: AppOptions.get("pageColorsForeground") + } : null; + let altTextManager; + if (AppOptions.get("enableUpdatedAddImage")) { + altTextManager = appConfig.newAltTextDialog ? new NewAltTextManager(appConfig.newAltTextDialog, this.overlayManager, eventBus) : null; + } else { + altTextManager = appConfig.altTextDialog ? new AltTextManager(appConfig.altTextDialog, container, this.overlayManager, eventBus) : null; + } + if (appConfig.editorUndoBar) { + this.editorUndoBar = new EditorUndoBar(appConfig.editorUndoBar, eventBus); + } + const enableHWA = AppOptions.get("enableHWA"); + const pdfViewer = new PDFViewer({ + container, + viewer, + eventBus, + renderingQueue: pdfRenderingQueue, + linkService: pdfLinkService, + downloadManager, + altTextManager, + editorUndoBar: this.editorUndoBar, + findController, + scriptingManager: AppOptions.get("enableScripting") && pdfScriptingManager, + l10n, + textLayerMode: AppOptions.get("textLayerMode"), + annotationMode: AppOptions.get("annotationMode"), + annotationEditorMode, + annotationEditorHighlightColors: AppOptions.get("highlightEditorColors"), + enableHighlightFloatingButton: AppOptions.get("enableHighlightFloatingButton"), + enableUpdatedAddImage: AppOptions.get("enableUpdatedAddImage"), + enableNewAltTextWhenAddingImage: AppOptions.get("enableNewAltTextWhenAddingImage"), + imageResourcesPath: AppOptions.get("imageResourcesPath"), + enablePrintAutoRotate: AppOptions.get("enablePrintAutoRotate"), + maxCanvasPixels: AppOptions.get("maxCanvasPixels"), + enablePermissions: AppOptions.get("enablePermissions"), + pageColors, + mlManager: this.mlManager, + abortSignal: this._globalAbortController.signal, + enableHWA + }); + this.pdfViewer = pdfViewer; + pdfRenderingQueue.setViewer(pdfViewer); + pdfLinkService.setViewer(pdfViewer); + pdfScriptingManager.setViewer(pdfViewer); + if (appConfig.sidebar?.thumbnailView) { + this.pdfThumbnailViewer = new PDFThumbnailViewer({ + container: appConfig.sidebar.thumbnailView, + eventBus, + renderingQueue: pdfRenderingQueue, + linkService: pdfLinkService, + pageColors, + abortSignal: this._globalAbortController.signal, + enableHWA + }); + pdfRenderingQueue.setThumbnailViewer(this.pdfThumbnailViewer); + } + if (!this.isViewerEmbedded && !AppOptions.get("disableHistory")) { + this.pdfHistory = new PDFHistory({ + linkService: pdfLinkService, + eventBus + }); + pdfLinkService.setHistory(this.pdfHistory); + } + if (!this.supportsIntegratedFind && appConfig.findBar) { + this.findBar = new PDFFindBar(appConfig.findBar, appConfig.principalContainer, eventBus); + } + if (appConfig.annotationEditorParams) { + if (typeof AbortSignal.any === "function" && annotationEditorMode !== AnnotationEditorType.DISABLE) { + this.annotationEditorParams = new AnnotationEditorParams(appConfig.annotationEditorParams, eventBus); + } else { + for (const id of ["editorModeButtons", "editorModeSeparator"]) { + document.getElementById(id)?.classList.add("hidden"); + } + } + } + if (this.mlManager && appConfig.secondaryToolbar?.imageAltTextSettingsButton) { + this.imageAltTextSettings = new ImageAltTextSettings(appConfig.altTextSettingsDialog, this.overlayManager, eventBus, this.mlManager); + } + if (appConfig.documentProperties) { + this.pdfDocumentProperties = new PDFDocumentProperties(appConfig.documentProperties, this.overlayManager, eventBus, l10n, () => this._docFilename); + } + if (appConfig.secondaryToolbar?.cursorHandToolButton) { + this.pdfCursorTools = new PDFCursorTools({ + container, + eventBus, + cursorToolOnLoad: AppOptions.get("cursorToolOnLoad") + }); + } + if (appConfig.toolbar) { + this.toolbar = new Toolbar(appConfig.toolbar, eventBus, AppOptions.get("toolbarDensity")); + } + if (appConfig.secondaryToolbar) { + if (AppOptions.get("enableAltText")) { + appConfig.secondaryToolbar.imageAltTextSettingsButton?.classList.remove("hidden"); + appConfig.secondaryToolbar.imageAltTextSettingsSeparator?.classList.remove("hidden"); + } + this.secondaryToolbar = new SecondaryToolbar(appConfig.secondaryToolbar, eventBus); + } + if (this.supportsFullscreen && appConfig.secondaryToolbar?.presentationModeButton) { + this.pdfPresentationMode = new PDFPresentationMode({ + container, + pdfViewer, + eventBus + }); + } + if (appConfig.passwordOverlay) { + this.passwordPrompt = new PasswordPrompt(appConfig.passwordOverlay, this.overlayManager, this.isViewerEmbedded); + } + if (appConfig.sidebar?.outlineView) { + this.pdfOutlineViewer = new PDFOutlineViewer({ + container: appConfig.sidebar.outlineView, + eventBus, + l10n, + linkService: pdfLinkService, + downloadManager + }); + } + if (appConfig.sidebar?.attachmentsView) { + this.pdfAttachmentViewer = new PDFAttachmentViewer({ + container: appConfig.sidebar.attachmentsView, + eventBus, + l10n, + downloadManager + }); + } + if (appConfig.sidebar?.layersView) { + this.pdfLayerViewer = new PDFLayerViewer({ + container: appConfig.sidebar.layersView, + eventBus, + l10n + }); + } + if (appConfig.sidebar) { + this.pdfSidebar = new PDFSidebar({ + elements: appConfig.sidebar, + eventBus, + l10n + }); + this.pdfSidebar.onToggled = this.forceRendering.bind(this); + this.pdfSidebar.onUpdateThumbnails = () => { + for (const pageView of pdfViewer.getCachedPageViews()) { + if (pageView.renderingState === RenderingStates.FINISHED) { + this.pdfThumbnailViewer.getThumbnail(pageView.id - 1)?.setImage(pageView); + } + } + this.pdfThumbnailViewer.scrollThumbnailIntoView(pdfViewer.currentPageNumber); + }; + } + }, + async run(config) { + await this.initialize(config); + const { + appConfig, + eventBus + } = this; + let file; + const queryString = document.location.search.substring(1); + const params = parseQueryString(queryString); + file = params.get("file") ?? AppOptions.get("defaultUrl"); + validateFileURL(file); + const fileInput = this._openFileInput = document.createElement("input"); + fileInput.id = "fileInput"; + fileInput.hidden = true; + fileInput.type = "file"; + fileInput.value = null; + document.body.append(fileInput); + fileInput.addEventListener("change", function (evt) { + const { + files + } = evt.target; + if (!files || files.length === 0) { + return; + } + eventBus.dispatch("fileinputchange", { + source: this, + fileInput: evt.target + }); + }); + appConfig.mainContainer.addEventListener("dragover", function (evt) { + for (const item of evt.dataTransfer.items) { + if (item.type === "application/pdf") { + evt.dataTransfer.dropEffect = evt.dataTransfer.effectAllowed === "copy" ? "copy" : "move"; + stopEvent(evt); + return; + } + } + }); + appConfig.mainContainer.addEventListener("drop", function (evt) { + if (evt.dataTransfer.files?.[0].type !== "application/pdf") { + return; + } + stopEvent(evt); + eventBus.dispatch("fileinputchange", { + source: this, + fileInput: evt.dataTransfer + }); + }); + if (!AppOptions.get("supportsDocumentFonts")) { + AppOptions.set("disableFontFace", true); + this.l10n.get("pdfjs-web-fonts-disabled").then(msg => { + console.warn(msg); + }); + } + if (!this.supportsPrinting) { + appConfig.toolbar?.print?.classList.add("hidden"); + appConfig.secondaryToolbar?.printButton.classList.add("hidden"); + } + if (!this.supportsFullscreen) { + appConfig.secondaryToolbar?.presentationModeButton.classList.add("hidden"); + } + if (this.supportsIntegratedFind) { + appConfig.findBar?.toggleButton?.classList.add("hidden"); + } + if (file) { + this.open({ + url: file + }); + } else { + this._hideViewBookmark(); + } + }, + get externalServices() { + return shadow(this, "externalServices", new ExternalServices()); + }, + get initialized() { + return this._initializedCapability.settled; + }, + get initializedPromise() { + return this._initializedCapability.promise; + }, + updateZoom(steps, scaleFactor, origin) { + if (this.pdfViewer.isInPresentationMode) { + return; + } + this.pdfViewer.updateScale({ + drawingDelay: AppOptions.get("defaultZoomDelay"), + steps, + scaleFactor, + origin + }); + }, + zoomIn() { + this.updateZoom(1); + }, + zoomOut() { + this.updateZoom(-1); + }, + zoomReset() { + if (this.pdfViewer.isInPresentationMode) { + return; + } + this.pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE; + }, + get pagesCount() { + return this.pdfDocument ? this.pdfDocument.numPages : 0; + }, + get page() { + return this.pdfViewer.currentPageNumber; + }, + set page(val) { + this.pdfViewer.currentPageNumber = val; + }, + get supportsPrinting() { + return PDFPrintServiceFactory.supportsPrinting; + }, + get supportsFullscreen() { + return shadow(this, "supportsFullscreen", document.fullscreenEnabled); + }, + get supportsPinchToZoom() { + return shadow(this, "supportsPinchToZoom", AppOptions.get("supportsPinchToZoom")); + }, + get supportsIntegratedFind() { + return shadow(this, "supportsIntegratedFind", AppOptions.get("supportsIntegratedFind")); + }, + get loadingBar() { + const barElement = document.getElementById("loadingBar"); + const bar = barElement ? new ProgressBar(barElement) : null; + return shadow(this, "loadingBar", bar); + }, + get supportsMouseWheelZoomCtrlKey() { + return shadow(this, "supportsMouseWheelZoomCtrlKey", AppOptions.get("supportsMouseWheelZoomCtrlKey")); + }, + get supportsMouseWheelZoomMetaKey() { + return shadow(this, "supportsMouseWheelZoomMetaKey", AppOptions.get("supportsMouseWheelZoomMetaKey")); + }, + get supportsCaretBrowsingMode() { + return AppOptions.get("supportsCaretBrowsingMode"); + }, + moveCaret(isUp, select) { + this._caretBrowsing ||= new CaretBrowsingMode(this._globalAbortController.signal, this.appConfig.mainContainer, this.appConfig.viewerContainer, this.appConfig.toolbar?.container); + this._caretBrowsing.moveCaret(isUp, select); + }, + setTitleUsingUrl(url = "", downloadUrl = null) { + this.url = url; + this.baseUrl = url.split("#", 1)[0]; + if (downloadUrl) { + this._downloadUrl = downloadUrl === url ? this.baseUrl : downloadUrl.split("#", 1)[0]; + } + if (isDataScheme(url)) { + this._hideViewBookmark(); + } + let title = pdfjs_getPdfFilenameFromUrl(url, ""); + if (!title) { + try { + title = decodeURIComponent(getFilenameFromUrl(url)); + } catch {} + } + this.setTitle(title || url); + }, + setTitle(title = this._title) { + this._title = title; + if (this.isViewerEmbedded) { + return; + } + const editorIndicator = this._hasAnnotationEditors && !this.pdfRenderingQueue.printing; + document.title = `${editorIndicator ? "* " : ""}${title}`; + }, + get _docFilename() { + return this._contentDispositionFilename || pdfjs_getPdfFilenameFromUrl(this.url); + }, + _hideViewBookmark() { + const { + secondaryToolbar + } = this.appConfig; + secondaryToolbar?.viewBookmarkButton.classList.add("hidden"); + if (secondaryToolbar?.presentationModeButton.classList.contains("hidden")) { + document.getElementById("viewBookmarkSeparator")?.classList.add("hidden"); + } + }, + async close() { + this._unblockDocumentLoadEvent(); + this._hideViewBookmark(); + if (!this.pdfLoadingTask) { + return; + } + if (this.pdfDocument?.annotationStorage.size > 0 && this._annotationStorageModified) { + try { + await this.save(); + } catch {} + } + const promises = []; + promises.push(this.pdfLoadingTask.destroy()); + this.pdfLoadingTask = null; + if (this.pdfDocument) { + this.pdfDocument = null; + this.pdfThumbnailViewer?.setDocument(null); + this.pdfViewer.setDocument(null); + this.pdfLinkService.setDocument(null); + this.pdfDocumentProperties?.setDocument(null); + } + this.pdfLinkService.externalLinkEnabled = true; + this.store = null; + this.isInitialViewSet = false; + this.url = ""; + this.baseUrl = ""; + this._downloadUrl = ""; + this.documentInfo = null; + this.metadata = null; + this._contentDispositionFilename = null; + this._contentLength = null; + this._saveInProgress = false; + this._hasAnnotationEditors = false; + promises.push(this.pdfScriptingManager.destroyPromise, this.passwordPrompt.close()); + this.setTitle(); + this.pdfSidebar?.reset(); + this.pdfOutlineViewer?.reset(); + this.pdfAttachmentViewer?.reset(); + this.pdfLayerViewer?.reset(); + this.pdfHistory?.reset(); + this.findBar?.reset(); + this.toolbar?.reset(); + this.secondaryToolbar?.reset(); + this._PDFBug?.cleanup(); + await Promise.all(promises); + }, + async open(args) { + if (this.pdfLoadingTask) { + await this.close(); + } + const workerParams = AppOptions.getAll(OptionKind.WORKER); + Object.assign(GlobalWorkerOptions, workerParams); + if (args.url) { + this.setTitleUsingUrl(args.originalUrl || args.url, args.url); + } + const apiParams = AppOptions.getAll(OptionKind.API); + const loadingTask = getDocument({ + ...apiParams, + ...args + }); + this.pdfLoadingTask = loadingTask; + loadingTask.onPassword = (updateCallback, reason) => { + if (this.isViewerEmbedded) { + this._unblockDocumentLoadEvent(); + } + this.pdfLinkService.externalLinkEnabled = false; + this.passwordPrompt.setUpdateCallback(updateCallback, reason); + this.passwordPrompt.open(); + }; + loadingTask.onProgress = ({ + loaded, + total + }) => { + this.progress(loaded / total); + }; + return loadingTask.promise.then(pdfDocument => { + this.load(pdfDocument); + }, reason => { + if (loadingTask !== this.pdfLoadingTask) { + return undefined; + } + let key = "pdfjs-loading-error"; + if (reason instanceof InvalidPDFException) { + key = "pdfjs-invalid-file-error"; + } else if (reason instanceof MissingPDFException) { + key = "pdfjs-missing-file-error"; + } else if (reason instanceof UnexpectedResponseException) { + key = "pdfjs-unexpected-response-error"; + } + return this._documentError(key, { + message: reason.message + }).then(() => { + throw reason; + }); + }); + }, + async download() { + let data; + try { + data = await this.pdfDocument.getData(); + } catch {} + this.downloadManager.download(data, this._downloadUrl, this._docFilename); + }, + async save() { + if (this._saveInProgress) { + return; + } + this._saveInProgress = true; + await this.pdfScriptingManager.dispatchWillSave(); + try { + const data = await this.pdfDocument.saveDocument(); + this.downloadManager.download(data, this._downloadUrl, this._docFilename); + } catch (reason) { + console.error(`Error when saving the document: ${reason.message}`); + await this.download(); + } finally { + await this.pdfScriptingManager.dispatchDidSave(); + this._saveInProgress = false; + } + if (this._hasAnnotationEditors) { + this.externalServices.reportTelemetry({ + type: "editing", + data: { + type: "save", + stats: this.pdfDocument?.annotationStorage.editorStats + } + }); + } + }, + async downloadOrSave() { + const { + classList + } = this.appConfig.appContainer; + classList.add("wait"); + await (this.pdfDocument?.annotationStorage.size > 0 ? this.save() : this.download()); + classList.remove("wait"); + }, + async _documentError(key, moreInfo = null) { + this._unblockDocumentLoadEvent(); + const message = await this._otherError(key || "pdfjs-loading-error", moreInfo); + this.eventBus.dispatch("documenterror", { + source: this, + message, + reason: moreInfo?.message ?? null + }); + }, + async _otherError(key, moreInfo = null) { + const message = await this.l10n.get(key); + const moreInfoText = [`PDF.js v${version || "?"} (build: ${build || "?"})`]; + if (moreInfo) { + moreInfoText.push(`Message: ${moreInfo.message}`); + if (moreInfo.stack) { + moreInfoText.push(`Stack: ${moreInfo.stack}`); + } else { + if (moreInfo.filename) { + moreInfoText.push(`File: ${moreInfo.filename}`); + } + if (moreInfo.lineNumber) { + moreInfoText.push(`Line: ${moreInfo.lineNumber}`); + } + } + } + console.error(`${message}\n\n${moreInfoText.join("\n")}`); + return message; + }, + progress(level) { + const percent = Math.round(level * 100); + if (!this.loadingBar || percent <= this.loadingBar.percent) { + return; + } + this.loadingBar.percent = percent; + if (this.pdfDocument?.loadingParams.disableAutoFetch ?? AppOptions.get("disableAutoFetch")) { + this.loadingBar.setDisableAutoFetch(); + } + }, + load(pdfDocument) { + this.pdfDocument = pdfDocument; + pdfDocument.getDownloadInfo().then(({ + length + }) => { + this._contentLength = length; + this.loadingBar?.hide(); + firstPagePromise.then(() => { + this.eventBus.dispatch("documentloaded", { + source: this + }); + }); + }); + const pageLayoutPromise = pdfDocument.getPageLayout().catch(() => {}); + const pageModePromise = pdfDocument.getPageMode().catch(() => {}); + const openActionPromise = pdfDocument.getOpenAction().catch(() => {}); + this.toolbar?.setPagesCount(pdfDocument.numPages, false); + this.secondaryToolbar?.setPagesCount(pdfDocument.numPages); + this.pdfLinkService.setDocument(pdfDocument); + this.pdfDocumentProperties?.setDocument(pdfDocument); + const pdfViewer = this.pdfViewer; + pdfViewer.setDocument(pdfDocument); + const { + firstPagePromise, + onePageRendered, + pagesPromise + } = pdfViewer; + this.pdfThumbnailViewer?.setDocument(pdfDocument); + const storedPromise = (this.store = new ViewHistory(pdfDocument.fingerprints[0])).getMultiple({ + page: null, + zoom: DEFAULT_SCALE_VALUE, + scrollLeft: "0", + scrollTop: "0", + rotation: null, + sidebarView: SidebarView.UNKNOWN, + scrollMode: ScrollMode.UNKNOWN, + spreadMode: SpreadMode.UNKNOWN + }).catch(() => {}); + firstPagePromise.then(pdfPage => { + this.loadingBar?.setWidth(this.appConfig.viewerContainer); + this._initializeAnnotationStorageCallbacks(pdfDocument); + Promise.all([animationStarted, storedPromise, pageLayoutPromise, pageModePromise, openActionPromise]).then(async ([timeStamp, stored, pageLayout, pageMode, openAction]) => { + const viewOnLoad = AppOptions.get("viewOnLoad"); + this._initializePdfHistory({ + fingerprint: pdfDocument.fingerprints[0], + viewOnLoad, + initialDest: openAction?.dest + }); + const initialBookmark = this.initialBookmark; + const zoom = AppOptions.get("defaultZoomValue"); + let hash = zoom ? `zoom=${zoom}` : null; + let rotation = null; + let sidebarView = AppOptions.get("sidebarViewOnLoad"); + let scrollMode = AppOptions.get("scrollModeOnLoad"); + let spreadMode = AppOptions.get("spreadModeOnLoad"); + if (stored?.page && viewOnLoad !== ViewOnLoad.INITIAL) { + hash = `page=${stored.page}&zoom=${zoom || stored.zoom},` + `${stored.scrollLeft},${stored.scrollTop}`; + rotation = parseInt(stored.rotation, 10); + if (sidebarView === SidebarView.UNKNOWN) { + sidebarView = stored.sidebarView | 0; + } + if (scrollMode === ScrollMode.UNKNOWN) { + scrollMode = stored.scrollMode | 0; + } + if (spreadMode === SpreadMode.UNKNOWN) { + spreadMode = stored.spreadMode | 0; + } + } + if (pageMode && sidebarView === SidebarView.UNKNOWN) { + sidebarView = apiPageModeToSidebarView(pageMode); + } + if (pageLayout && scrollMode === ScrollMode.UNKNOWN && spreadMode === SpreadMode.UNKNOWN) { + const modes = apiPageLayoutToViewerModes(pageLayout); + spreadMode = modes.spreadMode; + } + this.setInitialView(hash, { + rotation, + sidebarView, + scrollMode, + spreadMode + }); + this.eventBus.dispatch("documentinit", { + source: this + }); + if (!this.isViewerEmbedded) { + pdfViewer.focus(); + } + await Promise.race([pagesPromise, new Promise(resolve => { + setTimeout(resolve, FORCE_PAGES_LOADED_TIMEOUT); + })]); + if (!initialBookmark && !hash) { + return; + } + if (pdfViewer.hasEqualPageSizes) { + return; + } + this.initialBookmark = initialBookmark; + pdfViewer.currentScaleValue = pdfViewer.currentScaleValue; + this.setInitialView(hash); + }).catch(() => { + this.setInitialView(); + }).then(function () { + pdfViewer.update(); + }); + }); + pagesPromise.then(() => { + this._unblockDocumentLoadEvent(); + this._initializeAutoPrint(pdfDocument, openActionPromise); + }, reason => { + this._documentError("pdfjs-loading-error", { + message: reason.message + }); + }); + onePageRendered.then(data => { + this.externalServices.reportTelemetry({ + type: "pageInfo", + timestamp: data.timestamp + }); + if (this.pdfOutlineViewer) { + pdfDocument.getOutline().then(outline => { + if (pdfDocument !== this.pdfDocument) { + return; + } + this.pdfOutlineViewer.render({ + outline, + pdfDocument + }); + }); + } + if (this.pdfAttachmentViewer) { + pdfDocument.getAttachments().then(attachments => { + if (pdfDocument !== this.pdfDocument) { + return; + } + this.pdfAttachmentViewer.render({ + attachments + }); + }); + } + if (this.pdfLayerViewer) { + pdfViewer.optionalContentConfigPromise.then(optionalContentConfig => { + if (pdfDocument !== this.pdfDocument) { + return; + } + this.pdfLayerViewer.render({ + optionalContentConfig, + pdfDocument + }); + }); + } + }); + this._initializePageLabels(pdfDocument); + this._initializeMetadata(pdfDocument); + }, + async _scriptingDocProperties(pdfDocument) { + if (!this.documentInfo) { + await new Promise(resolve => { + this.eventBus._on("metadataloaded", resolve, { + once: true + }); + }); + if (pdfDocument !== this.pdfDocument) { + return null; + } + } + if (!this._contentLength) { + await new Promise(resolve => { + this.eventBus._on("documentloaded", resolve, { + once: true + }); + }); + if (pdfDocument !== this.pdfDocument) { + return null; + } + } + return { + ...this.documentInfo, + baseURL: this.baseUrl, + filesize: this._contentLength, + filename: this._docFilename, + metadata: this.metadata?.getRaw(), + authors: this.metadata?.get("dc:creator"), + numPages: this.pagesCount, + URL: this.url + }; + }, + async _initializeAutoPrint(pdfDocument, openActionPromise) { + const [openAction, jsActions] = await Promise.all([openActionPromise, this.pdfViewer.enableScripting ? null : pdfDocument.getJSActions()]); + if (pdfDocument !== this.pdfDocument) { + return; + } + let triggerAutoPrint = openAction?.action === "Print"; + if (jsActions) { + console.warn("Warning: JavaScript support is not enabled"); + for (const name in jsActions) { + if (triggerAutoPrint) { + break; + } + switch (name) { + case "WillClose": + case "WillSave": + case "DidSave": + case "WillPrint": + case "DidPrint": + continue; + } + triggerAutoPrint = jsActions[name].some(js => AutoPrintRegExp.test(js)); + } + } + if (triggerAutoPrint) { + this.triggerPrinting(); + } + }, + async _initializeMetadata(pdfDocument) { + const { + info, + metadata, + contentDispositionFilename, + contentLength + } = await pdfDocument.getMetadata(); + if (pdfDocument !== this.pdfDocument) { + return; + } + this.documentInfo = info; + this.metadata = metadata; + this._contentDispositionFilename ??= contentDispositionFilename; + this._contentLength ??= contentLength; + console.log(`PDF ${pdfDocument.fingerprints[0]} [${info.PDFFormatVersion} ` + `${(info.Producer || "-").trim()} / ${(info.Creator || "-").trim()}] ` + `(PDF.js: ${version || "?"} [${build || "?"}])`); + let pdfTitle = info.Title; + const metadataTitle = metadata?.get("dc:title"); + if (metadataTitle) { + if (metadataTitle !== "Untitled" && !/[\uFFF0-\uFFFF]/g.test(metadataTitle)) { + pdfTitle = metadataTitle; + } + } + if (pdfTitle) { + this.setTitle(`${pdfTitle} - ${this._contentDispositionFilename || this._title}`); + } else if (this._contentDispositionFilename) { + this.setTitle(this._contentDispositionFilename); + } + if (info.IsXFAPresent && !info.IsAcroFormPresent && !pdfDocument.isPureXfa) { + if (pdfDocument.loadingParams.enableXfa) { + console.warn("Warning: XFA Foreground documents are not supported"); + } else { + console.warn("Warning: XFA support is not enabled"); + } + } else if ((info.IsAcroFormPresent || info.IsXFAPresent) && !this.pdfViewer.renderForms) { + console.warn("Warning: Interactive form support is not enabled"); + } + if (info.IsSignaturesPresent) { + console.warn("Warning: Digital signatures validation is not supported"); + } + this.eventBus.dispatch("metadataloaded", { + source: this + }); + }, + async _initializePageLabels(pdfDocument) { + const labels = await pdfDocument.getPageLabels(); + if (pdfDocument !== this.pdfDocument) { + return; + } + if (!labels || AppOptions.get("disablePageLabels")) { + return; + } + const numLabels = labels.length; + let standardLabels = 0, + emptyLabels = 0; + for (let i = 0; i < numLabels; i++) { + const label = labels[i]; + if (label === (i + 1).toString()) { + standardLabels++; + } else if (label === "") { + emptyLabels++; + } else { + break; + } + } + if (standardLabels >= numLabels || emptyLabels >= numLabels) { + return; + } + const { + pdfViewer, + pdfThumbnailViewer, + toolbar + } = this; + pdfViewer.setPageLabels(labels); + pdfThumbnailViewer?.setPageLabels(labels); + toolbar?.setPagesCount(numLabels, true); + toolbar?.setPageNumber(pdfViewer.currentPageNumber, pdfViewer.currentPageLabel); + }, + _initializePdfHistory({ + fingerprint, + viewOnLoad, + initialDest = null + }) { + if (!this.pdfHistory) { + return; + } + this.pdfHistory.initialize({ + fingerprint, + resetHistory: viewOnLoad === ViewOnLoad.INITIAL, + updateUrl: AppOptions.get("historyUpdateUrl") + }); + if (this.pdfHistory.initialBookmark) { + this.initialBookmark = this.pdfHistory.initialBookmark; + this.initialRotation = this.pdfHistory.initialRotation; + } + if (initialDest && !this.initialBookmark && viewOnLoad === ViewOnLoad.UNKNOWN) { + this.initialBookmark = JSON.stringify(initialDest); + this.pdfHistory.push({ + explicitDest: initialDest, + pageNumber: null + }); + } + }, + _initializeAnnotationStorageCallbacks(pdfDocument) { + if (pdfDocument !== this.pdfDocument) { + return; + } + const { + annotationStorage + } = pdfDocument; + annotationStorage.onSetModified = () => { + window.addEventListener("beforeunload", beforeUnload); + this._annotationStorageModified = true; + }; + annotationStorage.onResetModified = () => { + window.removeEventListener("beforeunload", beforeUnload); + delete this._annotationStorageModified; + }; + annotationStorage.onAnnotationEditor = typeStr => { + this._hasAnnotationEditors = !!typeStr; + this.setTitle(); + }; + }, + setInitialView(storedHash, { + rotation, + sidebarView, + scrollMode, + spreadMode + } = {}) { + const setRotation = angle => { + if (isValidRotation(angle)) { + this.pdfViewer.pagesRotation = angle; + } + }; + const setViewerModes = (scroll, spread) => { + if (isValidScrollMode(scroll)) { + this.pdfViewer.scrollMode = scroll; + } + if (isValidSpreadMode(spread)) { + this.pdfViewer.spreadMode = spread; + } + }; + this.isInitialViewSet = true; + this.pdfSidebar?.setInitialView(sidebarView); + setViewerModes(scrollMode, spreadMode); + if (this.initialBookmark) { + setRotation(this.initialRotation); + delete this.initialRotation; + this.pdfLinkService.setHash(this.initialBookmark); + this.initialBookmark = null; + } else if (storedHash) { + setRotation(rotation); + this.pdfLinkService.setHash(storedHash); + } + this.toolbar?.setPageNumber(this.pdfViewer.currentPageNumber, this.pdfViewer.currentPageLabel); + this.secondaryToolbar?.setPageNumber(this.pdfViewer.currentPageNumber); + if (!this.pdfViewer.currentScaleValue) { + this.pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE; + } + }, + _cleanup() { + if (!this.pdfDocument) { + return; + } + this.pdfViewer.cleanup(); + this.pdfThumbnailViewer?.cleanup(); + this.pdfDocument.cleanup(AppOptions.get("fontExtraProperties")); + }, + forceRendering() { + this.pdfRenderingQueue.printing = !!this.printService; + this.pdfRenderingQueue.isThumbnailViewEnabled = this.pdfSidebar?.visibleView === SidebarView.THUMBS; + this.pdfRenderingQueue.renderHighestPriority(); + }, + beforePrint() { + this._printAnnotationStoragePromise = this.pdfScriptingManager.dispatchWillPrint().catch(() => {}).then(() => this.pdfDocument?.annotationStorage.print); + if (this.printService) { + return; + } + if (!this.supportsPrinting) { + this._otherError("pdfjs-printing-not-supported"); + return; + } + if (!this.pdfViewer.pageViewsReady) { + this.l10n.get("pdfjs-printing-not-ready").then(msg => { + window.alert(msg); + }); + return; + } + this.printService = PDFPrintServiceFactory.createPrintService({ + pdfDocument: this.pdfDocument, + pagesOverview: this.pdfViewer.getPagesOverview(), + printContainer: this.appConfig.printContainer, + printResolution: AppOptions.get("printResolution"), + printAnnotationStoragePromise: this._printAnnotationStoragePromise + }); + this.forceRendering(); + this.setTitle(); + this.printService.layout(); + if (this._hasAnnotationEditors) { + this.externalServices.reportTelemetry({ + type: "editing", + data: { + type: "print", + stats: this.pdfDocument?.annotationStorage.editorStats + } + }); + } + }, + afterPrint() { + if (this._printAnnotationStoragePromise) { + this._printAnnotationStoragePromise.then(() => { + this.pdfScriptingManager.dispatchDidPrint(); + }); + this._printAnnotationStoragePromise = null; + } + if (this.printService) { + this.printService.destroy(); + this.printService = null; + this.pdfDocument?.annotationStorage.resetModified(); + } + this.forceRendering(); + this.setTitle(); + }, + rotatePages(delta) { + this.pdfViewer.pagesRotation += delta; + }, + requestPresentationMode() { + this.pdfPresentationMode?.request(); + }, + triggerPrinting() { + if (this.supportsPrinting) { + window.print(); + } + }, + bindEvents() { + if (this._eventBusAbortController) { + return; + } + const ac = this._eventBusAbortController = new AbortController(); + const opts = { + signal: ac.signal + }; + const { + eventBus, + externalServices, + pdfDocumentProperties, + pdfViewer, + preferences + } = this; + eventBus._on("resize", onResize.bind(this), opts); + eventBus._on("hashchange", onHashchange.bind(this), opts); + eventBus._on("beforeprint", this.beforePrint.bind(this), opts); + eventBus._on("afterprint", this.afterPrint.bind(this), opts); + eventBus._on("pagerender", onPageRender.bind(this), opts); + eventBus._on("pagerendered", onPageRendered.bind(this), opts); + eventBus._on("updateviewarea", onUpdateViewarea.bind(this), opts); + eventBus._on("pagechanging", onPageChanging.bind(this), opts); + eventBus._on("scalechanging", onScaleChanging.bind(this), opts); + eventBus._on("rotationchanging", onRotationChanging.bind(this), opts); + eventBus._on("sidebarviewchanged", onSidebarViewChanged.bind(this), opts); + eventBus._on("pagemode", onPageMode.bind(this), opts); + eventBus._on("namedaction", onNamedAction.bind(this), opts); + eventBus._on("presentationmodechanged", evt => pdfViewer.presentationModeState = evt.state, opts); + eventBus._on("presentationmode", this.requestPresentationMode.bind(this), opts); + eventBus._on("switchannotationeditormode", evt => pdfViewer.annotationEditorMode = evt, opts); + eventBus._on("print", this.triggerPrinting.bind(this), opts); + eventBus._on("download", this.downloadOrSave.bind(this), opts); + eventBus._on("firstpage", () => this.page = 1, opts); + eventBus._on("lastpage", () => this.page = this.pagesCount, opts); + eventBus._on("nextpage", () => pdfViewer.nextPage(), opts); + eventBus._on("previouspage", () => pdfViewer.previousPage(), opts); + eventBus._on("zoomin", this.zoomIn.bind(this), opts); + eventBus._on("zoomout", this.zoomOut.bind(this), opts); + eventBus._on("zoomreset", this.zoomReset.bind(this), opts); + eventBus._on("pagenumberchanged", onPageNumberChanged.bind(this), opts); + eventBus._on("scalechanged", evt => pdfViewer.currentScaleValue = evt.value, opts); + eventBus._on("rotatecw", this.rotatePages.bind(this, 90), opts); + eventBus._on("rotateccw", this.rotatePages.bind(this, -90), opts); + eventBus._on("optionalcontentconfig", evt => pdfViewer.optionalContentConfigPromise = evt.promise, opts); + eventBus._on("switchscrollmode", evt => pdfViewer.scrollMode = evt.mode, opts); + eventBus._on("scrollmodechanged", onViewerModesChanged.bind(this, "scrollMode"), opts); + eventBus._on("switchspreadmode", evt => pdfViewer.spreadMode = evt.mode, opts); + eventBus._on("spreadmodechanged", onViewerModesChanged.bind(this, "spreadMode"), opts); + eventBus._on("imagealttextsettings", onImageAltTextSettings.bind(this), opts); + eventBus._on("documentproperties", () => pdfDocumentProperties?.open(), opts); + eventBus._on("findfromurlhash", onFindFromUrlHash.bind(this), opts); + eventBus._on("updatefindmatchescount", onUpdateFindMatchesCount.bind(this), opts); + eventBus._on("updatefindcontrolstate", onUpdateFindControlState.bind(this), opts); + eventBus._on("fileinputchange", onFileInputChange.bind(this), opts); + eventBus._on("openfile", onOpenFile.bind(this), opts); + }, + bindWindowEvents() { + if (this._windowAbortController) { + return; + } + this._windowAbortController = new AbortController(); + const { + eventBus, + appConfig: { + mainContainer + }, + pdfViewer, + _windowAbortController: { + signal + } + } = this; + function addWindowResolutionChange(evt = null) { + if (evt) { + pdfViewer.refresh(); + } + const mediaQueryList = window.matchMedia(`(resolution: ${window.devicePixelRatio || 1}dppx)`); + mediaQueryList.addEventListener("change", addWindowResolutionChange, { + once: true, + signal + }); + } + addWindowResolutionChange(); + window.addEventListener("wheel", onWheel.bind(this), { + passive: false, + signal + }); + window.addEventListener("touchstart", onTouchStart.bind(this), { + passive: false, + signal + }); + window.addEventListener("touchmove", onTouchMove.bind(this), { + passive: false, + signal + }); + window.addEventListener("touchend", onTouchEnd.bind(this), { + passive: false, + signal + }); + window.addEventListener("click", onClick.bind(this), { + signal + }); + window.addEventListener("keydown", onKeyDown.bind(this), { + signal + }); + window.addEventListener("keyup", onKeyUp.bind(this), { + signal + }); + window.addEventListener("resize", () => eventBus.dispatch("resize", { + source: window + }), { + signal + }); + window.addEventListener("hashchange", () => { + eventBus.dispatch("hashchange", { + source: window, + hash: document.location.hash.substring(1) + }); + }, { + signal + }); + window.addEventListener("beforeprint", () => eventBus.dispatch("beforeprint", { + source: window + }), { + signal + }); + window.addEventListener("afterprint", () => eventBus.dispatch("afterprint", { + source: window + }), { + signal + }); + window.addEventListener("updatefromsandbox", evt => { + eventBus.dispatch("updatefromsandbox", { + source: window, + detail: evt.detail + }); + }, { + signal + }); + if (!("onscrollend" in document.documentElement)) { + return; + } + ({ + scrollTop: this._lastScrollTop, + scrollLeft: this._lastScrollLeft + } = mainContainer); + const scrollend = () => { + ({ + scrollTop: this._lastScrollTop, + scrollLeft: this._lastScrollLeft + } = mainContainer); + this._isScrolling = false; + mainContainer.addEventListener("scroll", scroll, { + passive: true, + signal + }); + mainContainer.removeEventListener("scrollend", scrollend); + mainContainer.removeEventListener("blur", scrollend); + }; + const scroll = () => { + if (this._isCtrlKeyDown) { + return; + } + if (this._lastScrollTop === mainContainer.scrollTop && this._lastScrollLeft === mainContainer.scrollLeft) { + return; + } + mainContainer.removeEventListener("scroll", scroll); + this._isScrolling = true; + mainContainer.addEventListener("scrollend", scrollend, { + signal + }); + mainContainer.addEventListener("blur", scrollend, { + signal + }); + }; + mainContainer.addEventListener("scroll", scroll, { + passive: true, + signal + }); + }, + unbindEvents() { + this._eventBusAbortController?.abort(); + this._eventBusAbortController = null; + }, + unbindWindowEvents() { + this._windowAbortController?.abort(); + this._windowAbortController = null; + }, + async testingClose() { + this.unbindEvents(); + this.unbindWindowEvents(); + this._globalAbortController?.abort(); + this._globalAbortController = null; + this.findBar?.close(); + await Promise.all([this.l10n?.destroy(), this.close()]); + }, + _accumulateTicks(ticks, prop) { + if (this[prop] > 0 && ticks < 0 || this[prop] < 0 && ticks > 0) { + this[prop] = 0; + } + this[prop] += ticks; + const wholeTicks = Math.trunc(this[prop]); + this[prop] -= wholeTicks; + return wholeTicks; + }, + _accumulateFactor(previousScale, factor, prop) { + if (factor === 1) { + return 1; + } + if (this[prop] > 1 && factor < 1 || this[prop] < 1 && factor > 1) { + this[prop] = 1; + } + const newFactor = Math.floor(previousScale * factor * this[prop] * 100) / (100 * previousScale); + this[prop] = factor / newFactor; + return newFactor; + }, + _unblockDocumentLoadEvent() { + document.blockUnblockOnload?.(false); + this._unblockDocumentLoadEvent = () => {}; + }, + get scriptingReady() { + return this.pdfScriptingManager.ready; + } +}; +initCom(PDFViewerApplication); +{ + PDFPrintServiceFactory.initGlobals(PDFViewerApplication); +} +{ + const HOSTED_VIEWER_ORIGINS = ["null", "http://mozilla.github.io", "https://mozilla.github.io"]; + var validateFileURL = function (file) { + if (!file) { + return; + } + try { + const viewerOrigin = new URL(window.location.href).origin || "null"; + if (HOSTED_VIEWER_ORIGINS.includes(viewerOrigin)) { + return; + } + const fileOrigin = new URL(file, window.location.href).origin; + if (fileOrigin !== viewerOrigin) { + throw new Error("file origin does not match viewer's"); + } + } catch (ex) { + PDFViewerApplication._documentError("pdfjs-loading-error", { + message: ex.message + }); + throw ex; + } + }; + var onFileInputChange = function (evt) { + if (this.pdfViewer?.isInPresentationMode) { + return; + } + const file = evt.fileInput.files[0]; + this.open({ + url: URL.createObjectURL(file), + originalUrl: file.name + }); + }; + var onOpenFile = function (evt) { + this._openFileInput?.click(); + }; +} +function onPageRender({ + pageNumber +}) { + if (pageNumber === this.page) { + this.toolbar?.updateLoadingIndicatorState(true); + } +} +function onPageRendered({ + pageNumber, + error +}) { + if (pageNumber === this.page) { + this.toolbar?.updateLoadingIndicatorState(false); + } + if (this.pdfSidebar?.visibleView === SidebarView.THUMBS) { + const pageView = this.pdfViewer.getPageView(pageNumber - 1); + const thumbnailView = this.pdfThumbnailViewer?.getThumbnail(pageNumber - 1); + if (pageView) { + thumbnailView?.setImage(pageView); + } + } + if (error) { + this._otherError("pdfjs-rendering-error", error); + } +} +function onPageMode({ + mode +}) { + let view; + switch (mode) { + case "thumbs": + view = SidebarView.THUMBS; + break; + case "bookmarks": + case "outline": + view = SidebarView.OUTLINE; + break; + case "attachments": + view = SidebarView.ATTACHMENTS; + break; + case "layers": + view = SidebarView.LAYERS; + break; + case "none": + view = SidebarView.NONE; + break; + default: + console.error('Invalid "pagemode" hash parameter: ' + mode); + return; + } + this.pdfSidebar?.switchView(view, true); +} +function onNamedAction(evt) { + switch (evt.action) { + case "GoToPage": + this.appConfig.toolbar?.pageNumber.select(); + break; + case "Find": + if (!this.supportsIntegratedFind) { + this.findBar?.toggle(); + } + break; + case "Print": + this.triggerPrinting(); + break; + case "SaveAs": + this.downloadOrSave(); + break; + } +} +function onSidebarViewChanged({ + view +}) { + this.pdfRenderingQueue.isThumbnailViewEnabled = view === SidebarView.THUMBS; + if (this.isInitialViewSet) { + this.store?.set("sidebarView", view).catch(() => {}); + } +} +function onUpdateViewarea({ + location +}) { + if (this.isInitialViewSet) { + this.store?.setMultiple({ + page: location.pageNumber, + zoom: location.scale, + scrollLeft: location.left, + scrollTop: location.top, + rotation: location.rotation + }).catch(() => {}); + } + if (this.appConfig.secondaryToolbar) { + this.appConfig.secondaryToolbar.viewBookmarkButton.href = this.pdfLinkService.getAnchorUrl(location.pdfOpenParams); + } +} +function onViewerModesChanged(name, evt) { + if (this.isInitialViewSet && !this.pdfViewer.isInPresentationMode) { + this.store?.set(name, evt.mode).catch(() => {}); + } +} +function onResize() { + const { + pdfDocument, + pdfViewer, + pdfRenderingQueue + } = this; + if (pdfRenderingQueue.printing && window.matchMedia("print").matches) { + return; + } + if (!pdfDocument) { + return; + } + const currentScaleValue = pdfViewer.currentScaleValue; + if (currentScaleValue === "auto" || currentScaleValue === "page-fit" || currentScaleValue === "page-width") { + pdfViewer.currentScaleValue = currentScaleValue; + } + pdfViewer.update(); +} +function onHashchange(evt) { + const hash = evt.hash; + if (!hash) { + return; + } + if (!this.isInitialViewSet) { + this.initialBookmark = hash; + } else if (!this.pdfHistory?.popStateInProgress) { + this.pdfLinkService.setHash(hash); + } +} +function onPageNumberChanged(evt) { + const { + pdfViewer + } = this; + if (evt.value !== "") { + this.pdfLinkService.goToPage(evt.value); + } + if (evt.value !== pdfViewer.currentPageNumber.toString() && evt.value !== pdfViewer.currentPageLabel) { + this.toolbar?.setPageNumber(pdfViewer.currentPageNumber, pdfViewer.currentPageLabel); + } +} +function onImageAltTextSettings() { + this.imageAltTextSettings?.open({ + enableGuessAltText: AppOptions.get("enableGuessAltText"), + enableNewAltTextWhenAddingImage: AppOptions.get("enableNewAltTextWhenAddingImage") + }); +} +function onFindFromUrlHash(evt) { + this.eventBus.dispatch("find", { + source: evt.source, + type: "", + query: evt.query, + caseSensitive: false, + entireWord: false, + highlightAll: true, + findPrevious: false, + matchDiacritics: true + }); +} +function onUpdateFindMatchesCount({ + matchesCount +}) { + if (this.supportsIntegratedFind) { + this.externalServices.updateFindMatchesCount(matchesCount); + } else { + this.findBar?.updateResultsCount(matchesCount); + } +} +function onUpdateFindControlState({ + state, + previous, + entireWord, + matchesCount, + rawQuery +}) { + if (this.supportsIntegratedFind) { + this.externalServices.updateFindControlState({ + result: state, + findPrevious: previous, + entireWord, + matchesCount, + rawQuery + }); + } else { + this.findBar?.updateUIState(state, previous, matchesCount); + } +} +function onScaleChanging(evt) { + this.toolbar?.setPageScale(evt.presetValue, evt.scale); + this.pdfViewer.update(); +} +function onRotationChanging(evt) { + if (this.pdfThumbnailViewer) { + this.pdfThumbnailViewer.pagesRotation = evt.pagesRotation; + } + this.forceRendering(); + this.pdfViewer.currentPageNumber = evt.pageNumber; +} +function onPageChanging({ + pageNumber, + pageLabel +}) { + this.toolbar?.setPageNumber(pageNumber, pageLabel); + this.secondaryToolbar?.setPageNumber(pageNumber); + if (this.pdfSidebar?.visibleView === SidebarView.THUMBS) { + this.pdfThumbnailViewer?.scrollThumbnailIntoView(pageNumber); + } + const currentPage = this.pdfViewer.getPageView(pageNumber - 1); + this.toolbar?.updateLoadingIndicatorState(currentPage?.renderingState === RenderingStates.RUNNING); +} +function onWheel(evt) { + const { + pdfViewer, + supportsMouseWheelZoomCtrlKey, + supportsMouseWheelZoomMetaKey, + supportsPinchToZoom + } = this; + if (pdfViewer.isInPresentationMode) { + return; + } + const deltaMode = evt.deltaMode; + let scaleFactor = Math.exp(-evt.deltaY / 100); + const isBuiltInMac = false; + const isPinchToZoom = evt.ctrlKey && !this._isCtrlKeyDown && deltaMode === WheelEvent.DOM_DELTA_PIXEL && evt.deltaX === 0 && (Math.abs(scaleFactor - 1) < 0.05 || isBuiltInMac) && evt.deltaZ === 0; + const origin = [evt.clientX, evt.clientY]; + if (isPinchToZoom || evt.ctrlKey && supportsMouseWheelZoomCtrlKey || evt.metaKey && supportsMouseWheelZoomMetaKey) { + evt.preventDefault(); + if (this._isScrolling || document.visibilityState === "hidden" || this.overlayManager.active) { + return; + } + if (isPinchToZoom && supportsPinchToZoom) { + scaleFactor = this._accumulateFactor(pdfViewer.currentScale, scaleFactor, "_wheelUnusedFactor"); + this.updateZoom(null, scaleFactor, origin); + } else { + const delta = normalizeWheelEventDirection(evt); + let ticks = 0; + if (deltaMode === WheelEvent.DOM_DELTA_LINE || deltaMode === WheelEvent.DOM_DELTA_PAGE) { + ticks = Math.abs(delta) >= 1 ? Math.sign(delta) : this._accumulateTicks(delta, "_wheelUnusedTicks"); + } else { + const PIXELS_PER_LINE_SCALE = 30; + ticks = this._accumulateTicks(delta / PIXELS_PER_LINE_SCALE, "_wheelUnusedTicks"); + } + this.updateZoom(ticks, null, origin); + } + } +} +function onTouchStart(evt) { + if (this.pdfViewer.isInPresentationMode || evt.touches.length < 2) { + return; + } + evt.preventDefault(); + if (evt.touches.length !== 2 || this.overlayManager.active) { + this._touchInfo = null; + return; + } + let [touch0, touch1] = evt.touches; + if (touch0.identifier > touch1.identifier) { + [touch0, touch1] = [touch1, touch0]; + } + this._touchInfo = { + touch0X: touch0.screenX, + touch0Y: touch0.screenY, + touch1X: touch1.screenX, + touch1Y: touch1.screenY + }; +} +function onTouchMove(evt) { + if (!this._touchInfo || evt.touches.length !== 2) { + return; + } + const { + pdfViewer, + _touchInfo, + supportsPinchToZoom + } = this; + let [touch0, touch1] = evt.touches; + if (touch0.identifier > touch1.identifier) { + [touch0, touch1] = [touch1, touch0]; + } + const { + screenX: screen0X, + screenY: screen0Y + } = touch0; + const { + screenX: screen1X, + screenY: screen1Y + } = touch1; + const { + touch0X: pTouch0X, + touch0Y: pTouch0Y, + touch1X: pTouch1X, + touch1Y: pTouch1Y + } = _touchInfo; + const prevGapX = pTouch1X - pTouch0X; + const prevGapY = pTouch1Y - pTouch0Y; + const currGapX = screen1X - screen0X; + const currGapY = screen1Y - screen0Y; + const distance = Math.hypot(currGapX, currGapY) || 1; + const pDistance = Math.hypot(prevGapX, prevGapY) || 1; + if (!this._isPinching && Math.abs(pDistance - distance) <= MIN_TOUCH_DISTANCE_TO_PINCH) { + return; + } + _touchInfo.touch0X = screen0X; + _touchInfo.touch0Y = screen0Y; + _touchInfo.touch1X = screen1X; + _touchInfo.touch1Y = screen1Y; + evt.preventDefault(); + if (!this._isPinching) { + this._isPinching = true; + return; + } + const origin = [(screen0X + screen1X) / 2, (screen0Y + screen1Y) / 2]; + if (supportsPinchToZoom) { + const newScaleFactor = this._accumulateFactor(pdfViewer.currentScale, distance / pDistance, "_touchUnusedFactor"); + this.updateZoom(null, newScaleFactor, origin); + } else { + const PIXELS_PER_LINE_SCALE = 30; + const ticks = this._accumulateTicks((distance - pDistance) / PIXELS_PER_LINE_SCALE, "_touchUnusedTicks"); + this.updateZoom(ticks, null, origin); + } +} +function onTouchEnd(evt) { + if (!this._touchInfo) { + return; + } + evt.preventDefault(); + this._touchInfo = null; + this._touchUnusedTicks = 0; + this._touchUnusedFactor = 1; + this._isPinching = false; +} +function closeSecondaryToolbar(evt) { + if (!this.secondaryToolbar?.isOpen) { + return; + } + const appConfig = this.appConfig; + if (this.pdfViewer.containsElement(evt.target) || appConfig.toolbar?.container.contains(evt.target) && !appConfig.secondaryToolbar?.toggleButton.contains(evt.target)) { + this.secondaryToolbar.close(); + } +} +function closeEditorUndoBar(evt) { + if (!this.editorUndoBar?.isOpen) { + return; + } + if (this.appConfig.secondaryToolbar?.toolbar.contains(evt.target)) { + this.editorUndoBar.hide(); + } +} +function onClick(evt) { + closeSecondaryToolbar.call(this, evt); + closeEditorUndoBar.call(this, evt); +} +function onKeyUp(evt) { + if (evt.key === "Control") { + this._isCtrlKeyDown = false; + } +} +function onKeyDown(evt) { + this._isCtrlKeyDown = evt.key === "Control"; + if (this.editorUndoBar?.isOpen && evt.keyCode !== 9 && evt.keyCode !== 16 && !((evt.keyCode === 13 || evt.keyCode === 32) && getActiveOrFocusedElement() === this.appConfig.editorUndoBar.undoButton)) { + this.editorUndoBar.hide(); + } + if (this.overlayManager.active) { + return; + } + const { + eventBus, + pdfViewer + } = this; + const isViewerInPresentationMode = pdfViewer.isInPresentationMode; + let handled = false, + ensureViewerFocused = false; + const cmd = (evt.ctrlKey ? 1 : 0) | (evt.altKey ? 2 : 0) | (evt.shiftKey ? 4 : 0) | (evt.metaKey ? 8 : 0); + if (cmd === 1 || cmd === 8 || cmd === 5 || cmd === 12) { + switch (evt.keyCode) { + case 70: + if (!this.supportsIntegratedFind && !evt.shiftKey) { + this.findBar?.open(); + handled = true; + } + break; + case 71: + if (!this.supportsIntegratedFind) { + const { + state + } = this.findController; + if (state) { + const newState = { + source: window, + type: "again", + findPrevious: cmd === 5 || cmd === 12 + }; + eventBus.dispatch("find", { + ...state, + ...newState + }); + } + handled = true; + } + break; + case 61: + case 107: + case 187: + case 171: + this.zoomIn(); + handled = true; + break; + case 173: + case 109: + case 189: + this.zoomOut(); + handled = true; + break; + case 48: + case 96: + if (!isViewerInPresentationMode) { + setTimeout(() => { + this.zoomReset(); + }); + handled = false; + } + break; + case 38: + if (isViewerInPresentationMode || this.page > 1) { + this.page = 1; + handled = true; + ensureViewerFocused = true; + } + break; + case 40: + if (isViewerInPresentationMode || this.page < this.pagesCount) { + this.page = this.pagesCount; + handled = true; + ensureViewerFocused = true; + } + break; + } + } + if (cmd === 1 || cmd === 8) { + switch (evt.keyCode) { + case 83: + eventBus.dispatch("download", { + source: window + }); + handled = true; + break; + case 79: + { + eventBus.dispatch("openfile", { + source: window + }); + handled = true; + } + break; + } + } + if (cmd === 3 || cmd === 10) { + switch (evt.keyCode) { + case 80: + this.requestPresentationMode(); + handled = true; + this.externalServices.reportTelemetry({ + type: "buttons", + data: { + id: "presentationModeKeyboard" + } + }); + break; + case 71: + if (this.appConfig.toolbar) { + this.appConfig.toolbar.pageNumber.select(); + handled = true; + } + break; + } + } + if (handled) { + if (ensureViewerFocused && !isViewerInPresentationMode) { + pdfViewer.focus(); + } + evt.preventDefault(); + return; + } + const curElement = getActiveOrFocusedElement(); + const curElementTagName = curElement?.tagName.toUpperCase(); + if (curElementTagName === "INPUT" || curElementTagName === "TEXTAREA" || curElementTagName === "SELECT" || curElementTagName === "BUTTON" && (evt.keyCode === 13 || evt.keyCode === 32) || curElement?.isContentEditable) { + if (evt.keyCode !== 27) { + return; + } + } + if (cmd === 0) { + let turnPage = 0, + turnOnlyIfPageFit = false; + switch (evt.keyCode) { + case 38: + if (this.supportsCaretBrowsingMode) { + this.moveCaret(true, false); + handled = true; + break; + } + case 33: + if (pdfViewer.isVerticalScrollbarEnabled) { + turnOnlyIfPageFit = true; + } + turnPage = -1; + break; + case 8: + if (!isViewerInPresentationMode) { + turnOnlyIfPageFit = true; + } + turnPage = -1; + break; + case 37: + if (this.supportsCaretBrowsingMode) { + return; + } + if (pdfViewer.isHorizontalScrollbarEnabled) { + turnOnlyIfPageFit = true; + } + case 75: + case 80: + turnPage = -1; + break; + case 27: + if (this.secondaryToolbar?.isOpen) { + this.secondaryToolbar.close(); + handled = true; + } + if (!this.supportsIntegratedFind && this.findBar?.opened) { + this.findBar.close(); + handled = true; + } + break; + case 40: + if (this.supportsCaretBrowsingMode) { + this.moveCaret(false, false); + handled = true; + break; + } + case 34: + if (pdfViewer.isVerticalScrollbarEnabled) { + turnOnlyIfPageFit = true; + } + turnPage = 1; + break; + case 13: + case 32: + if (!isViewerInPresentationMode) { + turnOnlyIfPageFit = true; + } + turnPage = 1; + break; + case 39: + if (this.supportsCaretBrowsingMode) { + return; + } + if (pdfViewer.isHorizontalScrollbarEnabled) { + turnOnlyIfPageFit = true; + } + case 74: + case 78: + turnPage = 1; + break; + case 36: + if (isViewerInPresentationMode || this.page > 1) { + this.page = 1; + handled = true; + ensureViewerFocused = true; + } + break; + case 35: + if (isViewerInPresentationMode || this.page < this.pagesCount) { + this.page = this.pagesCount; + handled = true; + ensureViewerFocused = true; + } + break; + case 83: + this.pdfCursorTools?.switchTool(CursorTool.SELECT); + break; + case 72: + this.pdfCursorTools?.switchTool(CursorTool.HAND); + break; + case 82: + this.rotatePages(90); + break; + case 115: + this.pdfSidebar?.toggle(); + break; + } + if (turnPage !== 0 && (!turnOnlyIfPageFit || pdfViewer.currentScaleValue === "page-fit")) { + if (turnPage > 0) { + pdfViewer.nextPage(); + } else { + pdfViewer.previousPage(); + } + handled = true; + } + } + if (cmd === 4) { + switch (evt.keyCode) { + case 13: + case 32: + if (!isViewerInPresentationMode && pdfViewer.currentScaleValue !== "page-fit") { + break; + } + pdfViewer.previousPage(); + handled = true; + break; + case 38: + this.moveCaret(true, true); + handled = true; + break; + case 40: + this.moveCaret(false, true); + handled = true; + break; + case 82: + this.rotatePages(-90); + break; + } + } + if (!handled && !isViewerInPresentationMode) { + if (evt.keyCode >= 33 && evt.keyCode <= 40 || evt.keyCode === 32 && curElementTagName !== "BUTTON") { + ensureViewerFocused = true; + } + } + if (ensureViewerFocused && !pdfViewer.containsElement(curElement)) { + pdfViewer.focus(); + } + if (handled) { + evt.preventDefault(); + } +} +function beforeUnload(evt) { + evt.preventDefault(); + evt.returnValue = ""; + return false; +} + +;// ./web/viewer.js + + + + +const pdfjsVersion = "4.9.155"; +const pdfjsBuild = "a4eb8407c"; +const AppConstants = { + LinkTarget: LinkTarget, + RenderingStates: RenderingStates, + ScrollMode: ScrollMode, + SpreadMode: SpreadMode +}; +window.PDFViewerApplication = PDFViewerApplication; +window.PDFViewerApplicationConstants = AppConstants; +window.PDFViewerApplicationOptions = AppOptions; +function getViewerConfiguration() { + return { + appContainer: document.body, + principalContainer: document.getElementById("mainContainer"), + mainContainer: document.getElementById("viewerContainer"), + viewerContainer: document.getElementById("viewer"), + toolbar: { + container: document.getElementById("toolbarContainer"), + numPages: document.getElementById("numPages"), + pageNumber: document.getElementById("pageNumber"), + scaleSelect: document.getElementById("scaleSelect"), + customScaleOption: document.getElementById("customScaleOption"), + previous: document.getElementById("previous"), + next: document.getElementById("next"), + zoomIn: document.getElementById("zoomInButton"), + zoomOut: document.getElementById("zoomOutButton"), + print: document.getElementById("printButton"), + editorFreeTextButton: document.getElementById("editorFreeTextButton"), + editorFreeTextParamsToolbar: document.getElementById("editorFreeTextParamsToolbar"), + editorHighlightButton: document.getElementById("editorHighlightButton"), + editorHighlightParamsToolbar: document.getElementById("editorHighlightParamsToolbar"), + editorHighlightColorPicker: document.getElementById("editorHighlightColorPicker"), + editorInkButton: document.getElementById("editorInkButton"), + editorInkParamsToolbar: document.getElementById("editorInkParamsToolbar"), + editorStampButton: document.getElementById("editorStampButton"), + editorStampParamsToolbar: document.getElementById("editorStampParamsToolbar"), + download: document.getElementById("downloadButton") + }, + secondaryToolbar: { + toolbar: document.getElementById("secondaryToolbar"), + toggleButton: document.getElementById("secondaryToolbarToggleButton"), + presentationModeButton: document.getElementById("presentationMode"), + openFileButton: document.getElementById("secondaryOpenFile"), + printButton: document.getElementById("secondaryPrint"), + downloadButton: document.getElementById("secondaryDownload"), + viewBookmarkButton: document.getElementById("viewBookmark"), + firstPageButton: document.getElementById("firstPage"), + lastPageButton: document.getElementById("lastPage"), + pageRotateCwButton: document.getElementById("pageRotateCw"), + pageRotateCcwButton: document.getElementById("pageRotateCcw"), + cursorSelectToolButton: document.getElementById("cursorSelectTool"), + cursorHandToolButton: document.getElementById("cursorHandTool"), + scrollPageButton: document.getElementById("scrollPage"), + scrollVerticalButton: document.getElementById("scrollVertical"), + scrollHorizontalButton: document.getElementById("scrollHorizontal"), + scrollWrappedButton: document.getElementById("scrollWrapped"), + spreadNoneButton: document.getElementById("spreadNone"), + spreadOddButton: document.getElementById("spreadOdd"), + spreadEvenButton: document.getElementById("spreadEven"), + imageAltTextSettingsButton: document.getElementById("imageAltTextSettings"), + imageAltTextSettingsSeparator: document.getElementById("imageAltTextSettingsSeparator"), + documentPropertiesButton: document.getElementById("documentProperties") + }, + sidebar: { + outerContainer: document.getElementById("outerContainer"), + sidebarContainer: document.getElementById("sidebarContainer"), + toggleButton: document.getElementById("sidebarToggleButton"), + resizer: document.getElementById("sidebarResizer"), + thumbnailButton: document.getElementById("viewThumbnail"), + outlineButton: document.getElementById("viewOutline"), + attachmentsButton: document.getElementById("viewAttachments"), + layersButton: document.getElementById("viewLayers"), + thumbnailView: document.getElementById("thumbnailView"), + outlineView: document.getElementById("outlineView"), + attachmentsView: document.getElementById("attachmentsView"), + layersView: document.getElementById("layersView"), + currentOutlineItemButton: document.getElementById("currentOutlineItem") + }, + findBar: { + bar: document.getElementById("findbar"), + toggleButton: document.getElementById("viewFindButton"), + findField: document.getElementById("findInput"), + highlightAllCheckbox: document.getElementById("findHighlightAll"), + caseSensitiveCheckbox: document.getElementById("findMatchCase"), + matchDiacriticsCheckbox: document.getElementById("findMatchDiacritics"), + entireWordCheckbox: document.getElementById("findEntireWord"), + findMsg: document.getElementById("findMsg"), + findResultsCount: document.getElementById("findResultsCount"), + findPreviousButton: document.getElementById("findPreviousButton"), + findNextButton: document.getElementById("findNextButton") + }, + passwordOverlay: { + dialog: document.getElementById("passwordDialog"), + label: document.getElementById("passwordText"), + input: document.getElementById("password"), + submitButton: document.getElementById("passwordSubmit"), + cancelButton: document.getElementById("passwordCancel") + }, + documentProperties: { + dialog: document.getElementById("documentPropertiesDialog"), + closeButton: document.getElementById("documentPropertiesClose"), + fields: { + fileName: document.getElementById("fileNameField"), + fileSize: document.getElementById("fileSizeField"), + title: document.getElementById("titleField"), + author: document.getElementById("authorField"), + subject: document.getElementById("subjectField"), + keywords: document.getElementById("keywordsField"), + creationDate: document.getElementById("creationDateField"), + modificationDate: document.getElementById("modificationDateField"), + creator: document.getElementById("creatorField"), + producer: document.getElementById("producerField"), + version: document.getElementById("versionField"), + pageCount: document.getElementById("pageCountField"), + pageSize: document.getElementById("pageSizeField"), + linearized: document.getElementById("linearizedField") + } + }, + altTextDialog: { + dialog: document.getElementById("altTextDialog"), + optionDescription: document.getElementById("descriptionButton"), + optionDecorative: document.getElementById("decorativeButton"), + textarea: document.getElementById("descriptionTextarea"), + cancelButton: document.getElementById("altTextCancel"), + saveButton: document.getElementById("altTextSave") + }, + newAltTextDialog: { + dialog: document.getElementById("newAltTextDialog"), + title: document.getElementById("newAltTextTitle"), + descriptionContainer: document.getElementById("newAltTextDescriptionContainer"), + textarea: document.getElementById("newAltTextDescriptionTextarea"), + disclaimer: document.getElementById("newAltTextDisclaimer"), + learnMore: document.getElementById("newAltTextLearnMore"), + imagePreview: document.getElementById("newAltTextImagePreview"), + createAutomatically: document.getElementById("newAltTextCreateAutomatically"), + createAutomaticallyButton: document.getElementById("newAltTextCreateAutomaticallyButton"), + downloadModel: document.getElementById("newAltTextDownloadModel"), + downloadModelDescription: document.getElementById("newAltTextDownloadModelDescription"), + error: document.getElementById("newAltTextError"), + errorCloseButton: document.getElementById("newAltTextCloseButton"), + cancelButton: document.getElementById("newAltTextCancel"), + notNowButton: document.getElementById("newAltTextNotNow"), + saveButton: document.getElementById("newAltTextSave") + }, + altTextSettingsDialog: { + dialog: document.getElementById("altTextSettingsDialog"), + createModelButton: document.getElementById("createModelButton"), + aiModelSettings: document.getElementById("aiModelSettings"), + learnMore: document.getElementById("altTextSettingsLearnMore"), + deleteModelButton: document.getElementById("deleteModelButton"), + downloadModelButton: document.getElementById("downloadModelButton"), + showAltTextDialogButton: document.getElementById("showAltTextDialogButton"), + altTextSettingsCloseButton: document.getElementById("altTextSettingsCloseButton"), + closeButton: document.getElementById("altTextSettingsCloseButton") + }, + annotationEditorParams: { + editorFreeTextFontSize: document.getElementById("editorFreeTextFontSize"), + editorFreeTextColor: document.getElementById("editorFreeTextColor"), + editorInkColor: document.getElementById("editorInkColor"), + editorInkThickness: document.getElementById("editorInkThickness"), + editorInkOpacity: document.getElementById("editorInkOpacity"), + editorStampAddImage: document.getElementById("editorStampAddImage"), + editorFreeHighlightThickness: document.getElementById("editorFreeHighlightThickness"), + editorHighlightShowAll: document.getElementById("editorHighlightShowAll") + }, + printContainer: document.getElementById("printContainer"), + editorUndoBar: { + container: document.getElementById("editorUndoBar"), + message: document.getElementById("editorUndoBarMessage"), + undoButton: document.getElementById("editorUndoBarUndoButton"), + closeButton: document.getElementById("editorUndoBarCloseButton") + } + }; +} +function webViewerLoad() { + const config = getViewerConfiguration(); + const event = new CustomEvent("webviewerloaded", { + bubbles: true, + cancelable: true, + detail: { + source: window + } + }); + try { + parent.document.dispatchEvent(event); + } catch (ex) { + console.error(`webviewerloaded: ${ex}`); + document.dispatchEvent(event); + } + PDFViewerApplication.run(config); +} +document.blockUnblockOnload?.(true); +if (document.readyState === "interactive" || document.readyState === "complete") { + webViewerLoad(); +} else { + document.addEventListener("DOMContentLoaded", webViewerLoad, true); +} + +var __webpack_exports__PDFViewerApplication = __webpack_exports__.PDFViewerApplication; +var __webpack_exports__PDFViewerApplicationConstants = __webpack_exports__.PDFViewerApplicationConstants; +var __webpack_exports__PDFViewerApplicationOptions = __webpack_exports__.PDFViewerApplicationOptions; +export { __webpack_exports__PDFViewerApplication as PDFViewerApplication, __webpack_exports__PDFViewerApplicationConstants as PDFViewerApplicationConstants, __webpack_exports__PDFViewerApplicationOptions as PDFViewerApplicationOptions }; + +//# sourceMappingURL=viewer.mjs.map \ No newline at end of file diff --git a/pdfjs/web/viewer.mjs.map b/pdfjs/web/viewer.mjs.map new file mode 100644 index 0000000..8316ad4 --- /dev/null +++ b/pdfjs/web/viewer.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"viewer.mjs","mappings":";;;;;;;;;;;;;;;;;;;;;;SAAA;SACA;;;;;UCDA;UACA;UACA;UACA;UACA,yCAAyC,wCAAwC;UACjF;UACA;UACA;;;;;UCPA;;;;;;;;;;;;;;ACeA,MAAMA,mBAAmB,GAAG,MAAM;AAClC,MAAMC,aAAa,GAAG,GAAG;AACzB,MAAMC,mBAAmB,GAAG,GAAG;AAC/B,MAAMC,SAAS,GAAG,GAAG;AACrB,MAAMC,SAAS,GAAG,IAAI;AACtB,MAAMC,aAAa,GAAG,CAAC;AACvB,MAAMC,cAAc,GAAG,IAAI;AAC3B,MAAMC,iBAAiB,GAAG,EAAE;AAC5B,MAAMC,gBAAgB,GAAG,CAAC;AAE1B,MAAMC,eAAe,GAAG;EACtBC,OAAO,EAAE,CAAC;EACVC,OAAO,EAAE,CAAC;EACVC,MAAM,EAAE,CAAC;EACTC,QAAQ,EAAE;AACZ,CAAC;AAED,MAAMC,qBAAqB,GAAG;EAC5BC,OAAO,EAAE,CAAC;EACVC,MAAM,EAAE,CAAC;EACTC,QAAQ,EAAE,CAAC;EACXC,UAAU,EAAE;AACd,CAAC;AAED,MAAMC,WAAW,GAAG;EAClBJ,OAAO,EAAE,CAAC,CAAC;EACXK,IAAI,EAAE,CAAC;EACPC,MAAM,EAAE,CAAC;EACTC,OAAO,EAAE,CAAC;EACVC,WAAW,EAAE,CAAC;EACdC,MAAM,EAAE;AACV,CAAC;AAED,MAAMC,aAAa,GAAG;EACpBC,OAAO,EAAE,CAAC;EACVC,MAAM,EAAE,CAAC;EACTC,kBAAkB,EAAE;AACtB,CAAC;AAED,MAAMC,UAAU,GAAG;EACjBd,OAAO,EAAE,CAAC,CAAC;EACXe,QAAQ,EAAE,CAAC;EACX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,MAAM,CAAC;AAClC;AAIA9gF,QAAQ,CAACipF,kBAAkB,GAAG,IAAI,CAAC;AAEnC,IACEjpF,QAAQ,CAAC0sF,UAAU,KAAK,aAAa,IACrC1sF,QAAQ,CAAC0sF,UAAU,KAAK,UAAU,EAClC;EACAD,aAAa,CAAC,CAAC;AACjB,CAAC,MAAM;EACLzsF,QAAQ,CAACrI,gBAAgB,CAAC,kBAAkB,EAAE80F,aAAa,EAAE,IAAI,CAAC;AACpE","sources":["webpack://pdf.js/webpack/bootstrap","webpack://pdf.js/webpack/runtime/define property getters","webpack://pdf.js/webpack/runtime/hasOwnProperty shorthand","webpack://pdf.js/./web/ui_utils.js","webpack://pdf.js/./web/app_options.js","webpack://pdf.js/./web/pdf_link_service.js","webpack://pdf.js/./web/pdfjs.js","webpack://pdf.js/./web/event_utils.js","webpack://pdf.js/./web/external_services.js","webpack://pdf.js/./web/preferences.js","webpack://pdf.js/./node_modules/@fluent/bundle/esm/types.js","webpack://pdf.js/./node_modules/@fluent/bundle/esm/resolver.js","webpack://pdf.js/./node_modules/@fluent/bundle/esm/scope.js","webpack://pdf.js/./node_modules/@fluent/bundle/esm/builtins.js","webpack://pdf.js/./node_modules/@fluent/bundle/esm/memoizer.js","webpack://pdf.js/./node_modules/@fluent/bundle/esm/bundle.js","webpack://pdf.js/./node_modules/@fluent/bundle/esm/resource.js","webpack://pdf.js/./node_modules/@fluent/bundle/esm/index.js","webpack://pdf.js/./node_modules/@fluent/dom/esm/overlay.js","webpack://pdf.js/./node_modules/cached-iterable/src/cached_iterable.mjs","webpack://pdf.js/./node_modules/cached-iterable/src/cached_sync_iterable.mjs","webpack://pdf.js/./node_modules/cached-iterable/src/cached_async_iterable.mjs","webpack://pdf.js/./node_modules/cached-iterable/src/index.mjs","webpack://pdf.js/./node_modules/@fluent/dom/esm/localization.js","webpack://pdf.js/./node_modules/@fluent/dom/esm/dom_localization.js","webpack://pdf.js/./node_modules/@fluent/dom/esm/index.js","webpack://pdf.js/./web/l10n.js","webpack://pdf.js/./web/genericl10n.js","webpack://pdf.js/./web/generic_scripting.js","webpack://pdf.js/./web/genericcom.js","webpack://pdf.js/./web/new_alt_text_manager.js","webpack://pdf.js/./web/alt_text_manager.js","webpack://pdf.js/./web/annotation_editor_params.js","webpack://pdf.js/./web/caret_browsing.js","webpack://pdf.js/./web/download_manager.js","webpack://pdf.js/./web/editor_undo_bar.js","webpack://pdf.js/./web/overlay_manager.js","webpack://pdf.js/./web/password_prompt.js","webpack://pdf.js/./web/base_tree_viewer.js","webpack://pdf.js/./web/pdf_attachment_viewer.js","webpack://pdf.js/./web/grab_to_pan.js","webpack://pdf.js/./web/pdf_cursor_tools.js","webpack://pdf.js/./web/pdf_document_properties.js","webpack://pdf.js/./web/pdf_find_utils.js","webpack://pdf.js/./web/pdf_find_controller.js","webpack://pdf.js/./web/pdf_find_bar.js","webpack://pdf.js/./web/pdf_history.js","webpack://pdf.js/./web/pdf_layer_viewer.js","webpack://pdf.js/./web/pdf_outline_viewer.js","webpack://pdf.js/./web/pdf_presentation_mode.js","webpack://pdf.js/./web/xfa_layer_builder.js","webpack://pdf.js/./web/print_utils.js","webpack://pdf.js/./web/pdf_print_service.js","webpack://pdf.js/./web/pdf_rendering_queue.js","webpack://pdf.js/./web/pdf_scripting_manager.js","webpack://pdf.js/./web/pdf_sidebar.js","webpack://pdf.js/./web/pdf_thumbnail_view.js","webpack://pdf.js/./web/pdf_thumbnail_viewer.js","webpack://pdf.js/./web/annotation_editor_layer_builder.js","webpack://pdf.js/./web/annotation_layer_builder.js","webpack://pdf.js/./web/draw_layer_builder.js","webpack://pdf.js/./web/struct_tree_layer_builder.js","webpack://pdf.js/./web/text_accessibility.js","webpack://pdf.js/./web/text_highlighter.js","webpack://pdf.js/./web/text_layer_builder.js","webpack://pdf.js/./web/pdf_page_view.js","webpack://pdf.js/./web/pdf_viewer.js","webpack://pdf.js/./web/secondary_toolbar.js","webpack://pdf.js/./web/toolbar.js","webpack://pdf.js/./web/view_history.js","webpack://pdf.js/./web/app.js","webpack://pdf.js/./web/viewer.js"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst DEFAULT_SCALE_VALUE = \"auto\";\nconst DEFAULT_SCALE = 1.0;\nconst DEFAULT_SCALE_DELTA = 1.1;\nconst MIN_SCALE = 0.1;\nconst MAX_SCALE = 10.0;\nconst UNKNOWN_SCALE = 0;\nconst MAX_AUTO_SCALE = 1.25;\nconst SCROLLBAR_PADDING = 40;\nconst VERTICAL_PADDING = 5;\n\nconst RenderingStates = {\n INITIAL: 0,\n RUNNING: 1,\n PAUSED: 2,\n FINISHED: 3,\n};\n\nconst PresentationModeState = {\n UNKNOWN: 0,\n NORMAL: 1,\n CHANGING: 2,\n FULLSCREEN: 3,\n};\n\nconst SidebarView = {\n UNKNOWN: -1,\n NONE: 0,\n THUMBS: 1, // Default value.\n OUTLINE: 2,\n ATTACHMENTS: 3,\n LAYERS: 4,\n};\n\nconst TextLayerMode = {\n DISABLE: 0,\n ENABLE: 1,\n ENABLE_PERMISSIONS: 2,\n};\n\nconst ScrollMode = {\n UNKNOWN: -1,\n VERTICAL: 0, // Default value.\n HORIZONTAL: 1,\n WRAPPED: 2,\n PAGE: 3,\n};\n\nconst SpreadMode = {\n UNKNOWN: -1,\n NONE: 0, // Default value.\n ODD: 1,\n EVEN: 2,\n};\n\nconst CursorTool = {\n SELECT: 0, // The default value.\n HAND: 1,\n ZOOM: 2,\n};\n\n// Used by `PDFViewerApplication`, and by the API unit-tests.\nconst AutoPrintRegExp = /\\bprint\\s*\\(/;\n\n/**\n * Scrolls specified element into view of its parent.\n * @param {HTMLElement} element - The element to be visible.\n * @param {Object} [spot] - An object with optional top and left properties,\n * specifying the offset from the top left edge.\n * @param {number} [spot.left]\n * @param {number} [spot.top]\n * @param {boolean} [scrollMatches] - When scrolling search results into view,\n * ignore elements that either: Contains marked content identifiers,\n * or have the CSS-rule `overflow: hidden;` set. The default value is `false`.\n */\nfunction scrollIntoView(element, spot, scrollMatches = false) {\n // Assuming offsetParent is available (it's not available when viewer is in\n // hidden iframe or object). We have to scroll: if the offsetParent is not set\n // producing the error. See also animationStarted.\n let parent = element.offsetParent;\n if (!parent) {\n console.error(\"offsetParent is not set -- cannot scroll\");\n return;\n }\n let offsetY = element.offsetTop + element.clientTop;\n let offsetX = element.offsetLeft + element.clientLeft;\n while (\n (parent.clientHeight === parent.scrollHeight &&\n parent.clientWidth === parent.scrollWidth) ||\n (scrollMatches &&\n (parent.classList.contains(\"markedContent\") ||\n getComputedStyle(parent).overflow === \"hidden\"))\n ) {\n offsetY += parent.offsetTop;\n offsetX += parent.offsetLeft;\n\n parent = parent.offsetParent;\n if (!parent) {\n return; // no need to scroll\n }\n }\n if (spot) {\n if (spot.top !== undefined) {\n offsetY += spot.top;\n }\n if (spot.left !== undefined) {\n offsetX += spot.left;\n parent.scrollLeft = offsetX;\n }\n }\n parent.scrollTop = offsetY;\n}\n\n/**\n * Helper function to start monitoring the scroll event and converting them into\n * PDF.js friendly one: with scroll debounce and scroll direction.\n */\nfunction watchScroll(viewAreaElement, callback, abortSignal = undefined) {\n const debounceScroll = function (evt) {\n if (rAF) {\n return;\n }\n // schedule an invocation of scroll for next animation frame.\n rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {\n rAF = null;\n\n const currentX = viewAreaElement.scrollLeft;\n const lastX = state.lastX;\n if (currentX !== lastX) {\n state.right = currentX > lastX;\n }\n state.lastX = currentX;\n const currentY = viewAreaElement.scrollTop;\n const lastY = state.lastY;\n if (currentY !== lastY) {\n state.down = currentY > lastY;\n }\n state.lastY = currentY;\n callback(state);\n });\n };\n\n const state = {\n right: true,\n down: true,\n lastX: viewAreaElement.scrollLeft,\n lastY: viewAreaElement.scrollTop,\n _eventHandler: debounceScroll,\n };\n\n let rAF = null;\n viewAreaElement.addEventListener(\"scroll\", debounceScroll, {\n useCapture: true,\n signal: abortSignal,\n });\n abortSignal?.addEventListener(\n \"abort\",\n () => window.cancelAnimationFrame(rAF),\n { once: true }\n );\n return state;\n}\n\n/**\n * Helper function to parse query string (e.g. ?param1=value¶m2=...).\n * @param {string} query\n * @returns {Map}\n */\nfunction parseQueryString(query) {\n const params = new Map();\n for (const [key, value] of new URLSearchParams(query)) {\n params.set(key.toLowerCase(), value);\n }\n return params;\n}\n\nconst InvisibleCharsRegExp = /[\\x00-\\x1F]/g;\n\n/**\n * @param {string} str\n * @param {boolean} [replaceInvisible]\n */\nfunction removeNullCharacters(str, replaceInvisible = false) {\n if (!InvisibleCharsRegExp.test(str)) {\n return str;\n }\n if (replaceInvisible) {\n return str.replaceAll(InvisibleCharsRegExp, m => (m === \"\\x00\" ? \"\" : \" \"));\n }\n return str.replaceAll(\"\\x00\", \"\");\n}\n\n/**\n * Use binary search to find the index of the first item in a given array which\n * passes a given condition. The items are expected to be sorted in the sense\n * that if the condition is true for one item in the array, then it is also true\n * for all following items.\n *\n * @returns {number} Index of the first array element to pass the test,\n * or |items.length| if no such element exists.\n */\nfunction binarySearchFirstItem(items, condition, start = 0) {\n let minIndex = start;\n let maxIndex = items.length - 1;\n\n if (maxIndex < 0 || !condition(items[maxIndex])) {\n return items.length;\n }\n if (condition(items[minIndex])) {\n return minIndex;\n }\n\n while (minIndex < maxIndex) {\n const currentIndex = (minIndex + maxIndex) >> 1;\n const currentItem = items[currentIndex];\n if (condition(currentItem)) {\n maxIndex = currentIndex;\n } else {\n minIndex = currentIndex + 1;\n }\n }\n return minIndex; /* === maxIndex */\n}\n\n/**\n * Approximates float number as a fraction using Farey sequence (max order\n * of 8).\n * @param {number} x - Positive float number.\n * @returns {Array} Estimated fraction: the first array item is a numerator,\n * the second one is a denominator.\n * They are both natural numbers.\n */\nfunction approximateFraction(x) {\n // Fast paths for int numbers or their inversions.\n if (Math.floor(x) === x) {\n return [x, 1];\n }\n const xinv = 1 / x;\n const limit = 8;\n if (xinv > limit) {\n return [1, limit];\n } else if (Math.floor(xinv) === xinv) {\n return [1, xinv];\n }\n\n const x_ = x > 1 ? xinv : x;\n // a/b and c/d are neighbours in Farey sequence.\n let a = 0,\n b = 1,\n c = 1,\n d = 1;\n // Limiting search to order 8.\n while (true) {\n // Generating next term in sequence (order of q).\n const p = a + c,\n q = b + d;\n if (q > limit) {\n break;\n }\n if (x_ <= p / q) {\n c = p;\n d = q;\n } else {\n a = p;\n b = q;\n }\n }\n let result;\n // Select closest of the neighbours to x.\n if (x_ - a / b < c / d - x_) {\n result = x_ === x ? [a, b] : [b, a];\n } else {\n result = x_ === x ? [c, d] : [d, c];\n }\n return result;\n}\n\n/**\n * @param {number} x - A positive number to round to a multiple of `div`.\n * @param {number} div - A natural number.\n */\nfunction floorToDivide(x, div) {\n return x - (x % div);\n}\n\n/**\n * @typedef {Object} GetPageSizeInchesParameters\n * @property {number[]} view\n * @property {number} userUnit\n * @property {number} rotate\n */\n\n/**\n * @typedef {Object} PageSize\n * @property {number} width - In inches.\n * @property {number} height - In inches.\n */\n\n/**\n * Gets the size of the specified page, converted from PDF units to inches.\n * @param {GetPageSizeInchesParameters} params\n * @returns {PageSize}\n */\nfunction getPageSizeInches({ view, userUnit, rotate }) {\n const [x1, y1, x2, y2] = view;\n // We need to take the page rotation into account as well.\n const changeOrientation = rotate % 180 !== 0;\n\n const width = ((x2 - x1) / 72) * userUnit;\n const height = ((y2 - y1) / 72) * userUnit;\n\n return {\n width: changeOrientation ? height : width,\n height: changeOrientation ? width : height,\n };\n}\n\n/**\n * Helper function for getVisibleElements.\n *\n * @param {number} index - initial guess at the first visible element\n * @param {Array} views - array of pages, into which `index` is an index\n * @param {number} top - the top of the scroll pane\n * @returns {number} less than or equal to `index` that is definitely at or\n * before the first visible element in `views`, but not by too much. (Usually,\n * this will be the first element in the first partially visible row in\n * `views`, although sometimes it goes back one row further.)\n */\nfunction backtrackBeforeAllVisibleElements(index, views, top) {\n // binarySearchFirstItem's assumption is that the input is ordered, with only\n // one index where the conditions flips from false to true: [false ...,\n // true...]. With vertical scrolling and spreads, it is possible to have\n // [false ..., true, false, true ...]. With wrapped scrolling we can have a\n // similar sequence, with many more mixed true and false in the middle.\n //\n // So there is no guarantee that the binary search yields the index of the\n // first visible element. It could have been any of the other visible elements\n // that were preceded by a hidden element.\n\n // Of course, if either this element or the previous (hidden) element is also\n // the first element, there's nothing to worry about.\n if (index < 2) {\n return index;\n }\n\n // That aside, the possible cases are represented below.\n //\n // **** = fully hidden\n // A*B* = mix of partially visible and/or hidden pages\n // CDEF = fully visible\n //\n // (1) Binary search could have returned A, in which case we can stop.\n // (2) Binary search could also have returned B, in which case we need to\n // check the whole row.\n // (3) Binary search could also have returned C, in which case we need to\n // check the whole previous row.\n //\n // There's one other possibility:\n //\n // **** = fully hidden\n // ABCD = mix of fully and/or partially visible pages\n //\n // (4) Binary search could only have returned A.\n\n // Initially assume that we need to find the beginning of the current row\n // (case 1, 2, or 4), which means finding a page that is above the current\n // page's top. If the found page is partially visible, we're definitely not in\n // case 3, and this assumption is correct.\n let elt = views[index].div;\n let pageTop = elt.offsetTop + elt.clientTop;\n\n if (pageTop >= top) {\n // The found page is fully visible, so we're actually either in case 3 or 4,\n // and unfortunately we can't tell the difference between them without\n // scanning the entire previous row, so we just conservatively assume that\n // we do need to backtrack to that row. In both cases, the previous page is\n // in the previous row, so use its top instead.\n elt = views[index - 1].div;\n pageTop = elt.offsetTop + elt.clientTop;\n }\n\n // Now we backtrack to the first page that still has its bottom below\n // `pageTop`, which is the top of a page in the first visible row (unless\n // we're in case 4, in which case it's the row before that).\n // `index` is found by binary search, so the page at `index - 1` is\n // invisible and we can start looking for potentially visible pages from\n // `index - 2`. (However, if this loop terminates on its first iteration,\n // which is the case when pages are stacked vertically, `index` should remain\n // unchanged, so we use a distinct loop variable.)\n for (let i = index - 2; i >= 0; --i) {\n elt = views[i].div;\n if (elt.offsetTop + elt.clientTop + elt.clientHeight <= pageTop) {\n // We have reached the previous row, so stop now.\n // This loop is expected to terminate relatively quickly because the\n // number of pages per row is expected to be small.\n break;\n }\n index = i;\n }\n return index;\n}\n\n/**\n * @typedef {Object} GetVisibleElementsParameters\n * @property {HTMLElement} scrollEl - A container that can possibly scroll.\n * @property {Array} views - Objects with a `div` property that contains an\n * HTMLElement, which should all be descendants of `scrollEl` satisfying the\n * relevant layout assumptions.\n * @property {boolean} sortByVisibility - If `true`, the returned elements are\n * sorted in descending order of the percent of their padding box that is\n * visible. The default value is `false`.\n * @property {boolean} horizontal - If `true`, the elements are assumed to be\n * laid out horizontally instead of vertically. The default value is `false`.\n * @property {boolean} rtl - If `true`, the `scrollEl` container is assumed to\n * be in right-to-left mode. The default value is `false`.\n */\n\n/**\n * Generic helper to find out what elements are visible within a scroll pane.\n *\n * Well, pretty generic. There are some assumptions placed on the elements\n * referenced by `views`:\n * - If `horizontal`, no left of any earlier element is to the right of the\n * left of any later element.\n * - Otherwise, `views` can be split into contiguous rows where, within a row,\n * no top of any element is below the bottom of any other element, and\n * between rows, no bottom of any element in an earlier row is below the\n * top of any element in a later row.\n *\n * (Here, top, left, etc. all refer to the padding edge of the element in\n * question. For pages, that ends up being equivalent to the bounding box of the\n * rendering canvas. Earlier and later refer to index in `views`, not page\n * layout.)\n *\n * @param {GetVisibleElementsParameters} params\n * @returns {Object} `{ first, last, views: [{ id, x, y, view, percent }] }`\n */\nfunction getVisibleElements({\n scrollEl,\n views,\n sortByVisibility = false,\n horizontal = false,\n rtl = false,\n}) {\n const top = scrollEl.scrollTop,\n bottom = top + scrollEl.clientHeight;\n const left = scrollEl.scrollLeft,\n right = left + scrollEl.clientWidth;\n\n // Throughout this \"generic\" function, comments will assume we're working with\n // PDF document pages, which is the most important and complex case. In this\n // case, the visible elements we're actually interested is the page canvas,\n // which is contained in a wrapper which adds no padding/border/margin, which\n // is itself contained in `view.div` which adds no padding (but does add a\n // border). So, as specified in this function's doc comment, this function\n // does all of its work on the padding edge of the provided views, starting at\n // offsetLeft/Top (which includes margin) and adding clientLeft/Top (which is\n // the border). Adding clientWidth/Height gets us the bottom-right corner of\n // the padding edge.\n function isElementBottomAfterViewTop(view) {\n const element = view.div;\n const elementBottom =\n element.offsetTop + element.clientTop + element.clientHeight;\n return elementBottom > top;\n }\n function isElementNextAfterViewHorizontally(view) {\n const element = view.div;\n const elementLeft = element.offsetLeft + element.clientLeft;\n const elementRight = elementLeft + element.clientWidth;\n return rtl ? elementLeft < right : elementRight > left;\n }\n\n const visible = [],\n ids = new Set(),\n numViews = views.length;\n let firstVisibleElementInd = binarySearchFirstItem(\n views,\n horizontal\n ? isElementNextAfterViewHorizontally\n : isElementBottomAfterViewTop\n );\n\n // Please note the return value of the `binarySearchFirstItem` function when\n // no valid element is found (hence the `firstVisibleElementInd` check below).\n if (\n firstVisibleElementInd > 0 &&\n firstVisibleElementInd < numViews &&\n !horizontal\n ) {\n // In wrapped scrolling (or vertical scrolling with spreads), with some page\n // sizes, isElementBottomAfterViewTop doesn't satisfy the binary search\n // condition: there can be pages with bottoms above the view top between\n // pages with bottoms below. This function detects and corrects that error;\n // see it for more comments.\n firstVisibleElementInd = backtrackBeforeAllVisibleElements(\n firstVisibleElementInd,\n views,\n top\n );\n }\n\n // lastEdge acts as a cutoff for us to stop looping, because we know all\n // subsequent pages will be hidden.\n //\n // When using wrapped scrolling or vertical scrolling with spreads, we can't\n // simply stop the first time we reach a page below the bottom of the view;\n // the tops of subsequent pages on the same row could still be visible. In\n // horizontal scrolling, we don't have that issue, so we can stop as soon as\n // we pass `right`, without needing the code below that handles the -1 case.\n let lastEdge = horizontal ? right : -1;\n\n for (let i = firstVisibleElementInd; i < numViews; i++) {\n const view = views[i],\n element = view.div;\n const currentWidth = element.offsetLeft + element.clientLeft;\n const currentHeight = element.offsetTop + element.clientTop;\n const viewWidth = element.clientWidth,\n viewHeight = element.clientHeight;\n const viewRight = currentWidth + viewWidth;\n const viewBottom = currentHeight + viewHeight;\n\n if (lastEdge === -1) {\n // As commented above, this is only needed in non-horizontal cases.\n // Setting lastEdge to the bottom of the first page that is partially\n // visible ensures that the next page fully below lastEdge is on the\n // next row, which has to be fully hidden along with all subsequent rows.\n if (viewBottom >= bottom) {\n lastEdge = viewBottom;\n }\n } else if ((horizontal ? currentWidth : currentHeight) > lastEdge) {\n break;\n }\n\n if (\n viewBottom <= top ||\n currentHeight >= bottom ||\n viewRight <= left ||\n currentWidth >= right\n ) {\n continue;\n }\n\n const hiddenHeight =\n Math.max(0, top - currentHeight) + Math.max(0, viewBottom - bottom);\n const hiddenWidth =\n Math.max(0, left - currentWidth) + Math.max(0, viewRight - right);\n\n const fractionHeight = (viewHeight - hiddenHeight) / viewHeight,\n fractionWidth = (viewWidth - hiddenWidth) / viewWidth;\n const percent = (fractionHeight * fractionWidth * 100) | 0;\n\n visible.push({\n id: view.id,\n x: currentWidth,\n y: currentHeight,\n view,\n percent,\n widthPercent: (fractionWidth * 100) | 0,\n });\n ids.add(view.id);\n }\n\n const first = visible[0],\n last = visible.at(-1);\n\n if (sortByVisibility) {\n visible.sort(function (a, b) {\n const pc = a.percent - b.percent;\n if (Math.abs(pc) > 0.001) {\n return -pc;\n }\n return a.id - b.id; // ensure stability\n });\n }\n return { first, last, views: visible, ids };\n}\n\nfunction normalizeWheelEventDirection(evt) {\n let delta = Math.hypot(evt.deltaX, evt.deltaY);\n const angle = Math.atan2(evt.deltaY, evt.deltaX);\n if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) {\n // All that is left-up oriented has to change the sign.\n delta = -delta;\n }\n return delta;\n}\n\nfunction normalizeWheelEventDelta(evt) {\n const deltaMode = evt.deltaMode; // Avoid being affected by bug 1392460.\n let delta = normalizeWheelEventDirection(evt);\n\n const MOUSE_PIXELS_PER_LINE = 30;\n const MOUSE_LINES_PER_PAGE = 30;\n\n // Converts delta to per-page units\n if (deltaMode === WheelEvent.DOM_DELTA_PIXEL) {\n delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE;\n } else if (deltaMode === WheelEvent.DOM_DELTA_LINE) {\n delta /= MOUSE_LINES_PER_PAGE;\n }\n return delta;\n}\n\nfunction isValidRotation(angle) {\n return Number.isInteger(angle) && angle % 90 === 0;\n}\n\nfunction isValidScrollMode(mode) {\n return (\n Number.isInteger(mode) &&\n Object.values(ScrollMode).includes(mode) &&\n mode !== ScrollMode.UNKNOWN\n );\n}\n\nfunction isValidSpreadMode(mode) {\n return (\n Number.isInteger(mode) &&\n Object.values(SpreadMode).includes(mode) &&\n mode !== SpreadMode.UNKNOWN\n );\n}\n\nfunction isPortraitOrientation(size) {\n return size.width <= size.height;\n}\n\n/**\n * Promise that is resolved when DOM window becomes visible.\n */\nconst animationStarted = new Promise(function (resolve) {\n if (\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"LIB\") &&\n typeof window === \"undefined\"\n ) {\n // Prevent \"ReferenceError: window is not defined\" errors when running the\n // unit-tests in Node.js environments.\n setTimeout(resolve, 20);\n return;\n }\n window.requestAnimationFrame(resolve);\n});\n\nconst docStyle =\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"LIB\") &&\n typeof document === \"undefined\"\n ? null\n : document.documentElement.style;\n\nfunction clamp(v, min, max) {\n return Math.min(Math.max(v, min), max);\n}\n\nclass ProgressBar {\n #classList = null;\n\n #disableAutoFetchTimeout = null;\n\n #percent = 0;\n\n #style = null;\n\n #visible = true;\n\n constructor(bar) {\n this.#classList = bar.classList;\n this.#style = bar.style;\n }\n\n get percent() {\n return this.#percent;\n }\n\n set percent(val) {\n this.#percent = clamp(val, 0, 100);\n\n if (isNaN(val)) {\n this.#classList.add(\"indeterminate\");\n return;\n }\n this.#classList.remove(\"indeterminate\");\n\n this.#style.setProperty(\"--progressBar-percent\", `${this.#percent}%`);\n }\n\n setWidth(viewer) {\n if (!viewer) {\n return;\n }\n const container = viewer.parentNode;\n const scrollbarWidth = container.offsetWidth - viewer.offsetWidth;\n if (scrollbarWidth > 0) {\n this.#style.setProperty(\n \"--progressBar-end-offset\",\n `${scrollbarWidth}px`\n );\n }\n }\n\n setDisableAutoFetch(delay = /* ms = */ 5000) {\n if (this.#percent === 100 || isNaN(this.#percent)) {\n return;\n }\n if (this.#disableAutoFetchTimeout) {\n clearTimeout(this.#disableAutoFetchTimeout);\n }\n this.show();\n\n this.#disableAutoFetchTimeout = setTimeout(() => {\n this.#disableAutoFetchTimeout = null;\n this.hide();\n }, delay);\n }\n\n hide() {\n if (!this.#visible) {\n return;\n }\n this.#visible = false;\n this.#classList.add(\"hidden\");\n }\n\n show() {\n if (this.#visible) {\n return;\n }\n this.#visible = true;\n this.#classList.remove(\"hidden\");\n }\n}\n\n/**\n * Get the active or focused element in current DOM.\n *\n * Recursively search for the truly active or focused element in case there are\n * shadow DOMs.\n *\n * @returns {Element} the truly active or focused element.\n */\nfunction getActiveOrFocusedElement() {\n let curRoot = document;\n let curActiveOrFocused =\n curRoot.activeElement || curRoot.querySelector(\":focus\");\n\n while (curActiveOrFocused?.shadowRoot) {\n curRoot = curActiveOrFocused.shadowRoot;\n curActiveOrFocused =\n curRoot.activeElement || curRoot.querySelector(\":focus\");\n }\n\n return curActiveOrFocused;\n}\n\n/**\n * Converts API PageLayout values to the format used by `BaseViewer`.\n * @param {string} layout - The API PageLayout value.\n * @returns {Object}\n */\nfunction apiPageLayoutToViewerModes(layout) {\n let scrollMode = ScrollMode.VERTICAL,\n spreadMode = SpreadMode.NONE;\n\n switch (layout) {\n case \"SinglePage\":\n scrollMode = ScrollMode.PAGE;\n break;\n case \"OneColumn\":\n break;\n case \"TwoPageLeft\":\n scrollMode = ScrollMode.PAGE;\n /* falls through */\n case \"TwoColumnLeft\":\n spreadMode = SpreadMode.ODD;\n break;\n case \"TwoPageRight\":\n scrollMode = ScrollMode.PAGE;\n /* falls through */\n case \"TwoColumnRight\":\n spreadMode = SpreadMode.EVEN;\n break;\n }\n return { scrollMode, spreadMode };\n}\n\n/**\n * Converts API PageMode values to the format used by `PDFSidebar`.\n * NOTE: There's also a \"FullScreen\" parameter which is not possible to support,\n * since the Fullscreen API used in browsers requires that entering\n * fullscreen mode only occurs as a result of a user-initiated event.\n * @param {string} mode - The API PageMode value.\n * @returns {number} A value from {SidebarView}.\n */\nfunction apiPageModeToSidebarView(mode) {\n switch (mode) {\n case \"UseNone\":\n return SidebarView.NONE;\n case \"UseThumbs\":\n return SidebarView.THUMBS;\n case \"UseOutlines\":\n return SidebarView.OUTLINE;\n case \"UseAttachments\":\n return SidebarView.ATTACHMENTS;\n case \"UseOC\":\n return SidebarView.LAYERS;\n }\n return SidebarView.NONE; // Default value.\n}\n\nfunction toggleCheckedBtn(button, toggle, view = null) {\n button.classList.toggle(\"toggled\", toggle);\n button.setAttribute(\"aria-checked\", toggle);\n\n view?.classList.toggle(\"hidden\", !toggle);\n}\n\nfunction toggleExpandedBtn(button, toggle, view = null) {\n button.classList.toggle(\"toggled\", toggle);\n button.setAttribute(\"aria-expanded\", toggle);\n\n view?.classList.toggle(\"hidden\", !toggle);\n}\n\n// In Firefox, the css calc function uses f32 precision but the Chrome or Safari\n// are using f64 one. So in order to have the same rendering in all browsers, we\n// need to use the right precision in order to have correct dimensions.\nconst calcRound =\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")\n ? Math.fround\n : (function () {\n if (\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"LIB\") &&\n typeof document === \"undefined\"\n ) {\n return x => x;\n }\n const e = document.createElement(\"div\");\n e.style.width = \"round(down, calc(1.6666666666666665 * 792px), 1px)\";\n return e.style.width === \"calc(1320px)\" ? Math.fround : x => x;\n })();\n\nexport {\n animationStarted,\n apiPageLayoutToViewerModes,\n apiPageModeToSidebarView,\n approximateFraction,\n AutoPrintRegExp,\n backtrackBeforeAllVisibleElements, // only exported for testing\n binarySearchFirstItem,\n calcRound,\n CursorTool,\n DEFAULT_SCALE,\n DEFAULT_SCALE_DELTA,\n DEFAULT_SCALE_VALUE,\n docStyle,\n floorToDivide,\n getActiveOrFocusedElement,\n getPageSizeInches,\n getVisibleElements,\n isPortraitOrientation,\n isValidRotation,\n isValidScrollMode,\n isValidSpreadMode,\n MAX_AUTO_SCALE,\n MAX_SCALE,\n MIN_SCALE,\n normalizeWheelEventDelta,\n normalizeWheelEventDirection,\n parseQueryString,\n PresentationModeState,\n ProgressBar,\n removeNullCharacters,\n RenderingStates,\n SCROLLBAR_PADDING,\n scrollIntoView,\n ScrollMode,\n SidebarView,\n SpreadMode,\n TextLayerMode,\n toggleCheckedBtn,\n toggleExpandedBtn,\n UNKNOWN_SCALE,\n VERTICAL_PADDING,\n watchScroll,\n};\n","/* Copyright 2018 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nif (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) {\n // eslint-disable-next-line no-var\n var compatParams = new Map();\n if (\n typeof PDFJSDev !== \"undefined\" &&\n PDFJSDev.test(\"LIB\") &&\n typeof navigator === \"undefined\"\n ) {\n globalThis.navigator = Object.create(null);\n }\n const userAgent = navigator.userAgent || \"\";\n const platform = navigator.platform || \"\";\n const maxTouchPoints = navigator.maxTouchPoints || 1;\n\n const isAndroid = /Android/.test(userAgent);\n const isIOS =\n /\\b(iPad|iPhone|iPod)(?=;)/.test(userAgent) ||\n (platform === \"MacIntel\" && maxTouchPoints > 1);\n\n // Limit canvas size to 5 mega-pixels on mobile.\n // Support: Android, iOS\n (function () {\n if (isIOS || isAndroid) {\n compatParams.set(\"maxCanvasPixels\", 5242880);\n }\n })();\n\n // Don't use system fonts on Android (issue 18210).\n // Support: Android\n (function () {\n if (isAndroid) {\n compatParams.set(\"useSystemFonts\", false);\n }\n })();\n}\n\nconst OptionKind = {\n BROWSER: 0x01,\n VIEWER: 0x02,\n API: 0x04,\n WORKER: 0x08,\n EVENT_DISPATCH: 0x10,\n PREFERENCE: 0x80,\n};\n\n// Should only be used with options that allow multiple types.\nconst Type = {\n BOOLEAN: 0x01,\n NUMBER: 0x02,\n OBJECT: 0x04,\n STRING: 0x08,\n UNDEFINED: 0x10,\n};\n\n/**\n * NOTE: These options are used to generate the `default_preferences.json` file,\n * see `OptionKind.PREFERENCE`, hence the values below must use only\n * primitive types and cannot rely on any imported types.\n */\nconst defaultOptions = {\n allowedGlobalEvents: {\n /** @type {Object} */\n value: null,\n kind: OptionKind.BROWSER,\n },\n canvasMaxAreaInBytes: {\n /** @type {number} */\n value: -1,\n kind: OptionKind.BROWSER + OptionKind.API,\n },\n isInAutomation: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.BROWSER,\n },\n localeProperties: {\n /** @type {Object} */\n value:\n typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")\n ? { lang: navigator.language || \"en-US\" }\n : null,\n kind: OptionKind.BROWSER,\n },\n nimbusDataStr: {\n /** @type {string} */\n value: \"\",\n kind: OptionKind.BROWSER,\n },\n supportsCaretBrowsingMode: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.BROWSER,\n },\n supportsDocumentFonts: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.BROWSER,\n },\n supportsIntegratedFind: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.BROWSER,\n },\n supportsMouseWheelZoomCtrlKey: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.BROWSER,\n },\n supportsMouseWheelZoomMetaKey: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.BROWSER,\n },\n supportsPinchToZoom: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.BROWSER,\n },\n toolbarDensity: {\n /** @type {number} */\n value: 0, // 0 = \"normal\", 1 = \"compact\", 2 = \"touch\"\n kind: OptionKind.BROWSER + OptionKind.EVENT_DISPATCH,\n },\n\n altTextLearnMoreUrl: {\n /** @type {string} */\n value:\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")\n ? \"https://support.mozilla.org/1/firefox/%VERSION%/%OS%/%LOCALE%/pdf-alt-text\"\n : \"\",\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n annotationEditorMode: {\n /** @type {number} */\n value: 0,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n annotationMode: {\n /** @type {number} */\n value: 2,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n cursorToolOnLoad: {\n /** @type {number} */\n value: 0,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n debuggerSrc: {\n /** @type {string} */\n value: \"./debugger.mjs\",\n kind: OptionKind.VIEWER,\n },\n defaultZoomDelay: {\n /** @type {number} */\n value: 400,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n defaultZoomValue: {\n /** @type {string} */\n value: \"\",\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n disableHistory: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.VIEWER,\n },\n disablePageLabels: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n enableAltText: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n enableAltTextModelDownload: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH,\n },\n enableGuessAltText: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE + OptionKind.EVENT_DISPATCH,\n },\n enableHighlightFloatingButton: {\n // We'll probably want to make some experiments before enabling this\n // in Firefox release, but it has to be temporary.\n // TODO: remove it when unnecessary.\n /** @type {boolean} */\n value: typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\"),\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n enableNewAltTextWhenAddingImage: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n enablePermissions: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n enablePrintAutoRotate: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n enableScripting: {\n /** @type {boolean} */\n value: typeof PDFJSDev === \"undefined\" || !PDFJSDev.test(\"CHROME\"),\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n enableUpdatedAddImage: {\n // We'll probably want to make some experiments before enabling this\n // in Firefox release, but it has to be temporary.\n // TODO: remove it when unnecessary.\n /** @type {boolean} */\n value: false,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n externalLinkRel: {\n /** @type {string} */\n value: \"noopener noreferrer nofollow\",\n kind: OptionKind.VIEWER,\n },\n externalLinkTarget: {\n /** @type {number} */\n value: 0,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n highlightEditorColors: {\n /** @type {string} */\n value: \"yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F\",\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n historyUpdateUrl: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n ignoreDestinationZoom: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n imageResourcesPath: {\n /** @type {string} */\n value:\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")\n ? \"resource://pdf.js/web/images/\"\n : \"./images/\",\n kind: OptionKind.VIEWER,\n },\n maxCanvasPixels: {\n /** @type {number} */\n value: 2 ** 25,\n kind: OptionKind.VIEWER,\n },\n forcePageColors: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n pageColorsBackground: {\n /** @type {string} */\n value: \"Canvas\",\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n pageColorsForeground: {\n /** @type {string} */\n value: \"CanvasText\",\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n pdfBugEnabled: {\n /** @type {boolean} */\n value: typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\"),\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n printResolution: {\n /** @type {number} */\n value: 150,\n kind: OptionKind.VIEWER,\n },\n sidebarViewOnLoad: {\n /** @type {number} */\n value: -1,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n scrollModeOnLoad: {\n /** @type {number} */\n value: -1,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n spreadModeOnLoad: {\n /** @type {number} */\n value: -1,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n textLayerMode: {\n /** @type {number} */\n value: 1,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n viewOnLoad: {\n /** @type {boolean} */\n value: 0,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n\n cMapPacked: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.API,\n },\n cMapUrl: {\n /** @type {string} */\n value:\n // eslint-disable-next-line no-nested-ternary\n typeof PDFJSDev === \"undefined\"\n ? \"../external/bcmaps/\"\n : PDFJSDev.test(\"MOZCENTRAL\")\n ? \"resource://pdf.js/web/cmaps/\"\n : \"../web/cmaps/\",\n kind: OptionKind.API,\n },\n disableAutoFetch: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.API + OptionKind.PREFERENCE,\n },\n disableFontFace: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.API + OptionKind.PREFERENCE,\n },\n disableRange: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.API + OptionKind.PREFERENCE,\n },\n disableStream: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.API + OptionKind.PREFERENCE,\n },\n docBaseUrl: {\n /** @type {string} */\n value: typeof PDFJSDev === \"undefined\" ? document.URL.split(\"#\", 1)[0] : \"\",\n kind: OptionKind.API,\n },\n enableHWA: {\n /** @type {boolean} */\n value: typeof PDFJSDev !== \"undefined\" && !PDFJSDev.test(\"MOZCENTRAL\"),\n kind: OptionKind.API + OptionKind.VIEWER + OptionKind.PREFERENCE,\n },\n enableXfa: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.API + OptionKind.PREFERENCE,\n },\n fontExtraProperties: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.API,\n },\n isEvalSupported: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.API,\n },\n isOffscreenCanvasSupported: {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.API,\n },\n maxImageSize: {\n /** @type {number} */\n value: -1,\n kind: OptionKind.API,\n },\n pdfBug: {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.API,\n },\n standardFontDataUrl: {\n /** @type {string} */\n value:\n // eslint-disable-next-line no-nested-ternary\n typeof PDFJSDev === \"undefined\"\n ? \"../external/standard_fonts/\"\n : PDFJSDev.test(\"MOZCENTRAL\")\n ? \"resource://pdf.js/web/standard_fonts/\"\n : \"../web/standard_fonts/\",\n kind: OptionKind.API,\n },\n useSystemFonts: {\n // On Android, there is almost no chance to have the font we want so we\n // don't use the system fonts in this case (bug 1882613).\n /** @type {boolean|undefined} */\n value: (\n typeof PDFJSDev === \"undefined\"\n ? window.isGECKOVIEW\n : PDFJSDev.test(\"GECKOVIEW\")\n )\n ? false\n : undefined,\n kind: OptionKind.API,\n type: Type.BOOLEAN + Type.UNDEFINED,\n },\n verbosity: {\n /** @type {number} */\n value: 1,\n kind: OptionKind.API,\n },\n\n workerPort: {\n /** @type {Object} */\n value: null,\n kind: OptionKind.WORKER,\n },\n workerSrc: {\n /** @type {string} */\n value:\n // eslint-disable-next-line no-nested-ternary\n typeof PDFJSDev === \"undefined\"\n ? \"../src/pdf.worker.js\"\n : PDFJSDev.test(\"MOZCENTRAL\")\n ? \"resource://pdf.js/build/pdf.worker.mjs\"\n : \"../build/pdf.worker.mjs\",\n kind: OptionKind.WORKER,\n },\n};\nif (typeof PDFJSDev === \"undefined\" || !PDFJSDev.test(\"MOZCENTRAL\")) {\n defaultOptions.defaultUrl = {\n /** @type {string} */\n value:\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"CHROME\")\n ? \"\"\n : \"compressed.tracemonkey-pldi-09.pdf\",\n kind: OptionKind.VIEWER,\n };\n defaultOptions.sandboxBundleSrc = {\n /** @type {string} */\n value:\n typeof PDFJSDev === \"undefined\"\n ? \"../build/dev-sandbox/pdf.sandbox.mjs\"\n : \"../build/pdf.sandbox.mjs\",\n kind: OptionKind.VIEWER,\n };\n defaultOptions.viewerCssTheme = {\n /** @type {number} */\n value: typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"CHROME\") ? 2 : 0,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n };\n defaultOptions.enableFakeMLManager = {\n /** @type {boolean} */\n value: true,\n kind: OptionKind.VIEWER,\n };\n}\nif (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) {\n defaultOptions.disablePreferences = {\n /** @type {boolean} */\n value: typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"TESTING\"),\n kind: OptionKind.VIEWER,\n };\n} else if (PDFJSDev.test(\"CHROME\")) {\n defaultOptions.disableTelemetry = {\n /** @type {boolean} */\n value: false,\n kind: OptionKind.VIEWER + OptionKind.PREFERENCE,\n };\n}\n\nif (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING || LIB\")) {\n // Ensure that the `defaultOptions` are correctly specified.\n for (const name in defaultOptions) {\n const { value, kind, type } = defaultOptions[name];\n\n if (kind & OptionKind.PREFERENCE) {\n if (kind === OptionKind.PREFERENCE) {\n throw new Error(`Cannot use only \"PREFERENCE\" kind: ${name}`);\n }\n if (kind & OptionKind.BROWSER) {\n throw new Error(`Cannot mix \"PREFERENCE\" and \"BROWSER\" kind: ${name}`);\n }\n if (type !== undefined) {\n throw new Error(\n `Cannot have \\`type\\`-field for \"PREFERENCE\" kind: ${name}`\n );\n }\n if (typeof compatParams === \"object\" && compatParams.has(name)) {\n throw new Error(\n `Should not have compatibility-value for \"PREFERENCE\" kind: ${name}`\n );\n }\n // Only \"simple\" preference-values are allowed.\n if (\n typeof value !== \"boolean\" &&\n typeof value !== \"string\" &&\n !Number.isInteger(value)\n ) {\n throw new Error(`Invalid value for \"PREFERENCE\" kind: ${name}`);\n }\n } else if (kind & OptionKind.BROWSER) {\n if (type !== undefined) {\n throw new Error(\n `Cannot have \\`type\\`-field for \"BROWSER\" kind: ${name}`\n );\n }\n if (typeof compatParams === \"object\" && compatParams.has(name)) {\n throw new Error(\n `Should not have compatibility-value for \"BROWSER\" kind: ${name}`\n );\n }\n if (value === undefined) {\n throw new Error(`Invalid value for \"BROWSER\" kind: ${name}`);\n }\n }\n }\n}\n\nclass AppOptions {\n static eventBus;\n\n static #opts = new Map();\n\n static {\n // Initialize all the user-options.\n for (const name in defaultOptions) {\n this.#opts.set(name, defaultOptions[name].value);\n }\n\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) {\n // Apply any compatibility-values to the user-options.\n for (const [name, value] of compatParams) {\n this.#opts.set(name, value);\n }\n this._hasInvokedSet = false;\n\n this._checkDisablePreferences = () => {\n if (this.get(\"disablePreferences\")) {\n // Give custom implementations of the default viewer a simpler way to\n // opt-out of having the `Preferences` override existing `AppOptions`.\n return true;\n }\n if (this._hasInvokedSet) {\n console.warn(\n \"The Preferences may override manually set AppOptions; \" +\n 'please use the \"disablePreferences\"-option to prevent that.'\n );\n }\n return false;\n };\n }\n }\n\n constructor() {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) {\n throw new Error(\"Cannot initialize AppOptions.\");\n }\n }\n\n static get(name) {\n return this.#opts.get(name);\n }\n\n static getAll(kind = null, defaultOnly = false) {\n const options = Object.create(null);\n for (const name in defaultOptions) {\n const defaultOpt = defaultOptions[name];\n\n if (kind && !(kind & defaultOpt.kind)) {\n continue;\n }\n options[name] = !defaultOnly ? this.#opts.get(name) : defaultOpt.value;\n }\n return options;\n }\n\n static set(name, value) {\n this.setAll({ [name]: value });\n }\n\n static setAll(options, prefs = false) {\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) {\n this._hasInvokedSet ||= true;\n }\n let events;\n\n for (const name in options) {\n const defaultOpt = defaultOptions[name],\n userOpt = options[name];\n\n if (\n !defaultOpt ||\n !(\n typeof userOpt === typeof defaultOpt.value ||\n Type[(typeof userOpt).toUpperCase()] & defaultOpt.type\n )\n ) {\n continue;\n }\n const { kind } = defaultOpt;\n\n if (\n prefs &&\n !(kind & OptionKind.BROWSER || kind & OptionKind.PREFERENCE)\n ) {\n continue;\n }\n if (this.eventBus && kind & OptionKind.EVENT_DISPATCH) {\n (events ||= new Map()).set(name, userOpt);\n }\n this.#opts.set(name, userOpt);\n }\n\n if (events) {\n for (const [name, value] of events) {\n this.eventBus.dispatch(name.toLowerCase(), { source: this, value });\n }\n }\n }\n}\n\nexport { AppOptions, OptionKind };\n","/* Copyright 2015 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./event_utils\").EventBus} EventBus */\n/** @typedef {import(\"./interfaces\").IPDFLinkService} IPDFLinkService */\n\nimport { parseQueryString } from \"./ui_utils.js\";\n\nconst DEFAULT_LINK_REL = \"noopener noreferrer nofollow\";\n\nconst LinkTarget = {\n NONE: 0, // Default value.\n SELF: 1,\n BLANK: 2,\n PARENT: 3,\n TOP: 4,\n};\n\n/**\n * @typedef {Object} PDFLinkServiceOptions\n * @property {EventBus} eventBus - The application event bus.\n * @property {number} [externalLinkTarget] - Specifies the `target` attribute\n * for external links. Must use one of the values from {LinkTarget}.\n * Defaults to using no target.\n * @property {string} [externalLinkRel] - Specifies the `rel` attribute for\n * external links. Defaults to stripping the referrer.\n * @property {boolean} [ignoreDestinationZoom] - Ignores the zoom argument,\n * thus preserving the current zoom level in the viewer, when navigating\n * to internal destinations. The default value is `false`.\n */\n\n/**\n * Performs navigation functions inside PDF, such as opening specified page,\n * or destination.\n * @implements {IPDFLinkService}\n */\nclass PDFLinkService {\n externalLinkEnabled = true;\n\n /**\n * @param {PDFLinkServiceOptions} options\n */\n constructor({\n eventBus,\n externalLinkTarget = null,\n externalLinkRel = null,\n ignoreDestinationZoom = false,\n } = {}) {\n this.eventBus = eventBus;\n this.externalLinkTarget = externalLinkTarget;\n this.externalLinkRel = externalLinkRel;\n this._ignoreDestinationZoom = ignoreDestinationZoom;\n\n this.baseUrl = null;\n this.pdfDocument = null;\n this.pdfViewer = null;\n this.pdfHistory = null;\n }\n\n setDocument(pdfDocument, baseUrl = null) {\n this.baseUrl = baseUrl;\n this.pdfDocument = pdfDocument;\n }\n\n setViewer(pdfViewer) {\n this.pdfViewer = pdfViewer;\n }\n\n setHistory(pdfHistory) {\n this.pdfHistory = pdfHistory;\n }\n\n /**\n * @type {number}\n */\n get pagesCount() {\n return this.pdfDocument ? this.pdfDocument.numPages : 0;\n }\n\n /**\n * @type {number}\n */\n get page() {\n return this.pdfDocument ? this.pdfViewer.currentPageNumber : 1;\n }\n\n /**\n * @param {number} value\n */\n set page(value) {\n if (this.pdfDocument) {\n this.pdfViewer.currentPageNumber = value;\n }\n }\n\n /**\n * @type {number}\n */\n get rotation() {\n return this.pdfDocument ? this.pdfViewer.pagesRotation : 0;\n }\n\n /**\n * @param {number} value\n */\n set rotation(value) {\n if (this.pdfDocument) {\n this.pdfViewer.pagesRotation = value;\n }\n }\n\n /**\n * @type {boolean}\n */\n get isInPresentationMode() {\n return this.pdfDocument ? this.pdfViewer.isInPresentationMode : false;\n }\n\n /**\n * This method will, when available, also update the browser history.\n *\n * @param {string|Array} dest - The named, or explicit, PDF destination.\n */\n async goToDestination(dest) {\n if (!this.pdfDocument) {\n return;\n }\n let namedDest, explicitDest, pageNumber;\n if (typeof dest === \"string\") {\n namedDest = dest;\n explicitDest = await this.pdfDocument.getDestination(dest);\n } else {\n namedDest = null;\n explicitDest = await dest;\n }\n if (!Array.isArray(explicitDest)) {\n console.error(\n `goToDestination: \"${explicitDest}\" is not a valid destination array, for dest=\"${dest}\".`\n );\n return;\n }\n // Dest array looks like that: \n const [destRef] = explicitDest;\n\n if (destRef && typeof destRef === \"object\") {\n pageNumber = this.pdfDocument.cachedPageNumber(destRef);\n\n if (!pageNumber) {\n // Fetch the page reference if it's not yet available. This could\n // only occur during loading, before all pages have been resolved.\n try {\n pageNumber = (await this.pdfDocument.getPageIndex(destRef)) + 1;\n } catch {\n console.error(\n `goToDestination: \"${destRef}\" is not a valid page reference, for dest=\"${dest}\".`\n );\n return;\n }\n }\n } else if (Number.isInteger(destRef)) {\n pageNumber = destRef + 1;\n }\n if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) {\n console.error(\n `goToDestination: \"${pageNumber}\" is not a valid page number, for dest=\"${dest}\".`\n );\n return;\n }\n\n if (this.pdfHistory) {\n // Update the browser history before scrolling the new destination into\n // view, to be able to accurately capture the current document position.\n this.pdfHistory.pushCurrentPosition();\n this.pdfHistory.push({ namedDest, explicitDest, pageNumber });\n }\n\n this.pdfViewer.scrollPageIntoView({\n pageNumber,\n destArray: explicitDest,\n ignoreDestinationZoom: this._ignoreDestinationZoom,\n });\n }\n\n /**\n * This method will, when available, also update the browser history.\n *\n * @param {number|string} val - The page number, or page label.\n */\n goToPage(val) {\n if (!this.pdfDocument) {\n return;\n }\n const pageNumber =\n (typeof val === \"string\" && this.pdfViewer.pageLabelToPageNumber(val)) ||\n val | 0;\n if (\n !(\n Number.isInteger(pageNumber) &&\n pageNumber > 0 &&\n pageNumber <= this.pagesCount\n )\n ) {\n console.error(`PDFLinkService.goToPage: \"${val}\" is not a valid page.`);\n return;\n }\n\n if (this.pdfHistory) {\n // Update the browser history before scrolling the new page into view,\n // to be able to accurately capture the current document position.\n this.pdfHistory.pushCurrentPosition();\n this.pdfHistory.pushPage(pageNumber);\n }\n\n this.pdfViewer.scrollPageIntoView({ pageNumber });\n }\n\n /**\n * Adds various attributes (href, title, target, rel) to hyperlinks.\n * @param {HTMLAnchorElement} link\n * @param {string} url\n * @param {boolean} [newWindow]\n */\n addLinkAttributes(link, url, newWindow = false) {\n if (!url || typeof url !== \"string\") {\n throw new Error('A valid \"url\" parameter must provided.');\n }\n const target = newWindow ? LinkTarget.BLANK : this.externalLinkTarget,\n rel = this.externalLinkRel;\n\n if (this.externalLinkEnabled) {\n link.href = link.title = url;\n } else {\n link.href = \"\";\n link.title = `Disabled: ${url}`;\n link.onclick = () => false;\n }\n\n let targetStr = \"\"; // LinkTarget.NONE\n switch (target) {\n case LinkTarget.NONE:\n break;\n case LinkTarget.SELF:\n targetStr = \"_self\";\n break;\n case LinkTarget.BLANK:\n targetStr = \"_blank\";\n break;\n case LinkTarget.PARENT:\n targetStr = \"_parent\";\n break;\n case LinkTarget.TOP:\n targetStr = \"_top\";\n break;\n }\n link.target = targetStr;\n\n link.rel = typeof rel === \"string\" ? rel : DEFAULT_LINK_REL;\n }\n\n /**\n * @param {string|Array} dest - The PDF destination object.\n * @returns {string} The hyperlink to the PDF object.\n */\n getDestinationHash(dest) {\n if (typeof dest === \"string\") {\n if (dest.length > 0) {\n return this.getAnchorUrl(\"#\" + escape(dest));\n }\n } else if (Array.isArray(dest)) {\n const str = JSON.stringify(dest);\n if (str.length > 0) {\n return this.getAnchorUrl(\"#\" + escape(str));\n }\n }\n return this.getAnchorUrl(\"\");\n }\n\n /**\n * Prefix the full url on anchor links to make sure that links are resolved\n * relative to the current URL instead of the one defined in .\n * @param {string} anchor - The anchor hash, including the #.\n * @returns {string} The hyperlink to the PDF object.\n */\n getAnchorUrl(anchor) {\n return this.baseUrl ? this.baseUrl + anchor : anchor;\n }\n\n /**\n * @param {string} hash\n */\n setHash(hash) {\n if (!this.pdfDocument) {\n return;\n }\n let pageNumber, dest;\n if (hash.includes(\"=\")) {\n const params = parseQueryString(hash);\n if (params.has(\"search\")) {\n const query = params.get(\"search\").replaceAll('\"', \"\"),\n phrase = params.get(\"phrase\") === \"true\";\n\n this.eventBus.dispatch(\"findfromurlhash\", {\n source: this,\n query: phrase ? query : query.match(/\\S+/g),\n });\n }\n // borrowing syntax from \"Parameters for Opening PDF Files\"\n if (params.has(\"page\")) {\n pageNumber = params.get(\"page\") | 0 || 1;\n }\n if (params.has(\"zoom\")) {\n // Build the destination array.\n const zoomArgs = params.get(\"zoom\").split(\",\"); // scale,left,top\n const zoomArg = zoomArgs[0];\n const zoomArgNumber = parseFloat(zoomArg);\n\n if (!zoomArg.includes(\"Fit\")) {\n // If the zoomArg is a number, it has to get divided by 100. If it's\n // a string, it should stay as it is.\n dest = [\n null,\n { name: \"XYZ\" },\n zoomArgs.length > 1 ? zoomArgs[1] | 0 : null,\n zoomArgs.length > 2 ? zoomArgs[2] | 0 : null,\n zoomArgNumber ? zoomArgNumber / 100 : zoomArg,\n ];\n } else if (zoomArg === \"Fit\" || zoomArg === \"FitB\") {\n dest = [null, { name: zoomArg }];\n } else if (\n zoomArg === \"FitH\" ||\n zoomArg === \"FitBH\" ||\n zoomArg === \"FitV\" ||\n zoomArg === \"FitBV\"\n ) {\n dest = [\n null,\n { name: zoomArg },\n zoomArgs.length > 1 ? zoomArgs[1] | 0 : null,\n ];\n } else if (zoomArg === \"FitR\") {\n if (zoomArgs.length !== 5) {\n console.error(\n 'PDFLinkService.setHash: Not enough parameters for \"FitR\".'\n );\n } else {\n dest = [\n null,\n { name: zoomArg },\n zoomArgs[1] | 0,\n zoomArgs[2] | 0,\n zoomArgs[3] | 0,\n zoomArgs[4] | 0,\n ];\n }\n } else {\n console.error(\n `PDFLinkService.setHash: \"${zoomArg}\" is not a valid zoom value.`\n );\n }\n }\n if (dest) {\n this.pdfViewer.scrollPageIntoView({\n pageNumber: pageNumber || this.page,\n destArray: dest,\n allowNegativeOffset: true,\n });\n } else if (pageNumber) {\n this.page = pageNumber; // simple page\n }\n if (params.has(\"pagemode\")) {\n this.eventBus.dispatch(\"pagemode\", {\n source: this,\n mode: params.get(\"pagemode\"),\n });\n }\n // Ensure that this parameter is *always* handled last, in order to\n // guarantee that it won't be overridden (e.g. by the \"page\" parameter).\n if (params.has(\"nameddest\")) {\n this.goToDestination(params.get(\"nameddest\"));\n }\n\n if (typeof PDFJSDev === \"undefined\" || !PDFJSDev.test(\"MOZCENTRAL\")) {\n return;\n }\n // Support opening of PDF attachments in the Firefox PDF Viewer,\n // which uses a couple of non-standard hash parameters; refer to\n // `DownloadManager.openOrDownloadData` in the firefoxcom.js file.\n if (!params.has(\"filename\") || !params.has(\"filedest\")) {\n return;\n }\n hash = params.get(\"filedest\");\n }\n\n // Named (or explicit) destination.\n dest = unescape(hash);\n try {\n dest = JSON.parse(dest);\n\n if (!Array.isArray(dest)) {\n // Avoid incorrectly rejecting a valid named destination, such as\n // e.g. \"4.3\" or \"true\", because `JSON.parse` converted its type.\n dest = dest.toString();\n }\n } catch {}\n\n if (typeof dest === \"string\" || PDFLinkService.#isValidExplicitDest(dest)) {\n this.goToDestination(dest);\n return;\n }\n console.error(\n `PDFLinkService.setHash: \"${unescape(hash)}\" is not a valid destination.`\n );\n }\n\n /**\n * @param {string} action\n */\n executeNamedAction(action) {\n if (!this.pdfDocument) {\n return;\n }\n // See PDF reference, table 8.45 - Named action\n switch (action) {\n case \"GoBack\":\n this.pdfHistory?.back();\n break;\n\n case \"GoForward\":\n this.pdfHistory?.forward();\n break;\n\n case \"NextPage\":\n this.pdfViewer.nextPage();\n break;\n\n case \"PrevPage\":\n this.pdfViewer.previousPage();\n break;\n\n case \"LastPage\":\n this.page = this.pagesCount;\n break;\n\n case \"FirstPage\":\n this.page = 1;\n break;\n\n default:\n break; // No action according to spec\n }\n\n this.eventBus.dispatch(\"namedaction\", {\n source: this,\n action,\n });\n }\n\n /**\n * @param {Object} action\n */\n async executeSetOCGState(action) {\n if (!this.pdfDocument) {\n return;\n }\n const pdfDocument = this.pdfDocument,\n optionalContentConfig = await this.pdfViewer.optionalContentConfigPromise;\n\n if (pdfDocument !== this.pdfDocument) {\n return; // The document was closed while the optional content resolved.\n }\n optionalContentConfig.setOCGState(action);\n\n this.pdfViewer.optionalContentConfigPromise = Promise.resolve(\n optionalContentConfig\n );\n }\n\n static #isValidExplicitDest(dest) {\n if (!Array.isArray(dest) || dest.length < 2) {\n return false;\n }\n const [page, zoom, ...args] = dest;\n if (\n !(\n typeof page === \"object\" &&\n Number.isInteger(page?.num) &&\n Number.isInteger(page?.gen)\n ) &&\n !Number.isInteger(page)\n ) {\n return false;\n }\n if (!(typeof zoom === \"object\" && typeof zoom?.name === \"string\")) {\n return false;\n }\n const argsLen = args.length;\n let allowNull = true;\n switch (zoom.name) {\n case \"XYZ\":\n if (argsLen < 2 || argsLen > 3) {\n return false;\n }\n break;\n case \"Fit\":\n case \"FitB\":\n return argsLen === 0;\n case \"FitH\":\n case \"FitBH\":\n case \"FitV\":\n case \"FitBV\":\n if (argsLen > 1) {\n return false;\n }\n break;\n case \"FitR\":\n if (argsLen !== 4) {\n return false;\n }\n allowNull = false;\n break;\n default:\n return false;\n }\n for (const arg of args) {\n if (!(typeof arg === \"number\" || (allowNull && arg === null))) {\n return false;\n }\n }\n return true;\n }\n}\n\n/**\n * @implements {IPDFLinkService}\n */\nclass SimpleLinkService extends PDFLinkService {\n setDocument(pdfDocument, baseUrl = null) {}\n}\n\nexport { LinkTarget, PDFLinkService, SimpleLinkService };\n","/* Copyright 2016 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst {\n AbortException,\n AnnotationEditorLayer,\n AnnotationEditorParamsType,\n AnnotationEditorType,\n AnnotationEditorUIManager,\n AnnotationLayer,\n AnnotationMode,\n build,\n ColorPicker,\n createValidAbsoluteUrl,\n DOMSVGFactory,\n DrawLayer,\n FeatureTest,\n fetchData,\n getDocument,\n getFilenameFromUrl,\n getPdfFilenameFromUrl,\n getXfaPageViewport,\n GlobalWorkerOptions,\n ImageKind,\n InvalidPDFException,\n isDataScheme,\n isPdfFile,\n MissingPDFException,\n noContextMenu,\n normalizeUnicode,\n OPS,\n OutputScale,\n PasswordResponses,\n PDFDataRangeTransport,\n PDFDateString,\n PDFWorker,\n PermissionFlag,\n PixelsPerInch,\n RenderingCancelledException,\n setLayerDimensions,\n shadow,\n stopEvent,\n TextLayer,\n UnexpectedResponseException,\n Util,\n VerbosityLevel,\n version,\n XfaLayer,\n} = globalThis.pdfjsLib;\n\nexport {\n AbortException,\n AnnotationEditorLayer,\n AnnotationEditorParamsType,\n AnnotationEditorType,\n AnnotationEditorUIManager,\n AnnotationLayer,\n AnnotationMode,\n build,\n ColorPicker,\n createValidAbsoluteUrl,\n DOMSVGFactory,\n DrawLayer,\n FeatureTest,\n fetchData,\n getDocument,\n getFilenameFromUrl,\n getPdfFilenameFromUrl,\n getXfaPageViewport,\n GlobalWorkerOptions,\n ImageKind,\n InvalidPDFException,\n isDataScheme,\n isPdfFile,\n MissingPDFException,\n noContextMenu,\n normalizeUnicode,\n OPS,\n OutputScale,\n PasswordResponses,\n PDFDataRangeTransport,\n PDFDateString,\n PDFWorker,\n PermissionFlag,\n PixelsPerInch,\n RenderingCancelledException,\n setLayerDimensions,\n shadow,\n stopEvent,\n TextLayer,\n UnexpectedResponseException,\n Util,\n VerbosityLevel,\n version,\n XfaLayer,\n};\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst WaitOnType = {\n EVENT: \"event\",\n TIMEOUT: \"timeout\",\n};\n\n/**\n * @typedef {Object} WaitOnEventOrTimeoutParameters\n * @property {Object} target - The event target, can for example be:\n * `window`, `document`, a DOM element, or an {EventBus} instance.\n * @property {string} name - The name of the event.\n * @property {number} delay - The delay, in milliseconds, after which the\n * timeout occurs (if the event wasn't already dispatched).\n */\n\n/**\n * Allows waiting for an event or a timeout, whichever occurs first.\n * Can be used to ensure that an action always occurs, even when an event\n * arrives late or not at all.\n *\n * @param {WaitOnEventOrTimeoutParameters}\n * @returns {Promise} A promise that is resolved with a {WaitOnType} value.\n */\nasync function waitOnEventOrTimeout({ target, name, delay = 0 }) {\n if (\n typeof target !== \"object\" ||\n !(name && typeof name === \"string\") ||\n !(Number.isInteger(delay) && delay >= 0)\n ) {\n throw new Error(\"waitOnEventOrTimeout - invalid parameters.\");\n }\n const { promise, resolve } = Promise.withResolvers();\n const ac = new AbortController();\n\n function handler(type) {\n ac.abort(); // Remove event listener.\n clearTimeout(timeout);\n\n resolve(type);\n }\n\n const evtMethod = target instanceof EventBus ? \"_on\" : \"addEventListener\";\n target[evtMethod](name, handler.bind(null, WaitOnType.EVENT), {\n signal: ac.signal,\n });\n\n const timeout = setTimeout(handler.bind(null, WaitOnType.TIMEOUT), delay);\n\n return promise;\n}\n\n/**\n * Simple event bus for an application. Listeners are attached using the `on`\n * and `off` methods. To raise an event, the `dispatch` method shall be used.\n */\nclass EventBus {\n #listeners = Object.create(null);\n\n /**\n * @param {string} eventName\n * @param {function} listener\n * @param {Object} [options]\n */\n on(eventName, listener, options = null) {\n this._on(eventName, listener, {\n external: true,\n once: options?.once,\n signal: options?.signal,\n });\n }\n\n /**\n * @param {string} eventName\n * @param {function} listener\n * @param {Object} [options]\n */\n off(eventName, listener, options = null) {\n this._off(eventName, listener);\n }\n\n /**\n * @param {string} eventName\n * @param {Object} data\n */\n dispatch(eventName, data) {\n const eventListeners = this.#listeners[eventName];\n if (!eventListeners || eventListeners.length === 0) {\n return;\n }\n let externalListeners;\n // Making copy of the listeners array in case if it will be modified\n // during dispatch.\n for (const { listener, external, once } of eventListeners.slice(0)) {\n if (once) {\n this._off(eventName, listener);\n }\n if (external) {\n (externalListeners ||= []).push(listener);\n continue;\n }\n listener(data);\n }\n // Dispatch any \"external\" listeners *after* the internal ones, to give the\n // viewer components time to handle events and update their state first.\n if (externalListeners) {\n for (const listener of externalListeners) {\n listener(data);\n }\n externalListeners = null;\n }\n }\n\n /**\n * @ignore\n */\n _on(eventName, listener, options = null) {\n let rmAbort = null;\n if (options?.signal instanceof AbortSignal) {\n const { signal } = options;\n if (signal.aborted) {\n console.error(\"Cannot use an `aborted` signal.\");\n return;\n }\n const onAbort = () => this._off(eventName, listener);\n rmAbort = () => signal.removeEventListener(\"abort\", onAbort);\n\n signal.addEventListener(\"abort\", onAbort);\n }\n\n const eventListeners = (this.#listeners[eventName] ||= []);\n eventListeners.push({\n listener,\n external: options?.external === true,\n once: options?.once === true,\n rmAbort,\n });\n }\n\n /**\n * @ignore\n */\n _off(eventName, listener, options = null) {\n const eventListeners = this.#listeners[eventName];\n if (!eventListeners) {\n return;\n }\n for (let i = 0, ii = eventListeners.length; i < ii; i++) {\n const evt = eventListeners[i];\n if (evt.listener === listener) {\n evt.rmAbort?.(); // Ensure that the `AbortSignal` listener is removed.\n eventListeners.splice(i, 1);\n return;\n }\n }\n }\n}\n\n/**\n * NOTE: Only used in the Firefox build-in pdf viewer.\n */\nclass FirefoxEventBus extends EventBus {\n #externalServices;\n\n #globalEventNames;\n\n #isInAutomation;\n\n constructor(globalEventNames, externalServices, isInAutomation) {\n super();\n this.#globalEventNames = globalEventNames;\n this.#externalServices = externalServices;\n this.#isInAutomation = isInAutomation;\n }\n\n dispatch(eventName, data) {\n if (typeof PDFJSDev !== \"undefined\" && !PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: FirefoxEventBus.dispatch\");\n }\n super.dispatch(eventName, data);\n\n if (this.#isInAutomation) {\n const detail = Object.create(null);\n if (data) {\n for (const key in data) {\n const value = data[key];\n if (key === \"source\") {\n if (value === window || value === document) {\n return; // No need to re-dispatch (already) global events.\n }\n continue; // Ignore the `source` property.\n }\n detail[key] = value;\n }\n }\n const event = new CustomEvent(eventName, {\n bubbles: true,\n cancelable: true,\n detail,\n });\n document.dispatchEvent(event);\n }\n\n if (this.#globalEventNames?.has(eventName)) {\n this.#externalServices.dispatchGlobalEvent({\n eventName,\n detail: data,\n });\n }\n }\n}\n\nexport { EventBus, FirefoxEventBus, waitOnEventOrTimeout, WaitOnType };\n","/* Copyright 2024 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./interfaces.js\").IL10n} IL10n */\n\nclass BaseExternalServices {\n constructor() {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === BaseExternalServices\n ) {\n throw new Error(\"Cannot initialize BaseExternalServices.\");\n }\n }\n\n updateFindControlState(data) {}\n\n updateFindMatchesCount(data) {}\n\n initPassiveLoading() {}\n\n reportTelemetry(data) {}\n\n /**\n * @returns {Promise}\n */\n async createL10n() {\n throw new Error(\"Not implemented: createL10n\");\n }\n\n createScripting() {\n throw new Error(\"Not implemented: createScripting\");\n }\n\n updateEditorStates(data) {\n throw new Error(\"Not implemented: updateEditorStates\");\n }\n\n dispatchGlobalEvent(_event) {}\n}\n\nexport { BaseExternalServices };\n","/* Copyright 2013 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AppOptions, OptionKind } from \"./app_options.js\";\n\n/**\n * BasePreferences - Abstract base class for storing persistent settings.\n * Used for settings that should be applied to all opened documents,\n * or every time the viewer is loaded.\n */\nclass BasePreferences {\n #defaults = Object.freeze(\n typeof PDFJSDev === \"undefined\"\n ? AppOptions.getAll(OptionKind.PREFERENCE, /* defaultOnly = */ true)\n : PDFJSDev.eval(\"DEFAULT_PREFERENCES\")\n );\n\n #initializedPromise = null;\n\n constructor() {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"TESTING\")) &&\n this.constructor === BasePreferences\n ) {\n throw new Error(\"Cannot initialize BasePreferences.\");\n }\n\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"CHROME\")) {\n Object.defineProperty(this, \"defaults\", {\n get() {\n return this.#defaults;\n },\n });\n }\n\n this.#initializedPromise = this._readFromStorage(this.#defaults).then(\n ({ browserPrefs, prefs }) => {\n if (\n (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) &&\n AppOptions._checkDisablePreferences()\n ) {\n return;\n }\n AppOptions.setAll({ ...browserPrefs, ...prefs }, /* prefs = */ true);\n }\n );\n\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n window.addEventListener(\n \"updatedPreference\",\n async ({ detail: { name, value } }) => {\n await this.#initializedPromise;\n AppOptions.setAll({ [name]: value }, /* prefs = */ true);\n }\n );\n }\n }\n\n /**\n * Stub function for writing preferences to storage.\n * @param {Object} prefObj The preferences that should be written to storage.\n * @returns {Promise} A promise that is resolved when the preference values\n * have been written.\n */\n async _writeToStorage(prefObj) {\n throw new Error(\"Not implemented: _writeToStorage\");\n }\n\n /**\n * Stub function for reading preferences from storage.\n * @param {Object} prefObj The preferences that should be read from storage.\n * @returns {Promise} A promise that is resolved with an {Object} containing\n * the preferences that have been read.\n */\n async _readFromStorage(prefObj) {\n throw new Error(\"Not implemented: _readFromStorage\");\n }\n\n /**\n * Reset the preferences to their default values and update storage.\n * @returns {Promise} A promise that is resolved when the preference values\n * have been reset.\n */\n async reset() {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Please use `about:config` to change preferences.\");\n }\n await this.#initializedPromise;\n AppOptions.setAll(this.#defaults, /* prefs = */ true);\n\n await this._writeToStorage(this.#defaults);\n }\n\n /**\n * Set the value of a preference.\n * @param {string} name The name of the preference that should be changed.\n * @param {boolean|number|string} value The new value of the preference.\n * @returns {Promise} A promise that is resolved when the value has been set,\n * provided that the preference exists and the types match.\n */\n async set(name, value) {\n await this.#initializedPromise;\n AppOptions.setAll({ [name]: value }, /* prefs = */ true);\n\n await this._writeToStorage(\n typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")\n ? { [name]: AppOptions.get(name) }\n : AppOptions.getAll(OptionKind.PREFERENCE)\n );\n }\n\n /**\n * Get the value of a preference.\n * @param {string} name The name of the preference whose value is requested.\n * @returns {Promise} A promise resolved with a {boolean|number|string}\n * containing the value of the preference.\n */\n async get(name) {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"MOZCENTRAL\")) {\n throw new Error(\"Not implemented: get\");\n }\n await this.#initializedPromise;\n return AppOptions.get(name);\n }\n\n get initializedPromise() {\n return this.#initializedPromise;\n }\n}\n\nexport { BasePreferences };\n","/**\n * The `FluentType` class is the base of Fluent's type system.\n *\n * Fluent types wrap JavaScript values and store additional configuration for\n * them, which can then be used in the `toString` method together with a proper\n * `Intl` formatter.\n */\nexport class FluentType {\n /**\n * Create a `FluentType` instance.\n *\n * @param value The JavaScript value to wrap.\n */\n constructor(value) {\n this.value = value;\n }\n /**\n * Unwrap the raw value stored by this `FluentType`.\n */\n valueOf() {\n return this.value;\n }\n}\n/**\n * A `FluentType` representing no correct value.\n */\nexport class FluentNone extends FluentType {\n /**\n * Create an instance of `FluentNone` with an optional fallback value.\n * @param value The fallback value of this `FluentNone`.\n */\n constructor(value = \"???\") {\n super(value);\n }\n /**\n * Format this `FluentNone` to the fallback string.\n */\n toString(scope) {\n return `{${this.value}}`;\n }\n}\n/**\n * A `FluentType` representing a number.\n *\n * A `FluentNumber` instance stores the number value of the number it\n * represents. It may also store an option bag of options which will be passed\n * to `Intl.NumerFormat` when the `FluentNumber` is formatted to a string.\n */\nexport class FluentNumber extends FluentType {\n /**\n * Create an instance of `FluentNumber` with options to the\n * `Intl.NumberFormat` constructor.\n *\n * @param value The number value of this `FluentNumber`.\n * @param opts Options which will be passed to `Intl.NumberFormat`.\n */\n constructor(value, opts = {}) {\n super(value);\n this.opts = opts;\n }\n /**\n * Format this `FluentNumber` to a string.\n */\n toString(scope) {\n try {\n const nf = scope.memoizeIntlObject(Intl.NumberFormat, this.opts);\n return nf.format(this.value);\n }\n catch (err) {\n scope.reportError(err);\n return this.value.toString(10);\n }\n }\n}\n/**\n * A `FluentType` representing a date and time.\n *\n * A `FluentDateTime` instance stores the number value of the date it\n * represents, as a numerical timestamp in milliseconds. It may also store an\n * option bag of options which will be passed to `Intl.DateTimeFormat` when the\n * `FluentDateTime` is formatted to a string.\n */\nexport class FluentDateTime extends FluentType {\n /**\n * Create an instance of `FluentDateTime` with options to the\n * `Intl.DateTimeFormat` constructor.\n *\n * @param value The number value of this `FluentDateTime`, in milliseconds.\n * @param opts Options which will be passed to `Intl.DateTimeFormat`.\n */\n constructor(value, opts = {}) {\n super(value);\n this.opts = opts;\n }\n /**\n * Format this `FluentDateTime` to a string.\n */\n toString(scope) {\n try {\n const dtf = scope.memoizeIntlObject(Intl.DateTimeFormat, this.opts);\n return dtf.format(this.value);\n }\n catch (err) {\n scope.reportError(err);\n return new Date(this.value).toISOString();\n }\n }\n}\n","/* global Intl */\n/**\n * @overview\n *\n * The role of the Fluent resolver is to format a `Pattern` to an instance of\n * `FluentValue`. For performance reasons, primitive strings are considered\n * such instances, too.\n *\n * Translations can contain references to other messages or variables,\n * conditional logic in form of select expressions, traits which describe their\n * grammatical features, and can use Fluent builtins which make use of the\n * `Intl` formatters to format numbers and dates into the bundle's languages.\n * See the documentation of the Fluent syntax for more information.\n *\n * In case of errors the resolver will try to salvage as much of the\n * translation as possible. In rare situations where the resolver didn't know\n * how to recover from an error it will return an instance of `FluentNone`.\n *\n * All expressions resolve to an instance of `FluentValue`. The caller should\n * use the `toString` method to convert the instance to a native value.\n *\n * Functions in this file pass around an instance of the `Scope` class, which\n * stores the data required for successful resolution and error recovery.\n */\nimport { FluentType, FluentNone, FluentNumber, FluentDateTime, } from \"./types.js\";\n/**\n * The maximum number of placeables which can be expanded in a single call to\n * `formatPattern`. The limit protects against the Billion Laughs and Quadratic\n * Blowup attacks. See https://msdn.microsoft.com/en-us/magazine/ee335713.aspx.\n */\nconst MAX_PLACEABLES = 100;\n/** Unicode bidi isolation characters. */\nconst FSI = \"\\u2068\";\nconst PDI = \"\\u2069\";\n/** Helper: match a variant key to the given selector. */\nfunction match(scope, selector, key) {\n if (key === selector) {\n // Both are strings.\n return true;\n }\n // XXX Consider comparing options too, e.g. minimumFractionDigits.\n if (key instanceof FluentNumber &&\n selector instanceof FluentNumber &&\n key.value === selector.value) {\n return true;\n }\n if (selector instanceof FluentNumber && typeof key === \"string\") {\n let category = scope\n .memoizeIntlObject(Intl.PluralRules, selector.opts)\n .select(selector.value);\n if (key === category) {\n return true;\n }\n }\n return false;\n}\n/** Helper: resolve the default variant from a list of variants. */\nfunction getDefault(scope, variants, star) {\n if (variants[star]) {\n return resolvePattern(scope, variants[star].value);\n }\n scope.reportError(new RangeError(\"No default\"));\n return new FluentNone();\n}\n/** Helper: resolve arguments to a call expression. */\nfunction getArguments(scope, args) {\n const positional = [];\n const named = Object.create(null);\n for (const arg of args) {\n if (arg.type === \"narg\") {\n named[arg.name] = resolveExpression(scope, arg.value);\n }\n else {\n positional.push(resolveExpression(scope, arg));\n }\n }\n return { positional, named };\n}\n/** Resolve an expression to a Fluent type. */\nfunction resolveExpression(scope, expr) {\n switch (expr.type) {\n case \"str\":\n return expr.value;\n case \"num\":\n return new FluentNumber(expr.value, {\n minimumFractionDigits: expr.precision,\n });\n case \"var\":\n return resolveVariableReference(scope, expr);\n case \"mesg\":\n return resolveMessageReference(scope, expr);\n case \"term\":\n return resolveTermReference(scope, expr);\n case \"func\":\n return resolveFunctionReference(scope, expr);\n case \"select\":\n return resolveSelectExpression(scope, expr);\n default:\n return new FluentNone();\n }\n}\n/** Resolve a reference to a variable. */\nfunction resolveVariableReference(scope, { name }) {\n let arg;\n if (scope.params) {\n // We're inside a TermReference. It's OK to reference undefined parameters.\n if (Object.prototype.hasOwnProperty.call(scope.params, name)) {\n arg = scope.params[name];\n }\n else {\n return new FluentNone(`$${name}`);\n }\n }\n else if (scope.args &&\n Object.prototype.hasOwnProperty.call(scope.args, name)) {\n // We're in the top-level Pattern or inside a MessageReference. Missing\n // variables references produce ReferenceErrors.\n arg = scope.args[name];\n }\n else {\n scope.reportError(new ReferenceError(`Unknown variable: $${name}`));\n return new FluentNone(`$${name}`);\n }\n // Return early if the argument already is an instance of FluentType.\n if (arg instanceof FluentType) {\n return arg;\n }\n // Convert the argument to a Fluent type.\n switch (typeof arg) {\n case \"string\":\n return arg;\n case \"number\":\n return new FluentNumber(arg);\n case \"object\":\n if (arg instanceof Date) {\n return new FluentDateTime(arg.getTime());\n }\n // eslint-disable-next-line no-fallthrough\n default:\n scope.reportError(new TypeError(`Variable type not supported: $${name}, ${typeof arg}`));\n return new FluentNone(`$${name}`);\n }\n}\n/** Resolve a reference to another message. */\nfunction resolveMessageReference(scope, { name, attr }) {\n const message = scope.bundle._messages.get(name);\n if (!message) {\n scope.reportError(new ReferenceError(`Unknown message: ${name}`));\n return new FluentNone(name);\n }\n if (attr) {\n const attribute = message.attributes[attr];\n if (attribute) {\n return resolvePattern(scope, attribute);\n }\n scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`));\n return new FluentNone(`${name}.${attr}`);\n }\n if (message.value) {\n return resolvePattern(scope, message.value);\n }\n scope.reportError(new ReferenceError(`No value: ${name}`));\n return new FluentNone(name);\n}\n/** Resolve a call to a Term with key-value arguments. */\nfunction resolveTermReference(scope, { name, attr, args }) {\n const id = `-${name}`;\n const term = scope.bundle._terms.get(id);\n if (!term) {\n scope.reportError(new ReferenceError(`Unknown term: ${id}`));\n return new FluentNone(id);\n }\n if (attr) {\n const attribute = term.attributes[attr];\n if (attribute) {\n // Every TermReference has its own variables.\n scope.params = getArguments(scope, args).named;\n const resolved = resolvePattern(scope, attribute);\n scope.params = null;\n return resolved;\n }\n scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`));\n return new FluentNone(`${id}.${attr}`);\n }\n scope.params = getArguments(scope, args).named;\n const resolved = resolvePattern(scope, term.value);\n scope.params = null;\n return resolved;\n}\n/** Resolve a call to a Function with positional and key-value arguments. */\nfunction resolveFunctionReference(scope, { name, args }) {\n // Some functions are built-in. Others may be provided by the runtime via\n // the `FluentBundle` constructor.\n let func = scope.bundle._functions[name];\n if (!func) {\n scope.reportError(new ReferenceError(`Unknown function: ${name}()`));\n return new FluentNone(`${name}()`);\n }\n if (typeof func !== \"function\") {\n scope.reportError(new TypeError(`Function ${name}() is not callable`));\n return new FluentNone(`${name}()`);\n }\n try {\n let resolved = getArguments(scope, args);\n return func(resolved.positional, resolved.named);\n }\n catch (err) {\n scope.reportError(err);\n return new FluentNone(`${name}()`);\n }\n}\n/** Resolve a select expression to the member object. */\nfunction resolveSelectExpression(scope, { selector, variants, star }) {\n let sel = resolveExpression(scope, selector);\n if (sel instanceof FluentNone) {\n return getDefault(scope, variants, star);\n }\n // Match the selector against keys of each variant, in order.\n for (const variant of variants) {\n const key = resolveExpression(scope, variant.key);\n if (match(scope, sel, key)) {\n return resolvePattern(scope, variant.value);\n }\n }\n return getDefault(scope, variants, star);\n}\n/** Resolve a pattern (a complex string with placeables). */\nexport function resolveComplexPattern(scope, ptn) {\n if (scope.dirty.has(ptn)) {\n scope.reportError(new RangeError(\"Cyclic reference\"));\n return new FluentNone();\n }\n // Tag the pattern as dirty for the purpose of the current resolution.\n scope.dirty.add(ptn);\n const result = [];\n // Wrap interpolations with Directional Isolate Formatting characters\n // only when the pattern has more than one element.\n const useIsolating = scope.bundle._useIsolating && ptn.length > 1;\n for (const elem of ptn) {\n if (typeof elem === \"string\") {\n result.push(scope.bundle._transform(elem));\n continue;\n }\n scope.placeables++;\n if (scope.placeables > MAX_PLACEABLES) {\n scope.dirty.delete(ptn);\n // This is a fatal error which causes the resolver to instantly bail out\n // on this pattern. The length check protects against excessive memory\n // usage, and throwing protects against eating up the CPU when long\n // placeables are deeply nested.\n throw new RangeError(`Too many placeables expanded: ${scope.placeables}, ` +\n `max allowed is ${MAX_PLACEABLES}`);\n }\n if (useIsolating) {\n result.push(FSI);\n }\n result.push(resolveExpression(scope, elem).toString(scope));\n if (useIsolating) {\n result.push(PDI);\n }\n }\n scope.dirty.delete(ptn);\n return result.join(\"\");\n}\n/**\n * Resolve a simple or a complex Pattern to a FluentString\n * (which is really the string primitive).\n */\nfunction resolvePattern(scope, value) {\n // Resolve a simple pattern.\n if (typeof value === \"string\") {\n return scope.bundle._transform(value);\n }\n return resolveComplexPattern(scope, value);\n}\n","export class Scope {\n constructor(bundle, errors, args) {\n /**\n * The Set of patterns already encountered during this resolution.\n * Used to detect and prevent cyclic resolutions.\n * @ignore\n */\n this.dirty = new WeakSet();\n /** A dict of parameters passed to a TermReference. */\n this.params = null;\n /**\n * The running count of placeables resolved so far.\n * Used to detect the Billion Laughs and Quadratic Blowup attacks.\n * @ignore\n */\n this.placeables = 0;\n this.bundle = bundle;\n this.errors = errors;\n this.args = args;\n }\n reportError(error) {\n if (!this.errors || !(error instanceof Error)) {\n throw error;\n }\n this.errors.push(error);\n }\n memoizeIntlObject(ctor, opts) {\n let cache = this.bundle._intls.get(ctor);\n if (!cache) {\n cache = {};\n this.bundle._intls.set(ctor, cache);\n }\n let id = JSON.stringify(opts);\n if (!cache[id]) {\n cache[id] = new ctor(this.bundle.locales, opts);\n }\n return cache[id];\n }\n}\n","/**\n * @overview\n *\n * The FTL resolver ships with a number of functions built-in.\n *\n * Each function take two arguments:\n * - args - an array of positional args\n * - opts - an object of key-value args\n *\n * Arguments to functions are guaranteed to already be instances of\n * `FluentValue`. Functions must return `FluentValues` as well.\n */\nimport { FluentNone, FluentNumber, FluentDateTime, } from \"./types.js\";\nfunction values(opts, allowed) {\n const unwrapped = Object.create(null);\n for (const [name, opt] of Object.entries(opts)) {\n if (allowed.includes(name)) {\n unwrapped[name] = opt.valueOf();\n }\n }\n return unwrapped;\n}\nconst NUMBER_ALLOWED = [\n \"unitDisplay\",\n \"currencyDisplay\",\n \"useGrouping\",\n \"minimumIntegerDigits\",\n \"minimumFractionDigits\",\n \"maximumFractionDigits\",\n \"minimumSignificantDigits\",\n \"maximumSignificantDigits\",\n];\n/**\n * The implementation of the `NUMBER()` builtin available to translations.\n *\n * Translations may call the `NUMBER()` builtin in order to specify formatting\n * options of a number. For example:\n *\n * pi = The value of π is {NUMBER($pi, maximumFractionDigits: 2)}.\n *\n * The implementation expects an array of `FluentValues` representing the\n * positional arguments, and an object of named `FluentValues` representing the\n * named parameters.\n *\n * The following options are recognized:\n *\n * unitDisplay\n * currencyDisplay\n * useGrouping\n * minimumIntegerDigits\n * minimumFractionDigits\n * maximumFractionDigits\n * minimumSignificantDigits\n * maximumSignificantDigits\n *\n * Other options are ignored.\n *\n * @param args The positional arguments passed to this `NUMBER()`.\n * @param opts The named argments passed to this `NUMBER()`.\n */\nexport function NUMBER(args, opts) {\n let arg = args[0];\n if (arg instanceof FluentNone) {\n return new FluentNone(`NUMBER(${arg.valueOf()})`);\n }\n if (arg instanceof FluentNumber) {\n return new FluentNumber(arg.valueOf(), {\n ...arg.opts,\n ...values(opts, NUMBER_ALLOWED),\n });\n }\n if (arg instanceof FluentDateTime) {\n return new FluentNumber(arg.valueOf(), {\n ...values(opts, NUMBER_ALLOWED),\n });\n }\n throw new TypeError(\"Invalid argument to NUMBER\");\n}\nconst DATETIME_ALLOWED = [\n \"dateStyle\",\n \"timeStyle\",\n \"fractionalSecondDigits\",\n \"dayPeriod\",\n \"hour12\",\n \"weekday\",\n \"era\",\n \"year\",\n \"month\",\n \"day\",\n \"hour\",\n \"minute\",\n \"second\",\n \"timeZoneName\",\n];\n/**\n * The implementation of the `DATETIME()` builtin available to translations.\n *\n * Translations may call the `DATETIME()` builtin in order to specify\n * formatting options of a number. For example:\n *\n * now = It's {DATETIME($today, month: \"long\")}.\n *\n * The implementation expects an array of `FluentValues` representing the\n * positional arguments, and an object of named `FluentValues` representing the\n * named parameters.\n *\n * The following options are recognized:\n *\n * dateStyle\n * timeStyle\n * fractionalSecondDigits\n * dayPeriod\n * hour12\n * weekday\n * era\n * year\n * month\n * day\n * hour\n * minute\n * second\n * timeZoneName\n *\n * Other options are ignored.\n *\n * @param args The positional arguments passed to this `DATETIME()`.\n * @param opts The named argments passed to this `DATETIME()`.\n */\nexport function DATETIME(args, opts) {\n let arg = args[0];\n if (arg instanceof FluentNone) {\n return new FluentNone(`DATETIME(${arg.valueOf()})`);\n }\n if (arg instanceof FluentDateTime) {\n return new FluentDateTime(arg.valueOf(), {\n ...arg.opts,\n ...values(opts, DATETIME_ALLOWED),\n });\n }\n if (arg instanceof FluentNumber) {\n return new FluentDateTime(arg.valueOf(), {\n ...values(opts, DATETIME_ALLOWED),\n });\n }\n throw new TypeError(\"Invalid argument to DATETIME\");\n}\n","const cache = new Map();\nexport function getMemoizerForLocale(locales) {\n const stringLocale = Array.isArray(locales) ? locales.join(\" \") : locales;\n let memoizer = cache.get(stringLocale);\n if (memoizer === undefined) {\n memoizer = new Map();\n cache.set(stringLocale, memoizer);\n }\n return memoizer;\n}\n","import { resolveComplexPattern } from \"./resolver.js\";\nimport { Scope } from \"./scope.js\";\nimport { FluentNone } from \"./types.js\";\nimport { NUMBER, DATETIME } from \"./builtins.js\";\nimport { getMemoizerForLocale } from \"./memoizer.js\";\n/**\n * Message bundles are single-language stores of translation resources. They are\n * responsible for formatting message values and attributes to strings.\n */\nexport class FluentBundle {\n /**\n * Create an instance of `FluentBundle`.\n *\n * @example\n * ```js\n * let bundle = new FluentBundle([\"en-US\", \"en\"]);\n *\n * let bundle = new FluentBundle(locales, {useIsolating: false});\n *\n * let bundle = new FluentBundle(locales, {\n * useIsolating: true,\n * functions: {\n * NODE_ENV: () => process.env.NODE_ENV\n * }\n * });\n * ```\n *\n * @param locales - Used to instantiate `Intl` formatters used by translations.\n * @param options - Optional configuration for the bundle.\n */\n constructor(locales, { functions, useIsolating = true, transform = (v) => v, } = {}) {\n /** @ignore */\n this._terms = new Map();\n /** @ignore */\n this._messages = new Map();\n this.locales = Array.isArray(locales) ? locales : [locales];\n this._functions = {\n NUMBER,\n DATETIME,\n ...functions,\n };\n this._useIsolating = useIsolating;\n this._transform = transform;\n this._intls = getMemoizerForLocale(locales);\n }\n /**\n * Check if a message is present in the bundle.\n *\n * @param id - The identifier of the message to check.\n */\n hasMessage(id) {\n return this._messages.has(id);\n }\n /**\n * Return a raw unformatted message object from the bundle.\n *\n * Raw messages are `{value, attributes}` shapes containing translation units\n * called `Patterns`. `Patterns` are implementation-specific; they should be\n * treated as black boxes and formatted with `FluentBundle.formatPattern`.\n *\n * @param id - The identifier of the message to check.\n */\n getMessage(id) {\n return this._messages.get(id);\n }\n /**\n * Add a translation resource to the bundle.\n *\n * @example\n * ```js\n * let res = new FluentResource(\"foo = Foo\");\n * bundle.addResource(res);\n * bundle.getMessage(\"foo\");\n * // → {value: .., attributes: {..}}\n * ```\n *\n * @param res\n * @param options\n */\n addResource(res, { allowOverrides = false, } = {}) {\n const errors = [];\n for (let i = 0; i < res.body.length; i++) {\n let entry = res.body[i];\n if (entry.id.startsWith(\"-\")) {\n // Identifiers starting with a dash (-) define terms. Terms are private\n // and cannot be retrieved from FluentBundle.\n if (allowOverrides === false && this._terms.has(entry.id)) {\n errors.push(new Error(`Attempt to override an existing term: \"${entry.id}\"`));\n continue;\n }\n this._terms.set(entry.id, entry);\n }\n else {\n if (allowOverrides === false && this._messages.has(entry.id)) {\n errors.push(new Error(`Attempt to override an existing message: \"${entry.id}\"`));\n continue;\n }\n this._messages.set(entry.id, entry);\n }\n }\n return errors;\n }\n /**\n * Format a `Pattern` to a string.\n *\n * Format a raw `Pattern` into a string. `args` will be used to resolve\n * references to variables passed as arguments to the translation.\n *\n * In case of errors `formatPattern` will try to salvage as much of the\n * translation as possible and will still return a string. For performance\n * reasons, the encountered errors are not returned but instead are appended\n * to the `errors` array passed as the third argument.\n *\n * If `errors` is omitted, the first encountered error will be thrown.\n *\n * @example\n * ```js\n * let errors = [];\n * bundle.addResource(\n * new FluentResource(\"hello = Hello, {$name}!\"));\n *\n * let hello = bundle.getMessage(\"hello\");\n * if (hello.value) {\n * bundle.formatPattern(hello.value, {name: \"Jane\"}, errors);\n * // Returns \"Hello, Jane!\" and `errors` is empty.\n *\n * bundle.formatPattern(hello.value, undefined, errors);\n * // Returns \"Hello, {$name}!\" and `errors` is now:\n * // []\n * }\n * ```\n */\n formatPattern(pattern, args = null, errors = null) {\n // Resolve a simple pattern without creating a scope. No error handling is\n // required; by definition simple patterns don't have placeables.\n if (typeof pattern === \"string\") {\n return this._transform(pattern);\n }\n // Resolve a complex pattern.\n let scope = new Scope(this, errors, args);\n try {\n let value = resolveComplexPattern(scope, pattern);\n return value.toString(scope);\n }\n catch (err) {\n if (scope.errors && err instanceof Error) {\n scope.errors.push(err);\n return new FluentNone().toString(scope);\n }\n throw err;\n }\n }\n}\n","// This regex is used to iterate through the beginnings of messages and terms.\n// With the /m flag, the ^ matches at the beginning of every line.\nconst RE_MESSAGE_START = /^(-?[a-zA-Z][\\w-]*) *= */gm;\n// Both Attributes and Variants are parsed in while loops. These regexes are\n// used to break out of them.\nconst RE_ATTRIBUTE_START = /\\.([a-zA-Z][\\w-]*) *= */y;\nconst RE_VARIANT_START = /\\*?\\[/y;\nconst RE_NUMBER_LITERAL = /(-?[0-9]+(?:\\.([0-9]+))?)/y;\nconst RE_IDENTIFIER = /([a-zA-Z][\\w-]*)/y;\nconst RE_REFERENCE = /([$-])?([a-zA-Z][\\w-]*)(?:\\.([a-zA-Z][\\w-]*))?/y;\nconst RE_FUNCTION_NAME = /^[A-Z][A-Z0-9_-]*$/;\n// A \"run\" is a sequence of text or string literal characters which don't\n// require any special handling. For TextElements such special characters are: {\n// (starts a placeable), and line breaks which require additional logic to check\n// if the next line is indented. For StringLiterals they are: \\ (starts an\n// escape sequence), \" (ends the literal), and line breaks which are not allowed\n// in StringLiterals. Note that string runs may be empty; text runs may not.\nconst RE_TEXT_RUN = /([^{}\\n\\r]+)/y;\nconst RE_STRING_RUN = /([^\\\\\"\\n\\r]*)/y;\n// Escape sequences.\nconst RE_STRING_ESCAPE = /\\\\([\\\\\"])/y;\nconst RE_UNICODE_ESCAPE = /\\\\u([a-fA-F0-9]{4})|\\\\U([a-fA-F0-9]{6})/y;\n// Used for trimming TextElements and indents.\nconst RE_LEADING_NEWLINES = /^\\n+/;\nconst RE_TRAILING_SPACES = / +$/;\n// Used in makeIndent to strip spaces from blank lines and normalize CRLF to LF.\nconst RE_BLANK_LINES = / *\\r?\\n/g;\n// Used in makeIndent to measure the indentation.\nconst RE_INDENT = /( *)$/;\n// Common tokens.\nconst TOKEN_BRACE_OPEN = /{\\s*/y;\nconst TOKEN_BRACE_CLOSE = /\\s*}/y;\nconst TOKEN_BRACKET_OPEN = /\\[\\s*/y;\nconst TOKEN_BRACKET_CLOSE = /\\s*] */y;\nconst TOKEN_PAREN_OPEN = /\\s*\\(\\s*/y;\nconst TOKEN_ARROW = /\\s*->\\s*/y;\nconst TOKEN_COLON = /\\s*:\\s*/y;\n// Note the optional comma. As a deviation from the Fluent EBNF, the parser\n// doesn't enforce commas between call arguments.\nconst TOKEN_COMMA = /\\s*,?\\s*/y;\nconst TOKEN_BLANK = /\\s+/y;\n/**\n * Fluent Resource is a structure storing parsed localization entries.\n */\nexport class FluentResource {\n constructor(source) {\n this.body = [];\n RE_MESSAGE_START.lastIndex = 0;\n let cursor = 0;\n // Iterate over the beginnings of messages and terms to efficiently skip\n // comments and recover from errors.\n while (true) {\n let next = RE_MESSAGE_START.exec(source);\n if (next === null) {\n break;\n }\n cursor = RE_MESSAGE_START.lastIndex;\n try {\n this.body.push(parseMessage(next[1]));\n }\n catch (err) {\n if (err instanceof SyntaxError) {\n // Don't report any Fluent syntax errors. Skip directly to the\n // beginning of the next message or term.\n continue;\n }\n throw err;\n }\n }\n // The parser implementation is inlined below for performance reasons,\n // as well as for convenience of accessing `source` and `cursor`.\n // The parser focuses on minimizing the number of false negatives at the\n // expense of increasing the risk of false positives. In other words, it\n // aims at parsing valid Fluent messages with a success rate of 100%, but it\n // may also parse a few invalid messages which the reference parser would\n // reject. The parser doesn't perform any validation and may produce entries\n // which wouldn't make sense in the real world. For best results users are\n // advised to validate translations with the fluent-syntax parser\n // pre-runtime.\n // The parser makes an extensive use of sticky regexes which can be anchored\n // to any offset of the source string without slicing it. Errors are thrown\n // to bail out of parsing of ill-formed messages.\n function test(re) {\n re.lastIndex = cursor;\n return re.test(source);\n }\n // Advance the cursor by the char if it matches. May be used as a predicate\n // (was the match found?) or, if errorClass is passed, as an assertion.\n function consumeChar(char, errorClass) {\n if (source[cursor] === char) {\n cursor++;\n return true;\n }\n if (errorClass) {\n throw new errorClass(`Expected ${char}`);\n }\n return false;\n }\n // Advance the cursor by the token if it matches. May be used as a predicate\n // (was the match found?) or, if errorClass is passed, as an assertion.\n function consumeToken(re, errorClass) {\n if (test(re)) {\n cursor = re.lastIndex;\n return true;\n }\n if (errorClass) {\n throw new errorClass(`Expected ${re.toString()}`);\n }\n return false;\n }\n // Execute a regex, advance the cursor, and return all capture groups.\n function match(re) {\n re.lastIndex = cursor;\n let result = re.exec(source);\n if (result === null) {\n throw new SyntaxError(`Expected ${re.toString()}`);\n }\n cursor = re.lastIndex;\n return result;\n }\n // Execute a regex, advance the cursor, and return the capture group.\n function match1(re) {\n return match(re)[1];\n }\n function parseMessage(id) {\n let value = parsePattern();\n let attributes = parseAttributes();\n if (value === null && Object.keys(attributes).length === 0) {\n throw new SyntaxError(\"Expected message value or attributes\");\n }\n return { id, value, attributes };\n }\n function parseAttributes() {\n let attrs = Object.create(null);\n while (test(RE_ATTRIBUTE_START)) {\n let name = match1(RE_ATTRIBUTE_START);\n let value = parsePattern();\n if (value === null) {\n throw new SyntaxError(\"Expected attribute value\");\n }\n attrs[name] = value;\n }\n return attrs;\n }\n function parsePattern() {\n let first;\n // First try to parse any simple text on the same line as the id.\n if (test(RE_TEXT_RUN)) {\n first = match1(RE_TEXT_RUN);\n }\n // If there's a placeable on the first line, parse a complex pattern.\n if (source[cursor] === \"{\" || source[cursor] === \"}\") {\n // Re-use the text parsed above, if possible.\n return parsePatternElements(first ? [first] : [], Infinity);\n }\n // RE_TEXT_VALUE stops at newlines. Only continue parsing the pattern if\n // what comes after the newline is indented.\n let indent = parseIndent();\n if (indent) {\n if (first) {\n // If there's text on the first line, the blank block is part of the\n // translation content in its entirety.\n return parsePatternElements([first, indent], indent.length);\n }\n // Otherwise, we're dealing with a block pattern, i.e. a pattern which\n // starts on a new line. Discrad the leading newlines but keep the\n // inline indent; it will be used by the dedentation logic.\n indent.value = trim(indent.value, RE_LEADING_NEWLINES);\n return parsePatternElements([indent], indent.length);\n }\n if (first) {\n // It was just a simple inline text after all.\n return trim(first, RE_TRAILING_SPACES);\n }\n return null;\n }\n // Parse a complex pattern as an array of elements.\n function parsePatternElements(elements = [], commonIndent) {\n while (true) {\n if (test(RE_TEXT_RUN)) {\n elements.push(match1(RE_TEXT_RUN));\n continue;\n }\n if (source[cursor] === \"{\") {\n elements.push(parsePlaceable());\n continue;\n }\n if (source[cursor] === \"}\") {\n throw new SyntaxError(\"Unbalanced closing brace\");\n }\n let indent = parseIndent();\n if (indent) {\n elements.push(indent);\n commonIndent = Math.min(commonIndent, indent.length);\n continue;\n }\n break;\n }\n let lastIndex = elements.length - 1;\n let lastElement = elements[lastIndex];\n // Trim the trailing spaces in the last element if it's a TextElement.\n if (typeof lastElement === \"string\") {\n elements[lastIndex] = trim(lastElement, RE_TRAILING_SPACES);\n }\n let baked = [];\n for (let element of elements) {\n if (element instanceof Indent) {\n // Dedent indented lines by the maximum common indent.\n element = element.value.slice(0, element.value.length - commonIndent);\n }\n if (element) {\n baked.push(element);\n }\n }\n return baked;\n }\n function parsePlaceable() {\n consumeToken(TOKEN_BRACE_OPEN, SyntaxError);\n let selector = parseInlineExpression();\n if (consumeToken(TOKEN_BRACE_CLOSE)) {\n return selector;\n }\n if (consumeToken(TOKEN_ARROW)) {\n let variants = parseVariants();\n consumeToken(TOKEN_BRACE_CLOSE, SyntaxError);\n return {\n type: \"select\",\n selector,\n ...variants,\n };\n }\n throw new SyntaxError(\"Unclosed placeable\");\n }\n function parseInlineExpression() {\n if (source[cursor] === \"{\") {\n // It's a nested placeable.\n return parsePlaceable();\n }\n if (test(RE_REFERENCE)) {\n let [, sigil, name, attr = null] = match(RE_REFERENCE);\n if (sigil === \"$\") {\n return { type: \"var\", name };\n }\n if (consumeToken(TOKEN_PAREN_OPEN)) {\n let args = parseArguments();\n if (sigil === \"-\") {\n // A parameterized term: -term(...).\n return { type: \"term\", name, attr, args };\n }\n if (RE_FUNCTION_NAME.test(name)) {\n return { type: \"func\", name, args };\n }\n throw new SyntaxError(\"Function names must be all upper-case\");\n }\n if (sigil === \"-\") {\n // A non-parameterized term: -term.\n return {\n type: \"term\",\n name,\n attr,\n args: [],\n };\n }\n return { type: \"mesg\", name, attr };\n }\n return parseLiteral();\n }\n function parseArguments() {\n let args = [];\n while (true) {\n switch (source[cursor]) {\n case \")\": // End of the argument list.\n cursor++;\n return args;\n case undefined: // EOF\n throw new SyntaxError(\"Unclosed argument list\");\n }\n args.push(parseArgument());\n // Commas between arguments are treated as whitespace.\n consumeToken(TOKEN_COMMA);\n }\n }\n function parseArgument() {\n let expr = parseInlineExpression();\n if (expr.type !== \"mesg\") {\n return expr;\n }\n if (consumeToken(TOKEN_COLON)) {\n // The reference is the beginning of a named argument.\n return {\n type: \"narg\",\n name: expr.name,\n value: parseLiteral(),\n };\n }\n // It's a regular message reference.\n return expr;\n }\n function parseVariants() {\n let variants = [];\n let count = 0;\n let star;\n while (test(RE_VARIANT_START)) {\n if (consumeChar(\"*\")) {\n star = count;\n }\n let key = parseVariantKey();\n let value = parsePattern();\n if (value === null) {\n throw new SyntaxError(\"Expected variant value\");\n }\n variants[count++] = { key, value };\n }\n if (count === 0) {\n return null;\n }\n if (star === undefined) {\n throw new SyntaxError(\"Expected default variant\");\n }\n return { variants, star };\n }\n function parseVariantKey() {\n consumeToken(TOKEN_BRACKET_OPEN, SyntaxError);\n let key;\n if (test(RE_NUMBER_LITERAL)) {\n key = parseNumberLiteral();\n }\n else {\n key = {\n type: \"str\",\n value: match1(RE_IDENTIFIER),\n };\n }\n consumeToken(TOKEN_BRACKET_CLOSE, SyntaxError);\n return key;\n }\n function parseLiteral() {\n if (test(RE_NUMBER_LITERAL)) {\n return parseNumberLiteral();\n }\n if (source[cursor] === '\"') {\n return parseStringLiteral();\n }\n throw new SyntaxError(\"Invalid expression\");\n }\n function parseNumberLiteral() {\n let [, value, fraction = \"\"] = match(RE_NUMBER_LITERAL);\n let precision = fraction.length;\n return {\n type: \"num\",\n value: parseFloat(value),\n precision,\n };\n }\n function parseStringLiteral() {\n consumeChar('\"', SyntaxError);\n let value = \"\";\n while (true) {\n value += match1(RE_STRING_RUN);\n if (source[cursor] === \"\\\\\") {\n value += parseEscapeSequence();\n continue;\n }\n if (consumeChar('\"')) {\n return { type: \"str\", value };\n }\n // We've reached an EOL of EOF.\n throw new SyntaxError(\"Unclosed string literal\");\n }\n }\n // Unescape known escape sequences.\n function parseEscapeSequence() {\n if (test(RE_STRING_ESCAPE)) {\n return match1(RE_STRING_ESCAPE);\n }\n if (test(RE_UNICODE_ESCAPE)) {\n let [, codepoint4, codepoint6] = match(RE_UNICODE_ESCAPE);\n let codepoint = parseInt(codepoint4 || codepoint6, 16);\n return codepoint <= 0xd7ff || 0xe000 <= codepoint\n ? // It's a Unicode scalar value.\n String.fromCodePoint(codepoint)\n : // Lonely surrogates can cause trouble when the parsing result is\n // saved using UTF-8. Use U+FFFD REPLACEMENT CHARACTER instead.\n \"�\";\n }\n throw new SyntaxError(\"Unknown escape sequence\");\n }\n // Parse blank space. Return it if it looks like indent before a pattern\n // line. Skip it othwerwise.\n function parseIndent() {\n let start = cursor;\n consumeToken(TOKEN_BLANK);\n // Check the first non-blank character after the indent.\n switch (source[cursor]) {\n case \".\":\n case \"[\":\n case \"*\":\n case \"}\":\n case undefined: // EOF\n // A special character. End the Pattern.\n return false;\n case \"{\":\n // Placeables don't require indentation (in EBNF: block-placeable).\n // Continue the Pattern.\n return makeIndent(source.slice(start, cursor));\n }\n // If the first character on the line is not one of the special characters\n // listed above, it's a regular text character. Check if there's at least\n // one space of indent before it.\n if (source[cursor - 1] === \" \") {\n // It's an indented text character (in EBNF: indented-char). Continue\n // the Pattern.\n return makeIndent(source.slice(start, cursor));\n }\n // A not-indented text character is likely the identifier of the next\n // message. End the Pattern.\n return false;\n }\n // Trim blanks in text according to the given regex.\n function trim(text, re) {\n return text.replace(re, \"\");\n }\n // Normalize a blank block and extract the indent details.\n function makeIndent(blank) {\n let value = blank.replace(RE_BLANK_LINES, \"\\n\");\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n let length = RE_INDENT.exec(blank)[1].length;\n return new Indent(value, length);\n }\n }\n}\nclass Indent {\n constructor(value, length) {\n this.value = value;\n this.length = length;\n }\n}\n","/**\n * @module fluent\n * @overview\n *\n * `fluent` is a JavaScript implementation of Project Fluent, a localization\n * framework designed to unleash the expressive power of the natural language.\n *\n */\nexport { FluentBundle } from \"./bundle.js\";\nexport { FluentResource } from \"./resource.js\";\nexport { FluentType, FluentNone, FluentNumber, FluentDateTime, } from \"./types.js\";\n","/* eslint no-console: [\"error\", {allow: [\"warn\"]}] */\n/* global console */\n// Match the opening angle bracket (<) in HTML tags, and HTML entities like\n// &, &, &.\nconst reOverlay = /<|&#?\\w+;/;\n/**\n * Elements allowed in translations even if they are not present in the source\n * HTML. They are text-level elements as defined by the HTML5 spec:\n * https://www.w3.org/TR/html5/text-level-semantics.html with the exception of:\n *\n * - a - because we don't allow href on it anyways,\n * - ruby, rt, rp - because we don't allow nested elements to be inserted.\n */\nconst TEXT_LEVEL_ELEMENTS = {\n \"http://www.w3.org/1999/xhtml\": [\n \"em\",\n \"strong\",\n \"small\",\n \"s\",\n \"cite\",\n \"q\",\n \"dfn\",\n \"abbr\",\n \"data\",\n \"time\",\n \"code\",\n \"var\",\n \"samp\",\n \"kbd\",\n \"sub\",\n \"sup\",\n \"i\",\n \"b\",\n \"u\",\n \"mark\",\n \"bdi\",\n \"bdo\",\n \"span\",\n \"br\",\n \"wbr\",\n ],\n};\nconst LOCALIZABLE_ATTRIBUTES = {\n \"http://www.w3.org/1999/xhtml\": {\n global: [\"title\", \"aria-label\", \"aria-valuetext\"],\n a: [\"download\"],\n area: [\"download\", \"alt\"],\n // value is special-cased in isAttrNameLocalizable\n input: [\"alt\", \"placeholder\"],\n menuitem: [\"label\"],\n menu: [\"label\"],\n optgroup: [\"label\"],\n option: [\"label\"],\n track: [\"label\"],\n img: [\"alt\"],\n textarea: [\"placeholder\"],\n th: [\"abbr\"],\n },\n \"http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul\": {\n global: [\n \"accesskey\",\n \"aria-label\",\n \"aria-valuetext\",\n \"label\",\n \"title\",\n \"tooltiptext\",\n ],\n description: [\"value\"],\n key: [\"key\", \"keycode\"],\n label: [\"value\"],\n textbox: [\"placeholder\", \"value\"],\n },\n};\n/**\n * Translate an element.\n *\n * Translate the element's text content and attributes. Some HTML markup is\n * allowed in the translation. The element's children with the data-l10n-name\n * attribute will be treated as arguments to the translation. If the\n * translation defines the same children, their attributes and text contents\n * will be used for translating the matching source child.\n *\n * @param {Element} element\n * @param {Object} translation\n * @private\n */\nexport default function translateElement(element, translation) {\n const { value } = translation;\n if (typeof value === \"string\") {\n if (element.localName === \"title\" &&\n element.namespaceURI === \"http://www.w3.org/1999/xhtml\") {\n // A special case for the HTML title element whose content must be text.\n element.textContent = value;\n }\n else if (!reOverlay.test(value)) {\n // If the translation doesn't contain any markup skip the overlay logic.\n element.textContent = value;\n }\n else {\n // Else parse the translation's HTML using an inert template element,\n // sanitize it and replace the element's content.\n const templateElement = element.ownerDocument.createElementNS(\"http://www.w3.org/1999/xhtml\", \"template\");\n templateElement.innerHTML = value;\n overlayChildNodes(templateElement.content, element);\n }\n }\n // Even if the translation doesn't define any localizable attributes, run\n // overlayAttributes to remove any localizable attributes set by previous\n // translations.\n overlayAttributes(translation, element);\n}\n/**\n * Replace child nodes of an element with child nodes of another element.\n *\n * The contents of the target element will be cleared and fully replaced with\n * sanitized contents of the source element.\n *\n * @param {DocumentFragment} fromFragment - The source of children to overlay.\n * @param {Element} toElement - The target of the overlay.\n * @private\n */\nfunction overlayChildNodes(fromFragment, toElement) {\n for (const childNode of fromFragment.childNodes) {\n if (childNode.nodeType === childNode.TEXT_NODE) {\n // Keep the translated text node.\n continue;\n }\n if (childNode.hasAttribute(\"data-l10n-name\")) {\n const sanitized = getNodeForNamedElement(toElement, childNode);\n fromFragment.replaceChild(sanitized, childNode);\n continue;\n }\n if (isElementAllowed(childNode)) {\n const sanitized = createSanitizedElement(childNode);\n fromFragment.replaceChild(sanitized, childNode);\n continue;\n }\n console.warn(`An element of forbidden type \"${childNode.localName}\" was found in ` +\n \"the translation. Only safe text-level elements and elements with \" +\n \"data-l10n-name are allowed.\");\n // If all else fails, replace the element with its text content.\n fromFragment.replaceChild(createTextNodeFromTextContent(childNode), childNode);\n }\n toElement.textContent = \"\";\n toElement.appendChild(fromFragment);\n}\nfunction hasAttribute(attributes, name) {\n if (!attributes) {\n return false;\n }\n for (let attr of attributes) {\n if (attr.name === name) {\n return true;\n }\n }\n return false;\n}\n/**\n * Transplant localizable attributes of an element to another element.\n *\n * Any localizable attributes already set on the target element will be\n * cleared.\n *\n * @param {Element|Object} fromElement - The source of child nodes to overlay.\n * @param {Element} toElement - The target of the overlay.\n * @private\n */\nfunction overlayAttributes(fromElement, toElement) {\n const explicitlyAllowed = toElement.hasAttribute(\"data-l10n-attrs\")\n ? toElement\n .getAttribute(\"data-l10n-attrs\")\n .split(\",\")\n .map(i => i.trim())\n : null;\n // Remove existing localizable attributes if they\n // will not be used in the new translation.\n for (const attr of Array.from(toElement.attributes)) {\n if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) &&\n !hasAttribute(fromElement.attributes, attr.name)) {\n toElement.removeAttribute(attr.name);\n }\n }\n // fromElement might be a {value, attributes} object as returned by\n // Localization.messageFromBundle. In which case attributes may be null to\n // save GC cycles.\n if (!fromElement.attributes) {\n return;\n }\n // Set localizable attributes.\n for (const attr of Array.from(fromElement.attributes)) {\n if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) &&\n toElement.getAttribute(attr.name) !== attr.value) {\n toElement.setAttribute(attr.name, attr.value);\n }\n }\n}\n/**\n * Sanitize a child element created by the translation.\n *\n * Try to find a corresponding child in sourceElement and use it as the base\n * for the sanitization. This will preserve functional attribtues defined on\n * the child element in the source HTML.\n *\n * @param {Element} sourceElement - The source for data-l10n-name lookups.\n * @param {Element} translatedChild - The translated child to be sanitized.\n * @returns {Element}\n * @private\n */\nfunction getNodeForNamedElement(sourceElement, translatedChild) {\n const childName = translatedChild.getAttribute(\"data-l10n-name\");\n const sourceChild = sourceElement.querySelector(`[data-l10n-name=\"${childName}\"]`);\n if (!sourceChild) {\n console.warn(`An element named \"${childName}\" wasn't found in the source.`);\n return createTextNodeFromTextContent(translatedChild);\n }\n if (sourceChild.localName !== translatedChild.localName) {\n console.warn(`An element named \"${childName}\" was found in the translation ` +\n `but its type ${translatedChild.localName} didn't match the ` +\n `element found in the source (${sourceChild.localName}).`);\n return createTextNodeFromTextContent(translatedChild);\n }\n // Remove it from sourceElement so that the translation cannot use\n // the same reference name again.\n sourceElement.removeChild(sourceChild);\n // We can't currently guarantee that a translation won't remove\n // sourceChild from the element completely, which could break the app if\n // it relies on an event handler attached to the sourceChild. Let's make\n // this limitation explicit for now by breaking the identitiy of the\n // sourceChild by cloning it. This will destroy all event handlers\n // attached to sourceChild via addEventListener and via on\n // properties.\n const clone = sourceChild.cloneNode(false);\n return shallowPopulateUsing(translatedChild, clone);\n}\n/**\n * Sanitize an allowed element.\n *\n * Text-level elements allowed in translations may only use safe attributes\n * and will have any nested markup stripped to text content.\n *\n * @param {Element} element - The element to be sanitized.\n * @returns {Element}\n * @private\n */\nfunction createSanitizedElement(element) {\n // Start with an empty element of the same type to remove nested children\n // and non-localizable attributes defined by the translation.\n const clone = element.ownerDocument.createElement(element.localName);\n return shallowPopulateUsing(element, clone);\n}\n/**\n * Convert an element to a text node.\n *\n * @param {Element} element - The element to be sanitized.\n * @returns {Node}\n * @private\n */\nfunction createTextNodeFromTextContent(element) {\n return element.ownerDocument.createTextNode(element.textContent);\n}\n/**\n * Check if element is allowed in the translation.\n *\n * This method is used by the sanitizer when the translation markup contains\n * an element which is not present in the source code.\n *\n * @param {Element} element\n * @returns {boolean}\n * @private\n */\nfunction isElementAllowed(element) {\n const allowed = TEXT_LEVEL_ELEMENTS[element.namespaceURI];\n return allowed && allowed.includes(element.localName);\n}\n/**\n * Check if attribute is allowed for the given element.\n *\n * This method is used by the sanitizer when the translation markup contains\n * DOM attributes, or when the translation has traits which map to DOM\n * attributes.\n *\n * `explicitlyAllowed` can be passed as a list of attributes explicitly\n * allowed on this element.\n *\n * @param {string} name\n * @param {Element} element\n * @param {Array} explicitlyAllowed\n * @returns {boolean}\n * @private\n */\nfunction isAttrNameLocalizable(name, element, explicitlyAllowed = null) {\n if (explicitlyAllowed && explicitlyAllowed.includes(name)) {\n return true;\n }\n const allowed = LOCALIZABLE_ATTRIBUTES[element.namespaceURI];\n if (!allowed) {\n return false;\n }\n const attrName = name.toLowerCase();\n const elemName = element.localName;\n // Is it a globally safe attribute?\n if (allowed.global.includes(attrName)) {\n return true;\n }\n // Are there no allowed attributes for this element?\n if (!allowed[elemName]) {\n return false;\n }\n // Is it allowed on this element?\n if (allowed[elemName].includes(attrName)) {\n return true;\n }\n // Special case for value on HTML inputs with type button, reset, submit\n if (element.namespaceURI === \"http://www.w3.org/1999/xhtml\" &&\n elemName === \"input\" &&\n attrName === \"value\") {\n const type = element.type.toLowerCase();\n if (type === \"submit\" || type === \"button\" || type === \"reset\") {\n return true;\n }\n }\n return false;\n}\n/**\n * Helper to set textContent and localizable attributes on an element.\n *\n * @param {Element} fromElement\n * @param {Element} toElement\n * @returns {Element}\n * @private\n */\nfunction shallowPopulateUsing(fromElement, toElement) {\n toElement.textContent = fromElement.textContent;\n overlayAttributes(fromElement, toElement);\n return toElement;\n}\n","/*\n * Base CachedIterable class.\n */\nexport default class CachedIterable extends Array {\n /**\n * Create a `CachedIterable` instance from an iterable or, if another\n * instance of `CachedIterable` is passed, return it without any\n * modifications.\n *\n * @param {Iterable} iterable\n * @returns {CachedIterable}\n */\n static from(iterable) {\n if (iterable instanceof this) {\n return iterable;\n }\n\n return new this(iterable);\n }\n}\n","import CachedIterable from \"./cached_iterable.mjs\";\n\n/*\n * CachedSyncIterable caches the elements yielded by an iterable.\n *\n * It can be used to iterate over an iterable many times without depleting the\n * iterable.\n */\nexport default class CachedSyncIterable extends CachedIterable {\n /**\n * Create an `CachedSyncIterable` instance.\n *\n * @param {Iterable} iterable\n * @returns {CachedSyncIterable}\n */\n constructor(iterable) {\n super();\n\n if (Symbol.iterator in Object(iterable)) {\n this.iterator = iterable[Symbol.iterator]();\n } else {\n throw new TypeError(\"Argument must implement the iteration protocol.\");\n }\n }\n\n [Symbol.iterator]() {\n const cached = this;\n let cur = 0;\n\n return {\n next() {\n if (cached.length <= cur) {\n cached.push(cached.iterator.next());\n }\n return cached[cur++];\n }\n };\n }\n\n /**\n * This method allows user to consume the next element from the iterator\n * into the cache.\n *\n * @param {number} count - number of elements to consume\n */\n touchNext(count = 1) {\n let idx = 0;\n while (idx++ < count) {\n const last = this[this.length - 1];\n if (last && last.done) {\n break;\n }\n this.push(this.iterator.next());\n }\n // Return the last cached {value, done} object to allow the calling\n // code to decide if it needs to call touchNext again.\n return this[this.length - 1];\n }\n}\n","import CachedIterable from \"./cached_iterable.mjs\";\n\n/*\n * CachedAsyncIterable caches the elements yielded by an async iterable.\n *\n * It can be used to iterate over an iterable many times without depleting the\n * iterable.\n */\nexport default class CachedAsyncIterable extends CachedIterable {\n /**\n * Create an `CachedAsyncIterable` instance.\n *\n * @param {Iterable} iterable\n * @returns {CachedAsyncIterable}\n */\n constructor(iterable) {\n super();\n\n if (Symbol.asyncIterator in Object(iterable)) {\n this.iterator = iterable[Symbol.asyncIterator]();\n } else if (Symbol.iterator in Object(iterable)) {\n this.iterator = iterable[Symbol.iterator]();\n } else {\n throw new TypeError(\"Argument must implement the iteration protocol.\");\n }\n }\n\n /**\n * Asynchronous iterator caching the yielded elements.\n *\n * Elements yielded by the original iterable will be cached and available\n * synchronously. Returns an async generator object implementing the\n * iterator protocol over the elements of the original (async or sync)\n * iterable.\n */\n [Symbol.asyncIterator]() {\n const cached = this;\n let cur = 0;\n\n return {\n async next() {\n if (cached.length <= cur) {\n cached.push(cached.iterator.next());\n }\n return cached[cur++];\n }\n };\n }\n\n /**\n * This method allows user to consume the next element from the iterator\n * into the cache.\n *\n * @param {number} count - number of elements to consume\n */\n async touchNext(count = 1) {\n let idx = 0;\n while (idx++ < count) {\n const last = this[this.length - 1];\n if (last && (await last).done) {\n break;\n }\n this.push(this.iterator.next());\n }\n // Return the last cached {value, done} object to allow the calling\n // code to decide if it needs to call touchNext again.\n return this[this.length - 1];\n }\n}\n","export {default as CachedSyncIterable} from \"./cached_sync_iterable.mjs\";\nexport {default as CachedAsyncIterable} from \"./cached_async_iterable.mjs\";\n","/* eslint no-console: [\"error\", { allow: [\"warn\", \"error\"] }] */\n/* global console */\nimport { CachedAsyncIterable } from \"cached-iterable\";\n/**\n * The `Localization` class is a central high-level API for vanilla\n * JavaScript use of Fluent.\n * It combines language negotiation, FluentBundle and I/O to\n * provide a scriptable API to format translations.\n */\nexport default class Localization {\n /**\n * @param {Array} resourceIds - List of resource IDs\n * @param {Function} generateBundles - Function that returns a\n * generator over FluentBundles\n *\n * @returns {Localization}\n */\n constructor(resourceIds = [], generateBundles) {\n this.resourceIds = resourceIds;\n this.generateBundles = generateBundles;\n this.onChange(true);\n }\n addResourceIds(resourceIds, eager = false) {\n this.resourceIds.push(...resourceIds);\n this.onChange(eager);\n return this.resourceIds.length;\n }\n removeResourceIds(resourceIds) {\n this.resourceIds = this.resourceIds.filter(r => !resourceIds.includes(r));\n this.onChange();\n return this.resourceIds.length;\n }\n /**\n * Format translations and handle fallback if needed.\n *\n * Format translations for `keys` from `FluentBundle` instances on this\n * DOMLocalization. In case of errors, fetch the next context in the\n * fallback chain.\n *\n * @param {Array} keys - Translation keys to format.\n * @param {Function} method - Formatting function.\n * @returns {Promise>}\n * @private\n */\n async formatWithFallback(keys, method) {\n const translations = [];\n let hasAtLeastOneBundle = false;\n for await (const bundle of this.bundles) {\n hasAtLeastOneBundle = true;\n const missingIds = keysFromBundle(method, bundle, keys, translations);\n if (missingIds.size === 0) {\n break;\n }\n if (typeof console !== \"undefined\") {\n const locale = bundle.locales[0];\n const ids = Array.from(missingIds).join(\", \");\n console.warn(`[fluent] Missing translations in ${locale}: ${ids}`);\n }\n }\n if (!hasAtLeastOneBundle && typeof console !== \"undefined\") {\n // eslint-disable-next-line max-len\n console.warn(`[fluent] Request for keys failed because no resource bundles got generated.\n keys: ${JSON.stringify(keys)}.\n resourceIds: ${JSON.stringify(this.resourceIds)}.`);\n }\n return translations;\n }\n /**\n * Format translations into `{value, attributes}` objects.\n *\n * The fallback logic is the same as in `formatValues`\n * but it returns `{value, attributes}` objects\n * which are suitable for the translation of DOM elements.\n *\n * Returns a Promise resolving to an array of the translation strings.\n *\n * @example\n * ```js\n * docL10n.formatMessages([\n * {id: 'hello', args: { who: 'Mary' }},\n * {id: 'welcome'}\n * ]).then(console.log);\n *\n * // [\n * // { value: 'Hello, Mary!', attributes: null },\n * // {\n * // value: 'Welcome!',\n * // attributes: [ { name: \"title\", value: 'Hello' } ]\n * // }\n * // ]\n * ```\n *\n * @param {Array} keys\n * @returns {Promise>}\n * @private\n */\n formatMessages(keys) {\n return this.formatWithFallback(keys, messageFromBundle);\n }\n /**\n * Retrieve translations corresponding to the passed keys.\n *\n * A generalized version of `DOMLocalization.formatValue`. Keys must\n * be `{id, args}` objects.\n *\n * Returns a Promise resolving to an array of the translation strings.\n *\n * @example\n * ```js\n * docL10n.formatValues([\n * {id: 'hello', args: { who: 'Mary' }},\n * {id: 'hello', args: { who: 'John' }},\n * {id: 'welcome'}\n * ]).then(console.log);\n *\n * // ['Hello, Mary!', 'Hello, John!', 'Welcome!']\n * ```\n *\n * @param {Array} keys\n * @returns {Promise>}\n */\n formatValues(keys) {\n return this.formatWithFallback(keys, valueFromBundle);\n }\n /**\n * Retrieve the translation corresponding to the `id` identifier.\n *\n * If passed, `args` is a simple hash object with a list of variables that\n * will be interpolated in the value of the translation.\n *\n * Returns a Promise resolving to the translation string.\n *\n * Use this sparingly for one-off messages which don't need to be\n * retranslated when the user changes their language preferences, e.g. in\n * notifications.\n *\n * @example\n * ```js\n * docL10n.formatValue(\n * 'hello', { who: 'world' }\n * ).then(console.log);\n *\n * // 'Hello, world!'\n * ```\n *\n * @param {string} id - Identifier of the translation to format\n * @param {Object} [args] - Optional external arguments\n * @returns {Promise}\n */\n async formatValue(id, args) {\n const [val] = await this.formatValues([{ id, args }]);\n return val;\n }\n handleEvent() {\n this.onChange();\n }\n /**\n * This method should be called when there's a reason to believe\n * that language negotiation or available resources changed.\n */\n onChange(eager = false) {\n this.bundles = CachedAsyncIterable.from(this.generateBundles(this.resourceIds));\n if (eager) {\n this.bundles.touchNext(2);\n }\n }\n}\n/**\n * Format the value of a message into a string or `null`.\n *\n * This function is passed as a method to `keysFromBundle` and resolve\n * a value of a single L10n Entity using provided `FluentBundle`.\n *\n * If the message doesn't have a value, return `null`.\n *\n * @param {FluentBundle} bundle\n * @param {Array} errors\n * @param {Object} message\n * @param {Object} args\n * @returns {string|null}\n * @private\n */\nfunction valueFromBundle(bundle, errors, message, args) {\n if (message.value) {\n return bundle.formatPattern(message.value, args, errors);\n }\n return null;\n}\n/**\n * Format all public values of a message into a {value, attributes} object.\n *\n * This function is passed as a method to `keysFromBundle` and resolve\n * a single L10n Entity using provided `FluentBundle`.\n *\n * The function will return an object with a value and attributes of the\n * entity.\n *\n * @param {FluentBundle} bundle\n * @param {Array} errors\n * @param {Object} message\n * @param {Object} args\n * @returns {Object}\n * @private\n */\nfunction messageFromBundle(bundle, errors, message, args) {\n const formatted = {\n value: null,\n attributes: null,\n };\n if (message.value) {\n formatted.value = bundle.formatPattern(message.value, args, errors);\n }\n let attrNames = Object.keys(message.attributes);\n if (attrNames.length > 0) {\n formatted.attributes = new Array(attrNames.length);\n for (let [i, name] of attrNames.entries()) {\n let value = bundle.formatPattern(message.attributes[name], args, errors);\n formatted.attributes[i] = { name, value };\n }\n }\n return formatted;\n}\n/**\n * This function is an inner function for `Localization.formatWithFallback`.\n *\n * It takes a `FluentBundle`, list of l10n-ids and a method to be used for\n * key resolution (either `valueFromBundle` or `messageFromBundle`) and\n * optionally a value returned from `keysFromBundle` executed against\n * another `FluentBundle`.\n *\n * The idea here is that if the previous `FluentBundle` did not resolve\n * all keys, we're calling this function with the next context to resolve\n * the remaining ones.\n *\n * In the function, we loop over `keys` and check if we have the `prev`\n * passed and if it has an error entry for the position we're in.\n *\n * If it doesn't, it means that we have a good translation for this key and\n * we return it. If it does, we'll try to resolve the key using the passed\n * `FluentBundle`.\n *\n * In the end, we fill the translations array, and return the Set with\n * missing ids.\n *\n * See `Localization.formatWithFallback` for more info on how this is used.\n *\n * @param {Function} method\n * @param {FluentBundle} bundle\n * @param {Array} keys\n * @param {{Array<{value: string, attributes: Object}>}} translations\n *\n * @returns {Set}\n * @private\n */\nfunction keysFromBundle(method, bundle, keys, translations) {\n const messageErrors = [];\n const missingIds = new Set();\n keys.forEach(({ id, args }, i) => {\n if (translations[i] !== undefined) {\n return;\n }\n let message = bundle.getMessage(id);\n if (message) {\n messageErrors.length = 0;\n translations[i] = method(bundle, messageErrors, message, args);\n if (messageErrors.length > 0 && typeof console !== \"undefined\") {\n const locale = bundle.locales[0];\n const errors = messageErrors.join(\", \");\n // eslint-disable-next-line max-len\n console.warn(`[fluent][resolver] errors in ${locale}/${id}: ${errors}.`);\n }\n }\n else {\n missingIds.add(id);\n }\n });\n return missingIds;\n}\n","import translateElement from \"./overlay.js\";\nimport Localization from \"./localization.js\";\nconst L10NID_ATTR_NAME = \"data-l10n-id\";\nconst L10NARGS_ATTR_NAME = \"data-l10n-args\";\nconst L10N_ELEMENT_QUERY = `[${L10NID_ATTR_NAME}]`;\n/**\n * The `DOMLocalization` class is responsible for fetching resources and\n * formatting translations.\n *\n * It implements the fallback strategy in case of errors encountered during the\n * formatting of translations and methods for observing DOM\n * trees with a `MutationObserver`.\n */\nexport default class DOMLocalization extends Localization {\n /**\n * @param {Array} resourceIds - List of resource IDs\n * @param {Function} generateBundles - Function that returns a\n * generator over FluentBundles\n * @returns {DOMLocalization}\n */\n constructor(resourceIds, generateBundles) {\n super(resourceIds, generateBundles);\n // A Set of DOM trees observed by the `MutationObserver`.\n this.roots = new Set();\n // requestAnimationFrame handler.\n this.pendingrAF = null;\n // list of elements pending for translation.\n this.pendingElements = new Set();\n this.windowElement = null;\n this.mutationObserver = null;\n this.observerConfig = {\n attributes: true,\n characterData: false,\n childList: true,\n subtree: true,\n attributeFilter: [L10NID_ATTR_NAME, L10NARGS_ATTR_NAME],\n };\n }\n onChange(eager = false) {\n super.onChange(eager);\n if (this.roots) {\n this.translateRoots();\n }\n }\n /**\n * Set the `data-l10n-id` and `data-l10n-args` attributes on DOM elements.\n * FluentDOM makes use of mutation observers to detect changes\n * to `data-l10n-*` attributes and translate elements asynchronously.\n * `setAttributes` is a convenience method which allows to translate\n * DOM elements declaratively.\n *\n * You should always prefer to use `data-l10n-id` on elements (statically in\n * HTML or dynamically via `setAttributes`) over manually retrieving\n * translations with `format`. The use of attributes ensures that the\n * elements can be retranslated when the user changes their language\n * preferences.\n *\n * ```javascript\n * localization.setAttributes(\n * document.querySelector('#welcome'), 'hello', { who: 'world' }\n * );\n * ```\n *\n * This will set the following attributes on the `#welcome` element.\n * The MutationObserver will pick up this change and will localize the element\n * asynchronously.\n *\n * ```html\n *

\n *

\n * ```\n *\n * @param {Element} element - Element to set attributes on\n * @param {string} id - l10n-id string\n * @param {Object} args - KVP list of l10n arguments\n * @returns {Element}\n */\n setAttributes(element, id, args) {\n element.setAttribute(L10NID_ATTR_NAME, id);\n if (args) {\n element.setAttribute(L10NARGS_ATTR_NAME, JSON.stringify(args));\n }\n else {\n element.removeAttribute(L10NARGS_ATTR_NAME);\n }\n return element;\n }\n /**\n * Get the `data-l10n-*` attributes from DOM elements.\n *\n * ```javascript\n * localization.getAttributes(\n * document.querySelector('#welcome')\n * );\n * // -> { id: 'hello', args: { who: 'world' } }\n * ```\n *\n * @param {Element} element - HTML element\n * @returns {{id: string, args: Object}}\n */\n getAttributes(element) {\n return {\n id: element.getAttribute(L10NID_ATTR_NAME),\n args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null),\n };\n }\n /**\n * Add `newRoot` to the list of roots managed by this `DOMLocalization`.\n *\n * Additionally, if this `DOMLocalization` has an observer, start observing\n * `newRoot` in order to translate mutations in it.\n *\n * @param {Element} newRoot - Root to observe.\n */\n connectRoot(newRoot) {\n for (const root of this.roots) {\n if (root === newRoot ||\n root.contains(newRoot) ||\n newRoot.contains(root)) {\n throw new Error(\"Cannot add a root that overlaps with existing root.\");\n }\n }\n if (this.windowElement) {\n if (this.windowElement !== newRoot.ownerDocument.defaultView) {\n throw new Error(`Cannot connect a root:\n DOMLocalization already has a root from a different window.`);\n }\n }\n else {\n this.windowElement = newRoot.ownerDocument.defaultView;\n this.mutationObserver = new this.windowElement.MutationObserver(mutations => this.translateMutations(mutations));\n }\n this.roots.add(newRoot);\n this.mutationObserver.observe(newRoot, this.observerConfig);\n }\n /**\n * Remove `root` from the list of roots managed by this `DOMLocalization`.\n *\n * Additionally, if this `DOMLocalization` has an observer, stop observing\n * `root`.\n *\n * Returns `true` if the root was the last one managed by this\n * `DOMLocalization`.\n *\n * @param {Element} root - Root to disconnect.\n * @returns {boolean}\n */\n disconnectRoot(root) {\n this.roots.delete(root);\n // Pause the mutation observer to stop observing `root`.\n this.pauseObserving();\n if (this.roots.size === 0) {\n this.mutationObserver = null;\n if (this.windowElement && this.pendingrAF) {\n this.windowElement.cancelAnimationFrame(this.pendingrAF);\n }\n this.windowElement = null;\n this.pendingrAF = null;\n this.pendingElements.clear();\n return true;\n }\n // Resume observing all other roots.\n this.resumeObserving();\n return false;\n }\n /**\n * Translate all roots associated with this `DOMLocalization`.\n *\n * @returns {Promise}\n */\n translateRoots() {\n const roots = Array.from(this.roots);\n return Promise.all(roots.map(root => this.translateFragment(root)));\n }\n /**\n * Pauses the `MutationObserver`.\n */\n pauseObserving() {\n if (!this.mutationObserver) {\n return;\n }\n this.translateMutations(this.mutationObserver.takeRecords());\n this.mutationObserver.disconnect();\n }\n /**\n * Resumes the `MutationObserver`.\n */\n resumeObserving() {\n if (!this.mutationObserver) {\n return;\n }\n for (const root of this.roots) {\n this.mutationObserver.observe(root, this.observerConfig);\n }\n }\n /**\n * Translate mutations detected by the `MutationObserver`.\n *\n * @private\n */\n translateMutations(mutations) {\n for (const mutation of mutations) {\n switch (mutation.type) {\n case \"attributes\":\n if (mutation.target.hasAttribute(\"data-l10n-id\")) {\n this.pendingElements.add(mutation.target);\n }\n break;\n case \"childList\":\n for (const addedNode of mutation.addedNodes) {\n if (addedNode.nodeType === addedNode.ELEMENT_NODE) {\n if (addedNode.childElementCount) {\n for (const element of this.getTranslatables(addedNode)) {\n this.pendingElements.add(element);\n }\n }\n else if (addedNode.hasAttribute(L10NID_ATTR_NAME)) {\n this.pendingElements.add(addedNode);\n }\n }\n }\n break;\n }\n }\n // This fragment allows us to coalesce all pending translations\n // into a single requestAnimationFrame.\n if (this.pendingElements.size > 0) {\n if (this.pendingrAF === null) {\n this.pendingrAF = this.windowElement.requestAnimationFrame(() => {\n this.translateElements(Array.from(this.pendingElements));\n this.pendingElements.clear();\n this.pendingrAF = null;\n });\n }\n }\n }\n /**\n * Translate a DOM element or fragment asynchronously using this\n * `DOMLocalization` object.\n *\n * Manually trigger the translation (or re-translation) of a DOM fragment.\n * Use the `data-l10n-id` and `data-l10n-args` attributes to mark up the DOM\n * with information about which translations to use.\n *\n * Returns a `Promise` that gets resolved once the translation is complete.\n *\n * @param {DOMFragment} frag - Element or DocumentFragment to be translated\n * @returns {Promise}\n */\n translateFragment(frag) {\n return this.translateElements(this.getTranslatables(frag));\n }\n /**\n * Translate a list of DOM elements asynchronously using this\n * `DOMLocalization` object.\n *\n * Manually trigger the translation (or re-translation) of a list of elements.\n * Use the `data-l10n-id` and `data-l10n-args` attributes to mark up the DOM\n * with information about which translations to use.\n *\n * Returns a `Promise` that gets resolved once the translation is complete.\n *\n * @param {Array} elements - List of elements to be translated\n * @returns {Promise}\n */\n async translateElements(elements) {\n if (!elements.length) {\n return undefined;\n }\n const keys = elements.map(this.getKeysForElement);\n const translations = await this.formatMessages(keys);\n return this.applyTranslations(elements, translations);\n }\n /**\n * Applies translations onto elements.\n *\n * @param {Array} elements\n * @param {Array} translations\n * @private\n */\n applyTranslations(elements, translations) {\n this.pauseObserving();\n for (let i = 0; i < elements.length; i++) {\n if (translations[i] !== undefined) {\n translateElement(elements[i], translations[i]);\n }\n }\n this.resumeObserving();\n }\n /**\n * Collects all translatable child elements of the element.\n *\n * @param {Element} element\n * @returns {Array}\n * @private\n */\n getTranslatables(element) {\n const nodes = Array.from(element.querySelectorAll(L10N_ELEMENT_QUERY));\n if (typeof element.hasAttribute === \"function\" &&\n element.hasAttribute(L10NID_ATTR_NAME)) {\n nodes.push(element);\n }\n return nodes;\n }\n /**\n * Get the `data-l10n-*` attributes from DOM elements as a two-element\n * array.\n *\n * @param {Element} element\n * @returns {Object}\n * @private\n */\n getKeysForElement(element) {\n return {\n id: element.getAttribute(L10NID_ATTR_NAME),\n args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null),\n };\n }\n}\n","export { default as DOMLocalization } from \"./dom_localization.js\";\nexport { default as Localization } from \"./localization.js\";\n","/* Copyright 2023 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./interfaces\").IL10n} IL10n */\n\n/**\n * NOTE: The L10n-implementations should use lowercase language-codes\n * internally.\n * @implements {IL10n}\n */\nclass L10n {\n #dir;\n\n #elements;\n\n #lang;\n\n #l10n;\n\n constructor({ lang, isRTL }, l10n = null) {\n this.#lang = L10n.#fixupLangCode(lang);\n this.#l10n = l10n;\n this.#dir = (isRTL ?? L10n.#isRTL(this.#lang)) ? \"rtl\" : \"ltr\";\n }\n\n _setL10n(l10n) {\n this.#l10n = l10n;\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"TESTING\")) {\n document.l10n = l10n;\n }\n }\n\n /** @inheritdoc */\n getLanguage() {\n return this.#lang;\n }\n\n /** @inheritdoc */\n getDirection() {\n return this.#dir;\n }\n\n /** @inheritdoc */\n async get(ids, args = null, fallback) {\n if (Array.isArray(ids)) {\n ids = ids.map(id => ({ id }));\n const messages = await this.#l10n.formatMessages(ids);\n return messages.map(message => message.value);\n }\n\n const messages = await this.#l10n.formatMessages([\n {\n id: ids,\n args,\n },\n ]);\n return messages[0]?.value || fallback;\n }\n\n /** @inheritdoc */\n async translate(element) {\n (this.#elements ||= new Set()).add(element);\n try {\n this.#l10n.connectRoot(element);\n await this.#l10n.translateRoots();\n } catch {\n // Element is under an existing root, so there is no need to add it again.\n }\n }\n\n /** @inheritdoc */\n async translateOnce(element) {\n try {\n await this.#l10n.translateElements([element]);\n } catch (ex) {\n console.error(`translateOnce: \"${ex}\".`);\n }\n }\n\n /** @inheritdoc */\n async destroy() {\n if (this.#elements) {\n for (const element of this.#elements) {\n this.#l10n.disconnectRoot(element);\n }\n this.#elements.clear();\n this.#elements = null;\n }\n this.#l10n.pauseObserving();\n }\n\n /** @inheritdoc */\n pause() {\n this.#l10n.pauseObserving();\n }\n\n /** @inheritdoc */\n resume() {\n this.#l10n.resumeObserving();\n }\n\n static #fixupLangCode(langCode) {\n // Use only lowercase language-codes internally, and fallback to English.\n langCode = langCode?.toLowerCase() || \"en-us\";\n\n // Try to support \"incompletely\" specified language codes (see issue 13689).\n const PARTIAL_LANG_CODES = {\n en: \"en-us\",\n es: \"es-es\",\n fy: \"fy-nl\",\n ga: \"ga-ie\",\n gu: \"gu-in\",\n hi: \"hi-in\",\n hy: \"hy-am\",\n nb: \"nb-no\",\n ne: \"ne-np\",\n nn: \"nn-no\",\n pa: \"pa-in\",\n pt: \"pt-pt\",\n sv: \"sv-se\",\n zh: \"zh-cn\",\n };\n return PARTIAL_LANG_CODES[langCode] || langCode;\n }\n\n static #isRTL(lang) {\n const shortCode = lang.split(\"-\", 1)[0];\n return [\"ar\", \"he\", \"fa\", \"ps\", \"ur\"].includes(shortCode);\n }\n}\n\nconst GenericL10n = null;\n\nexport { GenericL10n, L10n };\n","/* Copyright 2017 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./interfaces\").IL10n} IL10n */\n\nimport { FluentBundle, FluentResource } from \"fluent-bundle\";\nimport { DOMLocalization } from \"fluent-dom\";\nimport { fetchData } from \"pdfjs-lib\";\nimport { L10n } from \"./l10n.js\";\n\nfunction createBundle(lang, text) {\n const resource = new FluentResource(text);\n const bundle = new FluentBundle(lang);\n const errors = bundle.addResource(resource);\n if (errors.length) {\n console.error(\"L10n errors\", errors);\n }\n return bundle;\n}\n\n/**\n * @implements {IL10n}\n */\nclass GenericL10n extends L10n {\n constructor(lang) {\n super({ lang });\n\n const generateBundles = !lang\n ? GenericL10n.#generateBundlesFallback.bind(\n GenericL10n,\n this.getLanguage()\n )\n : GenericL10n.#generateBundles.bind(\n GenericL10n,\n \"en-us\",\n this.getLanguage()\n );\n this._setL10n(new DOMLocalization([], generateBundles));\n }\n\n /**\n * Generate the bundles for Fluent.\n * @param {String} defaultLang - The fallback language to use for\n * translations.\n * @param {String} baseLang - The base language to use for translations.\n */\n static async *#generateBundles(defaultLang, baseLang) {\n const { baseURL, paths } = await this.#getPaths();\n\n const langs = [baseLang];\n if (defaultLang !== baseLang) {\n // Also fallback to the short-format of the base language\n // (see issue 17269).\n const shortLang = baseLang.split(\"-\", 1)[0];\n\n if (shortLang !== baseLang) {\n langs.push(shortLang);\n }\n langs.push(defaultLang);\n }\n for (const lang of langs) {\n const bundle = await this.#createBundle(lang, baseURL, paths);\n if (bundle) {\n yield bundle;\n } else if (lang === \"en-us\") {\n yield this.#createBundleFallback(lang);\n }\n }\n }\n\n static async #createBundle(lang, baseURL, paths) {\n const path = paths[lang];\n if (!path) {\n return null;\n }\n const url = new URL(path, baseURL);\n const text = await fetchData(url, /* type = */ \"text\");\n\n return createBundle(lang, text);\n }\n\n static async #getPaths() {\n try {\n const { href } = document.querySelector(`link[type=\"application/l10n\"]`);\n const paths = await fetchData(href, /* type = */ \"json\");\n\n return { baseURL: href.replace(/[^/]*$/, \"\") || \"./\", paths };\n } catch {}\n return { baseURL: \"./\", paths: Object.create(null) };\n }\n\n static async *#generateBundlesFallback(lang) {\n yield this.#createBundleFallback(lang);\n }\n\n static async #createBundleFallback(lang) {\n if (typeof PDFJSDev !== \"undefined\" && PDFJSDev.test(\"TESTING\")) {\n throw new Error(\"Not implemented: #createBundleFallback\");\n }\n const text =\n typeof PDFJSDev === \"undefined\"\n ? await fetchData(\n new URL(\"../l10n/en-US/viewer.ftl\", window.location.href),\n /* type = */ \"text\"\n )\n : PDFJSDev.eval(\"DEFAULT_FTL\");\n\n return createBundle(lang, text);\n }\n}\n\nexport { GenericL10n };\n","/* Copyright 2020 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getPdfFilenameFromUrl } from \"pdfjs-lib\";\n\nasync function docProperties(pdfDocument) {\n const url = \"\",\n baseUrl = url.split(\"#\", 1)[0];\n // eslint-disable-next-line prefer-const\n let { info, metadata, contentDispositionFilename, contentLength } =\n await pdfDocument.getMetadata();\n\n if (!contentLength) {\n const { length } = await pdfDocument.getDownloadInfo();\n contentLength = length;\n }\n\n return {\n ...info,\n baseURL: baseUrl,\n filesize: contentLength,\n filename: contentDispositionFilename || getPdfFilenameFromUrl(url),\n metadata: metadata?.getRaw(),\n authors: metadata?.get(\"dc:creator\"),\n numPages: pdfDocument.numPages,\n URL: url,\n };\n}\n\nclass GenericScripting {\n constructor(sandboxBundleSrc) {\n this._ready = new Promise((resolve, reject) => {\n const sandbox =\n typeof PDFJSDev === \"undefined\"\n ? import(sandboxBundleSrc) // eslint-disable-line no-unsanitized/method\n : __non_webpack_import__(sandboxBundleSrc);\n sandbox\n .then(pdfjsSandbox => {\n resolve(pdfjsSandbox.QuickJSSandbox());\n })\n .catch(reject);\n });\n }\n\n async createSandbox(data) {\n const sandbox = await this._ready;\n sandbox.create(data);\n }\n\n async dispatchEventInSandbox(event) {\n const sandbox = await this._ready;\n setTimeout(() => sandbox.dispatchEvent(event), 0);\n }\n\n async destroySandbox() {\n const sandbox = await this._ready;\n sandbox.nukeSandbox();\n }\n}\n\nexport { docProperties, GenericScripting };\n","/* Copyright 2017 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AppOptions } from \"./app_options.js\";\nimport { BaseExternalServices } from \"./external_services.js\";\nimport { BasePreferences } from \"./preferences.js\";\nimport { GenericL10n } from \"./genericl10n.js\";\nimport { GenericScripting } from \"./generic_scripting.js\";\n\nif (typeof PDFJSDev !== \"undefined\" && !PDFJSDev.test(\"GENERIC\")) {\n throw new Error(\n 'Module \"pdfjs-web/genericcom\" shall not be used outside GENERIC build.'\n );\n}\n\nfunction initCom(app) {}\n\nclass Preferences extends BasePreferences {\n async _writeToStorage(prefObj) {\n localStorage.setItem(\"pdfjs.preferences\", JSON.stringify(prefObj));\n }\n\n async _readFromStorage(prefObj) {\n return { prefs: JSON.parse(localStorage.getItem(\"pdfjs.preferences\")) };\n }\n}\n\nclass ExternalServices extends BaseExternalServices {\n async createL10n() {\n return new GenericL10n(AppOptions.get(\"localeProperties\")?.lang);\n }\n\n createScripting() {\n return new GenericScripting(AppOptions.get(\"sandboxBundleSrc\"));\n }\n}\n\nclass MLManager {\n async isEnabledFor(_name) {\n return false;\n }\n\n async deleteModel(_service) {\n return null;\n }\n\n isReady(_name) {\n return false;\n }\n\n guess(_data) {}\n\n toggleService(_name, _enabled) {}\n\n static getFakeMLManager(options) {\n return new FakeMLManager(options);\n }\n}\n\nclass FakeMLManager {\n eventBus = null;\n\n hasProgress = false;\n\n constructor({ enableGuessAltText, enableAltTextModelDownload }) {\n this.enableGuessAltText = enableGuessAltText;\n this.enableAltTextModelDownload = enableAltTextModelDownload;\n }\n\n setEventBus(eventBus, abortSignal) {\n this.eventBus = eventBus;\n }\n\n async isEnabledFor(_name) {\n return this.enableGuessAltText;\n }\n\n async deleteModel(_name) {\n this.enableAltTextModelDownload = false;\n return null;\n }\n\n async loadModel(_name) {}\n\n async downloadModel(_name) {\n // Simulate downloading the model but with progress.\n // The progress can be seen in the new alt-text dialog.\n this.hasProgress = true;\n\n const { promise, resolve } = Promise.withResolvers();\n const total = 1e8;\n const end = 1.5 * total;\n const increment = 5e6;\n let loaded = 0;\n const id = setInterval(() => {\n loaded += increment;\n if (loaded <= end) {\n this.eventBus.dispatch(\"loadaiengineprogress\", {\n source: this,\n detail: {\n total,\n totalLoaded: loaded,\n finished: loaded + increment >= end,\n },\n });\n return;\n }\n clearInterval(id);\n this.hasProgress = false;\n this.enableAltTextModelDownload = true;\n resolve(true);\n }, 900);\n return promise;\n }\n\n isReady(_name) {\n return this.enableAltTextModelDownload;\n }\n\n guess({ request: { data } }) {\n return new Promise(resolve => {\n setTimeout(() => {\n resolve(data ? { output: \"Fake alt text.\" } : { error: true });\n }, 3000);\n });\n }\n\n toggleService(_name, enabled) {\n this.enableGuessAltText = enabled;\n }\n}\n\nexport { ExternalServices, initCom, MLManager, Preferences };\n","/* Copyright 2024 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { noContextMenu } from \"pdfjs-lib\";\n\nclass NewAltTextManager {\n #boundCancel = this.#cancel.bind(this);\n\n #createAutomaticallyButton;\n\n #currentEditor = null;\n\n #cancelButton;\n\n #descriptionContainer;\n\n #dialog;\n\n #disclaimer;\n\n #downloadModel;\n\n #downloadModelDescription;\n\n #eventBus;\n\n #firstTime = false;\n\n #guessedAltText;\n\n #hasAI = null;\n\n #isEditing = null;\n\n #imagePreview;\n\n #imageData;\n\n #isAILoading = false;\n\n #wasAILoading = false;\n\n #learnMore;\n\n #notNowButton;\n\n #overlayManager;\n\n #textarea;\n\n #title;\n\n #uiManager;\n\n #previousAltText = null;\n\n constructor(\n {\n descriptionContainer,\n dialog,\n imagePreview,\n cancelButton,\n disclaimer,\n notNowButton,\n saveButton,\n textarea,\n learnMore,\n errorCloseButton,\n createAutomaticallyButton,\n downloadModel,\n downloadModelDescription,\n title,\n },\n overlayManager,\n eventBus\n ) {\n this.#cancelButton = cancelButton;\n this.#createAutomaticallyButton = createAutomaticallyButton;\n this.#descriptionContainer = descriptionContainer;\n this.#dialog = dialog;\n this.#disclaimer = disclaimer;\n this.#notNowButton = notNowButton;\n this.#imagePreview = imagePreview;\n this.#textarea = textarea;\n this.#learnMore = learnMore;\n this.#title = title;\n this.#downloadModel = downloadModel;\n this.#downloadModelDescription = downloadModelDescription;\n this.#overlayManager = overlayManager;\n this.#eventBus = eventBus;\n\n dialog.addEventListener(\"close\", this.#close.bind(this));\n dialog.addEventListener(\"contextmenu\", event => {\n if (event.target !== this.#textarea) {\n event.preventDefault();\n }\n });\n cancelButton.addEventListener(\"click\", this.#boundCancel);\n notNowButton.addEventListener(\"click\", this.#boundCancel);\n saveButton.addEventListener(\"click\", this.#save.bind(this));\n errorCloseButton.addEventListener(\"click\", () => {\n this.#toggleError(false);\n });\n createAutomaticallyButton.addEventListener(\"click\", async () => {\n const checked =\n createAutomaticallyButton.getAttribute(\"aria-pressed\") !== \"true\";\n this.#currentEditor._reportTelemetry({\n action: \"pdfjs.image.alt_text.ai_generation_check\",\n data: { status: checked },\n });\n\n if (this.#uiManager) {\n this.#uiManager.setPreference(\"enableGuessAltText\", checked);\n await this.#uiManager.mlManager.toggleService(\"altText\", checked);\n }\n this.#toggleGuessAltText(checked, /* isInitial = */ false);\n });\n textarea.addEventListener(\"focus\", () => {\n this.#wasAILoading = this.#isAILoading;\n this.#toggleLoading(false);\n this.#toggleTitleAndDisclaimer();\n });\n textarea.addEventListener(\"blur\", () => {\n if (!textarea.value) {\n this.#toggleLoading(this.#wasAILoading);\n }\n this.#toggleTitleAndDisclaimer();\n });\n textarea.addEventListener(\"input\", () => {\n this.#toggleTitleAndDisclaimer();\n });\n\n eventBus._on(\"enableguessalttext\", ({ value }) => {\n this.#toggleGuessAltText(value, /* isInitial = */ false);\n });\n\n this.#overlayManager.register(dialog);\n\n this.#learnMore.addEventListener(\"click\", () => {\n this.#currentEditor._reportTelemetry({\n action: \"pdfjs.image.alt_text.info\",\n data: { topic: \"alt_text\" },\n });\n });\n }\n\n #toggleLoading(value) {\n if (!this.#uiManager || this.#isAILoading === value) {\n return;\n }\n this.#isAILoading = value;\n this.#descriptionContainer.classList.toggle(\"loading\", value);\n }\n\n #toggleError(value) {\n if (!this.#uiManager) {\n return;\n }\n this.#dialog.classList.toggle(\"error\", value);\n }\n\n async #toggleGuessAltText(value, isInitial = false) {\n if (!this.#uiManager) {\n return;\n }\n this.#dialog.classList.toggle(\"aiDisabled\", !value);\n this.#createAutomaticallyButton.setAttribute(\"aria-pressed\", value);\n\n if (value) {\n const { altTextLearnMoreUrl } = this.#uiManager.mlManager;\n if (altTextLearnMoreUrl) {\n this.#learnMore.href = altTextLearnMoreUrl;\n }\n this.#mlGuessAltText(isInitial);\n } else {\n this.#toggleLoading(false);\n this.#isAILoading = false;\n this.#toggleTitleAndDisclaimer();\n }\n }\n\n #toggleNotNow() {\n this.#notNowButton.classList.toggle(\"hidden\", !this.#firstTime);\n this.#cancelButton.classList.toggle(\"hidden\", this.#firstTime);\n }\n\n #toggleAI(value) {\n if (!this.#uiManager || this.#hasAI === value) {\n return;\n }\n this.#hasAI = value;\n this.#dialog.classList.toggle(\"noAi\", !value);\n this.#toggleTitleAndDisclaimer();\n }\n\n #toggleTitleAndDisclaimer() {\n // Disclaimer is visible when the AI is loading or the user didn't change\n // the guessed alt text.\n const visible =\n this.#isAILoading ||\n (this.#guessedAltText && this.#guessedAltText === this.#textarea.value);\n this.#disclaimer.hidden = !visible;\n\n // The title changes depending if the text area is empty or not.\n const isEditing = this.#isAILoading || !!this.#textarea.value;\n if (this.#isEditing === isEditing) {\n return;\n }\n this.#isEditing = isEditing;\n this.#title.setAttribute(\n \"data-l10n-id\",\n isEditing\n ? \"pdfjs-editor-new-alt-text-dialog-edit-label\"\n : \"pdfjs-editor-new-alt-text-dialog-add-label\"\n );\n }\n\n async #mlGuessAltText(isInitial) {\n if (this.#isAILoading) {\n // We're still loading the previous guess.\n return;\n }\n\n if (this.#textarea.value) {\n // The user has already set an alt text.\n return;\n }\n\n if (isInitial && this.#previousAltText !== null) {\n // The user has already set an alt text (empty or not).\n return;\n }\n\n this.#guessedAltText = this.#currentEditor.guessedAltText;\n if (this.#previousAltText === null && this.#guessedAltText) {\n // We have a guessed alt text and the user didn't change it.\n this.#addAltText(this.#guessedAltText);\n return;\n }\n\n this.#toggleLoading(true);\n this.#toggleTitleAndDisclaimer();\n\n let hasError = false;\n try {\n // When calling #mlGuessAltText we don't wait for it, so we must take care\n // that the alt text dialog can have been closed before the response is.\n\n const altText = await this.#currentEditor.mlGuessAltText(\n this.#imageData,\n /* updateAltTextData = */ false\n );\n if (altText) {\n this.#guessedAltText = altText;\n this.#wasAILoading = this.#isAILoading;\n if (this.#isAILoading) {\n this.#addAltText(altText);\n }\n }\n } catch (e) {\n console.error(e);\n hasError = true;\n }\n\n this.#toggleLoading(false);\n this.#toggleTitleAndDisclaimer();\n\n if (hasError && this.#uiManager) {\n this.#toggleError(true);\n }\n }\n\n #addAltText(altText) {\n if (!this.#uiManager || this.#textarea.value) {\n return;\n }\n this.#textarea.value = altText;\n this.#toggleTitleAndDisclaimer();\n }\n\n #setProgress() {\n // Show the download model progress.\n this.#downloadModel.classList.toggle(\"hidden\", false);\n\n const callback = async ({ detail: { finished, total, totalLoaded } }) => {\n const ONE_MEGA_BYTES = 1e6;\n // totalLoaded can be greater than total if the download is compressed.\n // So we cheat to avoid any confusion.\n totalLoaded = Math.min(0.99 * total, totalLoaded);\n\n // Update the progress.\n const totalSize = (this.#downloadModelDescription.ariaValueMax =\n Math.round(total / ONE_MEGA_BYTES));\n const downloadedSize = (this.#downloadModelDescription.ariaValueNow =\n Math.round(totalLoaded / ONE_MEGA_BYTES));\n this.#downloadModelDescription.setAttribute(\n \"data-l10n-args\",\n JSON.stringify({ totalSize, downloadedSize })\n );\n if (!finished) {\n return;\n }\n\n // We're done, remove the listener and hide the download model progress.\n this.#eventBus._off(\"loadaiengineprogress\", callback);\n this.#downloadModel.classList.toggle(\"hidden\", true);\n\n this.#toggleAI(true);\n if (!this.#uiManager) {\n return;\n }\n const { mlManager } = this.#uiManager;\n\n // The model has been downloaded, we can now enable the AI service.\n mlManager.toggleService(\"altText\", true);\n this.#toggleGuessAltText(\n await mlManager.isEnabledFor(\"altText\"),\n /* isInitial = */ true\n );\n };\n this.#eventBus._on(\"loadaiengineprogress\", callback);\n }\n\n async editAltText(uiManager, editor, firstTime) {\n if (this.#currentEditor || !editor) {\n return;\n }\n\n if (firstTime && editor.hasAltTextData()) {\n editor.altTextFinish();\n return;\n }\n\n this.#firstTime = firstTime;\n let { mlManager } = uiManager;\n let hasAI = !!mlManager;\n this.#toggleTitleAndDisclaimer();\n\n if (mlManager && !mlManager.isReady(\"altText\")) {\n hasAI = false;\n if (mlManager.hasProgress) {\n this.#setProgress();\n } else {\n mlManager = null;\n }\n } else {\n this.#downloadModel.classList.toggle(\"hidden\", true);\n }\n\n const isAltTextEnabledPromise = mlManager?.isEnabledFor(\"altText\");\n\n this.#currentEditor = editor;\n this.#uiManager = uiManager;\n this.#uiManager.removeEditListeners();\n\n ({ altText: this.#previousAltText } = editor.altTextData);\n this.#textarea.value = this.#previousAltText ?? \"\";\n\n // TODO: get this value from Firefox\n // (https://bugzilla.mozilla.org/show_bug.cgi?id=1908184)\n const AI_MAX_IMAGE_DIMENSION = 224;\n const MAX_PREVIEW_DIMENSION = 180;\n\n // The max dimension of the preview in the dialog is 180px, so we keep 224px\n // and rescale it thanks to css.\n\n let canvas, width, height;\n if (mlManager) {\n ({\n canvas,\n width,\n height,\n imageData: this.#imageData,\n } = editor.copyCanvas(\n AI_MAX_IMAGE_DIMENSION,\n MAX_PREVIEW_DIMENSION,\n /* createImageData = */ true\n ));\n if (hasAI) {\n this.#toggleGuessAltText(\n await isAltTextEnabledPromise,\n /* isInitial = */ true\n );\n }\n } else {\n ({ canvas, width, height } = editor.copyCanvas(\n AI_MAX_IMAGE_DIMENSION,\n MAX_PREVIEW_DIMENSION,\n /* createImageData = */ false\n ));\n }\n\n canvas.setAttribute(\"role\", \"presentation\");\n const { style } = canvas;\n style.width = `${width}px`;\n style.height = `${height}px`;\n this.#imagePreview.append(canvas);\n\n this.#toggleNotNow();\n this.#toggleAI(hasAI);\n this.#toggleError(false);\n\n try {\n await this.#overlayManager.open(this.#dialog);\n } catch (ex) {\n this.#close();\n throw ex;\n }\n }\n\n #cancel() {\n this.#currentEditor.altTextData = {\n cancel: true,\n };\n const altText = this.#textarea.value.trim();\n this.#currentEditor._reportTelemetry({\n action: \"pdfjs.image.alt_text.dismiss\",\n data: {\n alt_text_type: altText ? \"present\" : \"empty\",\n flow: this.#firstTime ? \"image_add\" : \"alt_text_edit\",\n },\n });\n this.#currentEditor._reportTelemetry({\n action: \"pdfjs.image.image_added\",\n data: { alt_text_modal: true, alt_text_type: \"skipped\" },\n });\n this.#finish();\n }\n\n #finish() {\n if (this.#overlayManager.active === this.#dialog) {\n this.#overlayManager.close(this.#dialog);\n }\n }\n\n #close() {\n const canvas = this.#imagePreview.firstChild;\n canvas.remove();\n canvas.width = canvas.height = 0;\n this.#imageData = null;\n\n this.#toggleLoading(false);\n\n this.#uiManager?.addEditListeners();\n this.#currentEditor.altTextFinish();\n this.#uiManager?.setSelected(this.#currentEditor);\n this.#currentEditor = null;\n this.#uiManager = null;\n }\n\n #extractWords(text) {\n return new Set(\n text\n .toLowerCase()\n .split(/[^\\p{L}\\p{N}]+/gu)\n .filter(x => !!x)\n );\n }\n\n #save() {\n const altText = this.#textarea.value.trim();\n this.#currentEditor.altTextData = {\n altText,\n decorative: false,\n };\n this.#currentEditor.altTextData.guessedAltText = this.#guessedAltText;\n\n if (this.#guessedAltText && this.#guessedAltText !== altText) {\n const guessedWords = this.#extractWords(this.#guessedAltText);\n const words = this.#extractWords(altText);\n this.#currentEditor._reportTelemetry({\n action: \"pdfjs.image.alt_text.user_edit\",\n data: {\n total_words: guessedWords.size,\n words_removed: guessedWords.difference(words).size,\n words_added: words.difference(guessedWords).size,\n },\n });\n }\n this.#currentEditor._reportTelemetry({\n action: \"pdfjs.image.image_added\",\n data: {\n alt_text_modal: true,\n alt_text_type: altText ? \"present\" : \"empty\",\n },\n });\n\n this.#currentEditor._reportTelemetry({\n action: \"pdfjs.image.alt_text.save\",\n data: {\n alt_text_type: altText ? \"present\" : \"empty\",\n flow: this.#firstTime ? \"image_add\" : \"alt_text_edit\",\n },\n });\n\n this.#finish();\n }\n\n destroy() {\n this.#uiManager = null; // Avoid re-adding the edit listeners.\n this.#finish();\n }\n}\n\nclass ImageAltTextSettings {\n #aiModelSettings;\n\n #createModelButton;\n\n #downloadModelButton;\n\n #dialog;\n\n #eventBus;\n\n #mlManager;\n\n #overlayManager;\n\n #showAltTextDialogButton;\n\n constructor(\n {\n dialog,\n createModelButton,\n aiModelSettings,\n learnMore,\n closeButton,\n deleteModelButton,\n downloadModelButton,\n showAltTextDialogButton,\n },\n overlayManager,\n eventBus,\n mlManager\n ) {\n this.#dialog = dialog;\n this.#aiModelSettings = aiModelSettings;\n this.#createModelButton = createModelButton;\n this.#downloadModelButton = downloadModelButton;\n this.#showAltTextDialogButton = showAltTextDialogButton;\n this.#overlayManager = overlayManager;\n this.#eventBus = eventBus;\n this.#mlManager = mlManager;\n\n const { altTextLearnMoreUrl } = mlManager;\n if (altTextLearnMoreUrl) {\n learnMore.href = altTextLearnMoreUrl;\n }\n\n dialog.addEventListener(\"contextmenu\", noContextMenu);\n\n createModelButton.addEventListener(\"click\", async e => {\n const checked = this.#togglePref(\"enableGuessAltText\", e);\n await mlManager.toggleService(\"altText\", checked);\n this.#reportTelemetry({\n type: \"stamp\",\n action: \"pdfjs.image.alt_text.settings_ai_generation_check\",\n data: { status: checked },\n });\n });\n\n showAltTextDialogButton.addEventListener(\"click\", e => {\n const checked = this.#togglePref(\"enableNewAltTextWhenAddingImage\", e);\n this.#reportTelemetry({\n type: \"stamp\",\n action: \"pdfjs.image.alt_text.settings_edit_alt_text_check\",\n data: { status: checked },\n });\n });\n\n deleteModelButton.addEventListener(\"click\", this.#delete.bind(this, true));\n downloadModelButton.addEventListener(\n \"click\",\n this.#download.bind(this, true)\n );\n\n closeButton.addEventListener(\"click\", this.#finish.bind(this));\n\n learnMore.addEventListener(\"click\", () => {\n this.#reportTelemetry({\n type: \"stamp\",\n action: \"pdfjs.image.alt_text.info\",\n data: { topic: \"ai_generation\" },\n });\n });\n\n eventBus._on(\"enablealttextmodeldownload\", ({ value }) => {\n if (value) {\n this.#download(false);\n } else {\n this.#delete(false);\n }\n });\n\n this.#overlayManager.register(dialog);\n }\n\n #reportTelemetry(data) {\n this.#eventBus.dispatch(\"reporttelemetry\", {\n source: this,\n details: {\n type: \"editing\",\n data,\n },\n });\n }\n\n async #download(isFromUI = false) {\n if (isFromUI) {\n this.#downloadModelButton.disabled = true;\n const span = this.#downloadModelButton.firstChild;\n span.setAttribute(\n \"data-l10n-id\",\n \"pdfjs-editor-alt-text-settings-downloading-model-button\"\n );\n\n await this.#mlManager.downloadModel(\"altText\");\n\n span.setAttribute(\n \"data-l10n-id\",\n \"pdfjs-editor-alt-text-settings-download-model-button\"\n );\n\n this.#createModelButton.disabled = false;\n this.#setPref(\"enableGuessAltText\", true);\n this.#mlManager.toggleService(\"altText\", true);\n this.#setPref(\"enableAltTextModelDownload\", true);\n this.#downloadModelButton.disabled = false;\n }\n\n this.#aiModelSettings.classList.toggle(\"download\", false);\n this.#createModelButton.setAttribute(\"aria-pressed\", true);\n }\n\n async #delete(isFromUI = false) {\n if (isFromUI) {\n await this.#mlManager.deleteModel(\"altText\");\n this.#setPref(\"enableGuessAltText\", false);\n this.#setPref(\"enableAltTextModelDownload\", false);\n }\n\n this.#aiModelSettings.classList.toggle(\"download\", true);\n this.#createModelButton.disabled = true;\n this.#createModelButton.setAttribute(\"aria-pressed\", false);\n }\n\n async open({ enableGuessAltText, enableNewAltTextWhenAddingImage }) {\n const { enableAltTextModelDownload } = this.#mlManager;\n this.#createModelButton.disabled = !enableAltTextModelDownload;\n this.#createModelButton.setAttribute(\n \"aria-pressed\",\n enableAltTextModelDownload && enableGuessAltText\n );\n this.#showAltTextDialogButton.setAttribute(\n \"aria-pressed\",\n enableNewAltTextWhenAddingImage\n );\n this.#aiModelSettings.classList.toggle(\n \"download\",\n !enableAltTextModelDownload\n );\n\n await this.#overlayManager.open(this.#dialog);\n this.#reportTelemetry({\n type: \"stamp\",\n action: \"pdfjs.image.alt_text.settings_displayed\",\n });\n }\n\n #togglePref(name, { target }) {\n const checked = target.getAttribute(\"aria-pressed\") !== \"true\";\n this.#setPref(name, checked);\n target.setAttribute(\"aria-pressed\", checked);\n return checked;\n }\n\n #setPref(name, value) {\n this.#eventBus.dispatch(\"setpreference\", {\n source: this,\n name,\n value,\n });\n }\n\n #finish() {\n if (this.#overlayManager.active === this.#dialog) {\n this.#overlayManager.close(this.#dialog);\n }\n }\n}\n\nexport { ImageAltTextSettings, NewAltTextManager };\n","/* Copyright 2023 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DOMSVGFactory } from \"pdfjs-lib\";\n\nclass AltTextManager {\n #clickAC = null;\n\n #currentEditor = null;\n\n #cancelButton;\n\n #dialog;\n\n #eventBus;\n\n #hasUsedPointer = false;\n\n #optionDescription;\n\n #optionDecorative;\n\n #overlayManager;\n\n #saveButton;\n\n #textarea;\n\n #uiManager;\n\n #previousAltText = null;\n\n #resizeAC = null;\n\n #svgElement = null;\n\n #rectElement = null;\n\n #container;\n\n #telemetryData = null;\n\n constructor(\n {\n dialog,\n optionDescription,\n optionDecorative,\n textarea,\n cancelButton,\n saveButton,\n },\n container,\n overlayManager,\n eventBus\n ) {\n this.#dialog = dialog;\n this.#optionDescription = optionDescription;\n this.#optionDecorative = optionDecorative;\n this.#textarea = textarea;\n this.#cancelButton = cancelButton;\n this.#saveButton = saveButton;\n this.#overlayManager = overlayManager;\n this.#eventBus = eventBus;\n this.#container = container;\n\n const onUpdateUIState = this.#updateUIState.bind(this);\n\n dialog.addEventListener(\"close\", this.#close.bind(this));\n dialog.addEventListener(\"contextmenu\", event => {\n if (event.target !== this.#textarea) {\n event.preventDefault();\n }\n });\n cancelButton.addEventListener(\"click\", this.#finish.bind(this));\n saveButton.addEventListener(\"click\", this.#save.bind(this));\n optionDescription.addEventListener(\"change\", onUpdateUIState);\n optionDecorative.addEventListener(\"change\", onUpdateUIState);\n\n this.#overlayManager.register(dialog);\n }\n\n #createSVGElement() {\n if (this.#svgElement) {\n return;\n }\n\n // We create a mask to add to the dialog backdrop: the idea is to have a\n // darken background everywhere except on the editor to clearly see the\n // picture to describe.\n\n const svgFactory = new DOMSVGFactory();\n const svg = (this.#svgElement = svgFactory.createElement(\"svg\"));\n svg.setAttribute(\"width\", \"0\");\n svg.setAttribute(\"height\", \"0\");\n const defs = svgFactory.createElement(\"defs\");\n svg.append(defs);\n const mask = svgFactory.createElement(\"mask\");\n defs.append(mask);\n mask.setAttribute(\"id\", \"alttext-manager-mask\");\n mask.setAttribute(\"maskContentUnits\", \"objectBoundingBox\");\n let rect = svgFactory.createElement(\"rect\");\n mask.append(rect);\n rect.setAttribute(\"fill\", \"white\");\n rect.setAttribute(\"width\", \"1\");\n rect.setAttribute(\"height\", \"1\");\n rect.setAttribute(\"x\", \"0\");\n rect.setAttribute(\"y\", \"0\");\n\n rect = this.#rectElement = svgFactory.createElement(\"rect\");\n mask.append(rect);\n rect.setAttribute(\"fill\", \"black\");\n this.#dialog.append(svg);\n }\n\n async editAltText(uiManager, editor) {\n if (this.#currentEditor || !editor) {\n return;\n }\n this.#createSVGElement();\n\n this.#hasUsedPointer = false;\n\n this.#clickAC = new AbortController();\n const clickOpts = { signal: this.#clickAC.signal },\n onClick = this.#onClick.bind(this);\n for (const element of [\n this.#optionDescription,\n this.#optionDecorative,\n this.#textarea,\n this.#saveButton,\n this.#cancelButton,\n ]) {\n element.addEventListener(\"click\", onClick, clickOpts);\n }\n\n const { altText, decorative } = editor.altTextData;\n if (decorative === true) {\n this.#optionDecorative.checked = true;\n this.#optionDescription.checked = false;\n } else {\n this.#optionDecorative.checked = false;\n this.#optionDescription.checked = true;\n }\n this.#previousAltText = this.#textarea.value = altText?.trim() || \"\";\n this.#updateUIState();\n\n this.#currentEditor = editor;\n this.#uiManager = uiManager;\n this.#uiManager.removeEditListeners();\n\n this.#resizeAC = new AbortController();\n this.#eventBus._on(\"resize\", this.#setPosition.bind(this), {\n signal: this.#resizeAC.signal,\n });\n\n try {\n await this.#overlayManager.open(this.#dialog);\n this.#setPosition();\n } catch (ex) {\n this.#close();\n throw ex;\n }\n }\n\n #setPosition() {\n if (!this.#currentEditor) {\n return;\n }\n const dialog = this.#dialog;\n const { style } = dialog;\n const {\n x: containerX,\n y: containerY,\n width: containerW,\n height: containerH,\n } = this.#container.getBoundingClientRect();\n const { innerWidth: windowW, innerHeight: windowH } = window;\n const { width: dialogW, height: dialogH } = dialog.getBoundingClientRect();\n const { x, y, width, height } = this.#currentEditor.getClientDimensions();\n const MARGIN = 10;\n const isLTR = this.#uiManager.direction === \"ltr\";\n\n const xs = Math.max(x, containerX);\n const xe = Math.min(x + width, containerX + containerW);\n const ys = Math.max(y, containerY);\n const ye = Math.min(y + height, containerY + containerH);\n this.#rectElement.setAttribute(\"width\", `${(xe - xs) / windowW}`);\n this.#rectElement.setAttribute(\"height\", `${(ye - ys) / windowH}`);\n this.#rectElement.setAttribute(\"x\", `${xs / windowW}`);\n this.#rectElement.setAttribute(\"y\", `${ys / windowH}`);\n\n let left = null;\n let top = Math.max(y, 0);\n top += Math.min(windowH - (top + dialogH), 0);\n\n if (isLTR) {\n // Prefer to position the dialog \"after\" (so on the right) the editor.\n if (x + width + MARGIN + dialogW < windowW) {\n left = x + width + MARGIN;\n } else if (x > dialogW + MARGIN) {\n left = x - dialogW - MARGIN;\n }\n } else if (x > dialogW + MARGIN) {\n left = x - dialogW - MARGIN;\n } else if (x + width + MARGIN + dialogW < windowW) {\n left = x + width + MARGIN;\n }\n\n if (left === null) {\n top = null;\n left = Math.max(x, 0);\n left += Math.min(windowW - (left + dialogW), 0);\n if (y > dialogH + MARGIN) {\n top = y - dialogH - MARGIN;\n } else if (y + height + MARGIN + dialogH < windowH) {\n top = y + height + MARGIN;\n }\n }\n\n if (top !== null) {\n dialog.classList.add(\"positioned\");\n if (isLTR) {\n style.left = `${left}px`;\n } else {\n style.right = `${windowW - left - dialogW}px`;\n }\n style.top = `${top}px`;\n } else {\n dialog.classList.remove(\"positioned\");\n style.left = \"\";\n style.top = \"\";\n }\n }\n\n #finish() {\n if (this.#overlayManager.active === this.#dialog) {\n this.#overlayManager.close(this.#dialog);\n }\n }\n\n #close() {\n this.#currentEditor._reportTelemetry(\n this.#telemetryData || {\n action: \"alt_text_cancel\",\n alt_text_keyboard: !this.#hasUsedPointer,\n }\n );\n this.#telemetryData = null;\n\n this.#removeOnClickListeners();\n this.#uiManager?.addEditListeners();\n this.#resizeAC?.abort();\n this.#resizeAC = null;\n this.#currentEditor.altTextFinish();\n this.#currentEditor = null;\n this.#uiManager = null;\n }\n\n #updateUIState() {\n this.#textarea.disabled = this.#optionDecorative.checked;\n }\n\n #save() {\n const altText = this.#textarea.value.trim();\n const decorative = this.#optionDecorative.checked;\n this.#currentEditor.altTextData = {\n altText,\n decorative,\n };\n this.#telemetryData = {\n action: \"alt_text_save\",\n alt_text_description: !!altText,\n alt_text_edit:\n !!this.#previousAltText && this.#previousAltText !== altText,\n alt_text_decorative: decorative,\n alt_text_keyboard: !this.#hasUsedPointer,\n };\n this.#finish();\n }\n\n #onClick(evt) {\n if (evt.detail === 0) {\n return; // The keyboard was used.\n }\n this.#hasUsedPointer = true;\n this.#removeOnClickListeners();\n }\n\n #removeOnClickListeners() {\n this.#clickAC?.abort();\n this.#clickAC = null;\n }\n\n destroy() {\n this.#uiManager = null; // Avoid re-adding the edit listeners.\n this.#finish();\n this.#svgElement?.remove();\n this.#svgElement = this.#rectElement = null;\n }\n}\n\nexport { AltTextManager };\n","/* Copyright 2022 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./event_utils.js\").EventBus} EventBus */\n\nimport { AnnotationEditorParamsType } from \"pdfjs-lib\";\n\n/**\n * @typedef {Object} AnnotationEditorParamsOptions\n * @property {HTMLInputElement} editorFreeTextFontSize\n * @property {HTMLInputElement} editorFreeTextColor\n * @property {HTMLInputElement} editorInkColor\n * @property {HTMLInputElement} editorInkThickness\n * @property {HTMLInputElement} editorInkOpacity\n * @property {HTMLButtonElement} editorStampAddImage\n * @property {HTMLInputElement} editorFreeHighlightThickness\n * @property {HTMLButtonElement} editorHighlightShowAll\n */\n\nclass AnnotationEditorParams {\n /**\n * @param {AnnotationEditorParamsOptions} options\n * @param {EventBus} eventBus\n */\n constructor(options, eventBus) {\n this.eventBus = eventBus;\n this.#bindListeners(options);\n }\n\n /**\n * @param {AnnotationEditorParamsOptions} options\n */\n #bindListeners({\n editorFreeTextFontSize,\n editorFreeTextColor,\n editorInkColor,\n editorInkThickness,\n editorInkOpacity,\n editorStampAddImage,\n editorFreeHighlightThickness,\n editorHighlightShowAll,\n }) {\n const dispatchEvent = (typeStr, value) => {\n this.eventBus.dispatch(\"switchannotationeditorparams\", {\n source: this,\n type: AnnotationEditorParamsType[typeStr],\n value,\n });\n };\n editorFreeTextFontSize.addEventListener(\"input\", function () {\n dispatchEvent(\"FREETEXT_SIZE\", this.valueAsNumber);\n });\n editorFreeTextColor.addEventListener(\"input\", function () {\n dispatchEvent(\"FREETEXT_COLOR\", this.value);\n });\n editorInkColor.addEventListener(\"input\", function () {\n dispatchEvent(\"INK_COLOR\", this.value);\n });\n editorInkThickness.addEventListener(\"input\", function () {\n dispatchEvent(\"INK_THICKNESS\", this.valueAsNumber);\n });\n editorInkOpacity.addEventListener(\"input\", function () {\n dispatchEvent(\"INK_OPACITY\", this.valueAsNumber);\n });\n editorStampAddImage.addEventListener(\"click\", () => {\n this.eventBus.dispatch(\"reporttelemetry\", {\n source: this,\n details: {\n type: \"editing\",\n data: { action: \"pdfjs.image.add_image_click\" },\n },\n });\n dispatchEvent(\"CREATE\");\n });\n editorFreeHighlightThickness.addEventListener(\"input\", function () {\n dispatchEvent(\"HIGHLIGHT_THICKNESS\", this.valueAsNumber);\n });\n editorHighlightShowAll.addEventListener(\"click\", function () {\n const checked = this.getAttribute(\"aria-pressed\") === \"true\";\n this.setAttribute(\"aria-pressed\", !checked);\n dispatchEvent(\"HIGHLIGHT_SHOW_ALL\", !checked);\n });\n\n this.eventBus._on(\"annotationeditorparamschanged\", evt => {\n for (const [type, value] of evt.details) {\n switch (type) {\n case AnnotationEditorParamsType.FREETEXT_SIZE:\n editorFreeTextFontSize.value = value;\n break;\n case AnnotationEditorParamsType.FREETEXT_COLOR:\n editorFreeTextColor.value = value;\n break;\n case AnnotationEditorParamsType.INK_COLOR:\n editorInkColor.value = value;\n break;\n case AnnotationEditorParamsType.INK_THICKNESS:\n editorInkThickness.value = value;\n break;\n case AnnotationEditorParamsType.INK_OPACITY:\n editorInkOpacity.value = value;\n break;\n case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:\n editorFreeHighlightThickness.value = value;\n break;\n case AnnotationEditorParamsType.HIGHLIGHT_FREE:\n editorFreeHighlightThickness.disabled = !value;\n break;\n case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:\n editorHighlightShowAll.setAttribute(\"aria-pressed\", value);\n break;\n }\n }\n });\n }\n}\n\nexport { AnnotationEditorParams };\n","/* Copyright 2024 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Used to compare floats: there is no exact equality due to rounding errors.\nconst PRECISION = 1e-1;\n\nclass CaretBrowsingMode {\n #mainContainer;\n\n #toolBarHeight = 0;\n\n #viewerContainer;\n\n constructor(abortSignal, mainContainer, viewerContainer, toolbarContainer) {\n this.#mainContainer = mainContainer;\n this.#viewerContainer = viewerContainer;\n\n if (!toolbarContainer) {\n return;\n }\n this.#toolBarHeight = toolbarContainer.getBoundingClientRect().height;\n\n const toolbarObserver = new ResizeObserver(entries => {\n for (const entry of entries) {\n if (entry.target === toolbarContainer) {\n this.#toolBarHeight = Math.floor(entry.borderBoxSize[0].blockSize);\n break;\n }\n }\n });\n toolbarObserver.observe(toolbarContainer);\n\n abortSignal.addEventListener(\"abort\", () => toolbarObserver.disconnect(), {\n once: true,\n });\n }\n\n /**\n * Return true if the two rectangles are on the same line.\n * @param {DOMRect} rect1\n * @param {DOMRect} rect2\n * @returns {boolean}\n */\n #isOnSameLine(rect1, rect2) {\n const top1 = rect1.y;\n const bot1 = rect1.bottom;\n const mid1 = rect1.y + rect1.height / 2;\n\n const top2 = rect2.y;\n const bot2 = rect2.bottom;\n const mid2 = rect2.y + rect2.height / 2;\n\n return (top1 <= mid2 && mid2 <= bot1) || (top2 <= mid1 && mid1 <= bot2);\n }\n\n /**\n * Return `true` if the rectangle is:\n * - under the caret when `isUp === false`.\n * - over the caret when `isUp === true`.\n * @param {DOMRect} rect\n * @param {number} x\n * @param {number} y\n * @param {boolean} isUp\n * @returns {boolean}\n */\n #isUnderOver(rect, x, y, isUp) {\n const midY = rect.y + rect.height / 2;\n return (\n (isUp ? y >= midY : y <= midY) &&\n rect.x - PRECISION <= x &&\n x <= rect.right + PRECISION\n );\n }\n\n /**\n * Check if the rectangle is visible.\n * @param {DOMRect} rect\n * @returns {boolean}\n */\n #isVisible(rect) {\n return (\n rect.top >= this.#toolBarHeight &&\n rect.left >= 0 &&\n rect.bottom <=\n (window.innerHeight || document.documentElement.clientHeight) &&\n rect.right <= (window.innerWidth || document.documentElement.clientWidth)\n );\n }\n\n /**\n * Get the position of the caret.\n * @param {Selection} selection\n * @param {boolean} isUp\n * @returns {Array}\n */\n #getCaretPosition(selection, isUp) {\n const { focusNode, focusOffset } = selection;\n const range = document.createRange();\n range.setStart(focusNode, focusOffset);\n range.setEnd(focusNode, focusOffset);\n const rect = range.getBoundingClientRect();\n\n return [rect.x, isUp ? rect.top : rect.bottom];\n }\n\n static #caretPositionFromPoint(x, y) {\n if (\n (typeof PDFJSDev === \"undefined\" || !PDFJSDev.test(\"MOZCENTRAL\")) &&\n !document.caretPositionFromPoint\n ) {\n const { startContainer: offsetNode, startOffset: offset } =\n document.caretRangeFromPoint(x, y);\n return { offsetNode, offset };\n }\n return document.caretPositionFromPoint(x, y);\n }\n\n #setCaretPositionHelper(selection, caretX, select, element, rect) {\n rect ||= element.getBoundingClientRect();\n if (caretX <= rect.x + PRECISION) {\n if (select) {\n selection.extend(element.firstChild, 0);\n } else {\n selection.setPosition(element.firstChild, 0);\n }\n return;\n }\n if (rect.right - PRECISION <= caretX) {\n const { lastChild } = element;\n if (select) {\n selection.extend(lastChild, lastChild.length);\n } else {\n selection.setPosition(lastChild, lastChild.length);\n }\n return;\n }\n\n const midY = rect.y + rect.height / 2;\n let caretPosition = CaretBrowsingMode.#caretPositionFromPoint(caretX, midY);\n let parentElement = caretPosition.offsetNode?.parentElement;\n if (parentElement && parentElement !== element) {\n // There is an element on top of the one in the text layer, so we\n // need to hide all the elements (except the one in the text layer)\n // at this position in order to get the correct caret position.\n const elementsAtPoint = document.elementsFromPoint(caretX, midY);\n const savedVisibilities = [];\n for (const el of elementsAtPoint) {\n if (el === element) {\n break;\n }\n const { style } = el;\n savedVisibilities.push([el, style.visibility]);\n style.visibility = \"hidden\";\n }\n caretPosition = CaretBrowsingMode.#caretPositionFromPoint(caretX, midY);\n parentElement = caretPosition.offsetNode?.parentElement;\n for (const [el, visibility] of savedVisibilities) {\n el.style.visibility = visibility;\n }\n }\n if (parentElement !== element) {\n // The element targeted by caretPositionFromPoint isn't in the text\n // layer.\n if (select) {\n selection.extend(element.firstChild, 0);\n } else {\n selection.setPosition(element.firstChild, 0);\n }\n return;\n }\n if (select) {\n selection.extend(caretPosition.offsetNode, caretPosition.offset);\n } else {\n selection.setPosition(caretPosition.offsetNode, caretPosition.offset);\n }\n }\n\n /**\n * Set the caret position or extend the selection (it depends on the select\n * parameter).\n * @param {boolean} select\n * @param {Selection} selection\n * @param {Element} newLineElement\n * @param {DOMRect} newLineElementRect\n * @param {number} caretX\n */\n #setCaretPosition(\n select,\n selection,\n newLineElement,\n newLineElementRect,\n caretX\n ) {\n if (this.#isVisible(newLineElementRect)) {\n this.#setCaretPositionHelper(\n selection,\n caretX,\n select,\n newLineElement,\n newLineElementRect\n );\n return;\n }\n this.#mainContainer.addEventListener(\n \"scrollend\",\n this.#setCaretPositionHelper.bind(\n this,\n selection,\n caretX,\n select,\n newLineElement,\n null\n ),\n { once: true }\n );\n newLineElement.scrollIntoView();\n }\n\n /**\n * Get the node on the next page.\n * @param {Element} textLayer\n * @param {boolean} isUp\n * @returns {Node}\n */\n #getNodeOnNextPage(textLayer, isUp) {\n while (true) {\n const page = textLayer.closest(\".page\");\n const pageNumber = parseInt(page.getAttribute(\"data-page-number\"));\n const nextPage = isUp ? pageNumber - 1 : pageNumber + 1;\n textLayer = this.#viewerContainer.querySelector(\n `.page[data-page-number=\"${nextPage}\"] .textLayer`\n );\n if (!textLayer) {\n return null;\n }\n const walker = document.createTreeWalker(textLayer, NodeFilter.SHOW_TEXT);\n const node = isUp ? walker.lastChild() : walker.firstChild();\n if (node) {\n return node;\n }\n }\n }\n\n /**\n * Move the caret in the given direction.\n * @param {boolean} isUp\n * @param {boolean} select\n */\n moveCaret(isUp, select) {\n const selection = document.getSelection();\n if (selection.rangeCount === 0) {\n return;\n }\n const { focusNode } = selection;\n const focusElement =\n focusNode.nodeType !== Node.ELEMENT_NODE\n ? focusNode.parentElement\n : focusNode;\n const root = focusElement.closest(\".textLayer\");\n if (!root) {\n return;\n }\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);\n walker.currentNode = focusNode;\n\n // Move to the next element which is not on the same line as the focus\n // element.\n const focusRect = focusElement.getBoundingClientRect();\n let newLineElement = null;\n const nodeIterator = (\n isUp ? walker.previousSibling : walker.nextSibling\n ).bind(walker);\n while (nodeIterator()) {\n const element = walker.currentNode.parentElement;\n if (!this.#isOnSameLine(focusRect, element.getBoundingClientRect())) {\n newLineElement = element;\n break;\n }\n }\n\n if (!newLineElement) {\n // Need to find the next line on the next page.\n const node = this.#getNodeOnNextPage(root, isUp);\n if (!node) {\n return;\n }\n if (select) {\n const lastNode =\n (isUp ? walker.firstChild() : walker.lastChild()) || focusNode;\n selection.extend(lastNode, isUp ? 0 : lastNode.length);\n const range = document.createRange();\n range.setStart(node, isUp ? node.length : 0);\n range.setEnd(node, isUp ? node.length : 0);\n selection.addRange(range);\n return;\n }\n const [caretX] = this.#getCaretPosition(selection, isUp);\n const { parentElement } = node;\n this.#setCaretPosition(\n select,\n selection,\n parentElement,\n parentElement.getBoundingClientRect(),\n caretX\n );\n return;\n }\n\n // We've a candidate for the next line now we want to find the first element\n // which is under/over the caret.\n const [caretX, caretY] = this.#getCaretPosition(selection, isUp);\n const newLineElementRect = newLineElement.getBoundingClientRect();\n\n // Maybe the element on the new line is a valid candidate.\n if (this.#isUnderOver(newLineElementRect, caretX, caretY, isUp)) {\n this.#setCaretPosition(\n select,\n selection,\n newLineElement,\n newLineElementRect,\n caretX\n );\n return;\n }\n\n while (nodeIterator()) {\n // Search an element on the same line as newLineElement\n // which could be under/over the caret.\n const element = walker.currentNode.parentElement;\n const elementRect = element.getBoundingClientRect();\n if (!this.#isOnSameLine(newLineElementRect, elementRect)) {\n break;\n }\n if (this.#isUnderOver(elementRect, caretX, caretY, isUp)) {\n // We found the element.\n this.#setCaretPosition(select, selection, element, elementRect, caretX);\n return;\n }\n }\n\n // No element has been found so just put the caret on the element on the new\n // line.\n this.#setCaretPosition(\n select,\n selection,\n newLineElement,\n newLineElementRect,\n caretX\n );\n }\n}\n\nexport { CaretBrowsingMode };\n","/* Copyright 2013 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./interfaces\").IDownloadManager} IDownloadManager */\n\nimport { createValidAbsoluteUrl, isPdfFile } from \"pdfjs-lib\";\n\nif (typeof PDFJSDev !== \"undefined\" && !PDFJSDev.test(\"CHROME || GENERIC\")) {\n throw new Error(\n 'Module \"pdfjs-web/download_manager\" shall not be used ' +\n \"outside CHROME and GENERIC builds.\"\n );\n}\n\nfunction download(blobUrl, filename) {\n const a = document.createElement(\"a\");\n if (!a.click) {\n throw new Error('DownloadManager: \"a.click()\" is not supported.');\n }\n a.href = blobUrl;\n a.target = \"_parent\";\n // Use a.download if available. This increases the likelihood that\n // the file is downloaded instead of opened by another PDF plugin.\n if (\"download\" in a) {\n a.download = filename;\n }\n // must be in the document for recent Firefox versions,\n // otherwise .click() is ignored.\n (document.body || document.documentElement).append(a);\n a.click();\n a.remove();\n}\n\n/**\n * @implements {IDownloadManager}\n */\nclass DownloadManager {\n #openBlobUrls = new WeakMap();\n\n downloadData(data, filename, contentType) {\n const blobUrl = URL.createObjectURL(\n new Blob([data], { type: contentType })\n );\n download(blobUrl, filename);\n }\n\n /**\n * @returns {boolean} Indicating if the data was opened.\n */\n openOrDownloadData(data, filename, dest = null) {\n const isPdfData = isPdfFile(filename);\n const contentType = isPdfData ? \"application/pdf\" : \"\";\n\n if (\n (typeof PDFJSDev === \"undefined\" || !PDFJSDev.test(\"COMPONENTS\")) &&\n isPdfData\n ) {\n let blobUrl = this.#openBlobUrls.get(data);\n if (!blobUrl) {\n blobUrl = URL.createObjectURL(new Blob([data], { type: contentType }));\n this.#openBlobUrls.set(data, blobUrl);\n }\n let viewerUrl;\n if (typeof PDFJSDev === \"undefined\" || PDFJSDev.test(\"GENERIC\")) {\n // The current URL is the viewer, let's use it and append the file.\n viewerUrl = \"?file=\" + encodeURIComponent(blobUrl + \"#\" + filename);\n } else if (PDFJSDev.test(\"CHROME\")) {\n // In the Chrome extension, the URL is rewritten using the history API\n // in viewer.js, so an absolute URL must be generated.\n viewerUrl =\n // eslint-disable-next-line no-undef\n chrome.runtime.getURL(\"/content/web/viewer.html\") +\n \"?file=\" +\n encodeURIComponent(blobUrl + \"#\" + filename);\n }\n if (dest) {\n viewerUrl += `#${escape(dest)}`;\n }\n\n try {\n window.open(viewerUrl);\n return true;\n } catch (ex) {\n console.error(`openOrDownloadData: ${ex}`);\n // Release the `blobUrl`, since opening it failed, and fallback to\n // downloading the PDF file.\n URL.revokeObjectURL(blobUrl);\n this.#openBlobUrls.delete(data);\n }\n }\n\n this.downloadData(data, filename, contentType);\n return false;\n }\n\n download(data, url, filename) {\n let blobUrl;\n if (data) {\n blobUrl = URL.createObjectURL(\n new Blob([data], { type: \"application/pdf\" })\n );\n } else {\n if (!createValidAbsoluteUrl(url, \"http://example.com\")) {\n console.error(`download - not a valid URL: ${url}`);\n return;\n }\n blobUrl = url + \"#pdfjs.action=download\";\n }\n download(blobUrl, filename);\n }\n}\n\nexport { DownloadManager };\n","/* Copyright 2024 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { noContextMenu } from \"pdfjs-lib\";\n\nclass EditorUndoBar {\n #closeButton = null;\n\n #container;\n\n #eventBus = null;\n\n #focusTimeout = null;\n\n #initController = null;\n\n isOpen = false;\n\n #message;\n\n #showController = null;\n\n #undoButton;\n\n static #l10nMessages = Object.freeze({\n highlight: \"pdfjs-editor-undo-bar-message-highlight\",\n freetext: \"pdfjs-editor-undo-bar-message-freetext\",\n stamp: \"pdfjs-editor-undo-bar-message-stamp\",\n ink: \"pdfjs-editor-undo-bar-message-ink\",\n _multiple: \"pdfjs-editor-undo-bar-message-multiple\",\n });\n\n constructor({ container, message, undoButton, closeButton }, eventBus) {\n this.#container = container;\n this.#message = message;\n this.#undoButton = undoButton;\n this.#closeButton = closeButton;\n this.#eventBus = eventBus;\n }\n\n destroy() {\n this.#initController?.abort();\n this.#initController = null;\n\n this.hide();\n }\n\n show(undoAction, messageData) {\n if (!this.#initController) {\n this.#initController = new AbortController();\n const opts = { signal: this.#initController.signal };\n const boundHide = this.hide.bind(this);\n\n this.#container.addEventListener(\"contextmenu\", noContextMenu, opts);\n this.#closeButton.addEventListener(\"click\", boundHide, opts);\n this.#eventBus._on(\"beforeprint\", boundHide, opts);\n this.#eventBus._on(\"download\", boundHide, opts);\n }\n\n this.hide();\n\n if (typeof messageData === \"string\") {\n this.#message.setAttribute(\n \"data-l10n-id\",\n EditorUndoBar.#l10nMessages[messageData]\n );\n } else {\n this.#message.setAttribute(\n \"data-l10n-id\",\n EditorUndoBar.#l10nMessages._multiple\n );\n this.#message.setAttribute(\n \"data-l10n-args\",\n JSON.stringify({ count: messageData })\n );\n }\n this.isOpen = true;\n this.#container.hidden = false;\n\n this.#showController = new AbortController();\n\n this.#undoButton.addEventListener(\n \"click\",\n () => {\n undoAction();\n this.hide();\n },\n { signal: this.#showController.signal }\n );\n\n // Without the setTimeout, VoiceOver will read out the document title\n // instead of the popup label.\n this.#focusTimeout = setTimeout(() => {\n this.#container.focus();\n this.#focusTimeout = null;\n }, 100);\n }\n\n hide() {\n if (!this.isOpen) {\n return;\n }\n this.isOpen = false;\n this.#container.hidden = true;\n\n this.#showController?.abort();\n this.#showController = null;\n\n if (this.#focusTimeout) {\n clearTimeout(this.#focusTimeout);\n this.#focusTimeout = null;\n }\n }\n}\n\nexport { EditorUndoBar };\n","/* Copyright 2014 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nclass OverlayManager {\n #overlays = new WeakMap();\n\n #active = null;\n\n get active() {\n return this.#active;\n }\n\n /**\n * @param {HTMLDialogElement} dialog - The overlay's DOM element.\n * @param {boolean} [canForceClose] - Indicates if opening the overlay closes\n * an active overlay. The default is `false`.\n * @returns {Promise} A promise that is resolved when the overlay has been\n * registered.\n */\n async register(dialog, canForceClose = false) {\n if (typeof dialog !== \"object\") {\n throw new Error(\"Not enough parameters.\");\n } else if (this.#overlays.has(dialog)) {\n throw new Error(\"The overlay is already registered.\");\n }\n this.#overlays.set(dialog, { canForceClose });\n\n dialog.addEventListener(\"cancel\", evt => {\n this.#active = null;\n });\n }\n\n /**\n * @param {HTMLDialogElement} dialog - The overlay's DOM element.\n * @returns {Promise} A promise that is resolved when the overlay has been\n * opened.\n */\n async open(dialog) {\n if (!this.#overlays.has(dialog)) {\n throw new Error(\"The overlay does not exist.\");\n } else if (this.#active) {\n if (this.#active === dialog) {\n throw new Error(\"The overlay is already active.\");\n } else if (this.#overlays.get(dialog).canForceClose) {\n await this.close();\n } else {\n throw new Error(\"Another overlay is currently active.\");\n }\n }\n this.#active = dialog;\n dialog.showModal();\n }\n\n /**\n * @param {HTMLDialogElement} dialog - The overlay's DOM element.\n * @returns {Promise} A promise that is resolved when the overlay has been\n * closed.\n */\n async close(dialog = this.#active) {\n if (!this.#overlays.has(dialog)) {\n throw new Error(\"The overlay does not exist.\");\n } else if (!this.#active) {\n throw new Error(\"The overlay is currently not active.\");\n } else if (this.#active !== dialog) {\n throw new Error(\"Another overlay is currently active.\");\n }\n dialog.close();\n this.#active = null;\n }\n}\n\nexport { OverlayManager };\n","/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @typedef {import(\"./overlay_manager.js\").OverlayManager} OverlayManager */\n\nimport { PasswordResponses } from \"pdfjs-lib\";\n\n/**\n * @typedef {Object} PasswordPromptOptions\n * @property {HTMLDialogElement} dialog - The overlay's DOM element.\n * @property {HTMLParagraphElement} label - Label containing instructions for\n * entering the password.\n * @property {HTMLInputElement} input - Input field for entering the password.\n * @property {HTMLButtonElement} submitButton - Button for submitting the\n * password.\n * @property {HTMLButtonElement} cancelButton - Button for cancelling password\n * entry.\n */\n\nclass PasswordPrompt {\n #activeCapability = null;\n\n #updateCallback = null;\n\n #reason = null;\n\n /**\n * @param {PasswordPromptOptions} options\n * @param {OverlayManager} overlayManager - Manager for the viewer overlays.\n * @param {boolean} [isViewerEmbedded] - If the viewer is embedded, in e.g.\n * an