pdf_viewer.js 153 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734
  1. /* Copyright 2014 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. (function (root, factory) {
  16. 'use strict';
  17. if (typeof define === 'function' && define.amd) {
  18. define('pdfjs-dist/web/pdf_viewer', [
  19. 'exports',
  20. 'pdfjs-dist/build/pdf'
  21. ], factory);
  22. } else if (typeof exports !== 'undefined') {
  23. factory(exports, require('../build/pdf.js'));
  24. } else {
  25. factory(root.pdfjsDistWebPDFViewer = {}, root.pdfjsDistBuildPdf);
  26. }
  27. }(this, function (exports, pdfjsLib) {
  28. 'use strict';
  29. var pdfViewerLibs = { pdfjsWebPDFJS: pdfjsLib };
  30. (function () {
  31. (function (root, factory) {
  32. factory(root.pdfjsWebPDFRenderingQueue = {});
  33. }(this, function (exports) {
  34. var CLEANUP_TIMEOUT = 30000;
  35. var RenderingStates = {
  36. INITIAL: 0,
  37. RUNNING: 1,
  38. PAUSED: 2,
  39. FINISHED: 3
  40. };
  41. /**
  42. * Controls rendering of the views for pages and thumbnails.
  43. * @class
  44. */
  45. var PDFRenderingQueue = function PDFRenderingQueueClosure() {
  46. /**
  47. * @constructs
  48. */
  49. function PDFRenderingQueue() {
  50. this.pdfViewer = null;
  51. this.pdfThumbnailViewer = null;
  52. this.onIdle = null;
  53. this.highestPriorityPage = null;
  54. this.idleTimeout = null;
  55. this.printing = false;
  56. this.isThumbnailViewEnabled = false;
  57. }
  58. PDFRenderingQueue.prototype = /** @lends PDFRenderingQueue.prototype */
  59. {
  60. /**
  61. * @param {PDFViewer} pdfViewer
  62. */
  63. setViewer: function PDFRenderingQueue_setViewer(pdfViewer) {
  64. this.pdfViewer = pdfViewer;
  65. },
  66. /**
  67. * @param {PDFThumbnailViewer} pdfThumbnailViewer
  68. */
  69. setThumbnailViewer: function PDFRenderingQueue_setThumbnailViewer(pdfThumbnailViewer) {
  70. this.pdfThumbnailViewer = pdfThumbnailViewer;
  71. },
  72. /**
  73. * @param {IRenderableView} view
  74. * @returns {boolean}
  75. */
  76. isHighestPriority: function PDFRenderingQueue_isHighestPriority(view) {
  77. return this.highestPriorityPage === view.renderingId;
  78. },
  79. renderHighestPriority: function PDFRenderingQueue_renderHighestPriority(currentlyVisiblePages) {
  80. if (this.idleTimeout) {
  81. clearTimeout(this.idleTimeout);
  82. this.idleTimeout = null;
  83. }
  84. // Pages have a higher priority than thumbnails, so check them first.
  85. if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
  86. return;
  87. }
  88. // No pages needed rendering so check thumbnails.
  89. if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) {
  90. if (this.pdfThumbnailViewer.forceRendering()) {
  91. return;
  92. }
  93. }
  94. if (this.printing) {
  95. // If printing is currently ongoing do not reschedule cleanup.
  96. return;
  97. }
  98. if (this.onIdle) {
  99. this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
  100. }
  101. },
  102. getHighestPriority: function PDFRenderingQueue_getHighestPriority(visible, views, scrolledDown) {
  103. // The state has changed figure out which page has the highest priority to
  104. // render next (if any).
  105. // Priority:
  106. // 1 visible pages
  107. // 2 if last scrolled down page after the visible pages
  108. // 2 if last scrolled up page before the visible pages
  109. var visibleViews = visible.views;
  110. var numVisible = visibleViews.length;
  111. if (numVisible === 0) {
  112. return false;
  113. }
  114. for (var i = 0; i < numVisible; ++i) {
  115. var view = visibleViews[i].view;
  116. if (!this.isViewFinished(view)) {
  117. return view;
  118. }
  119. }
  120. // All the visible views have rendered, try to render next/previous pages.
  121. if (scrolledDown) {
  122. var nextPageIndex = visible.last.id;
  123. // ID's start at 1 so no need to add 1.
  124. if (views[nextPageIndex] && !this.isViewFinished(views[nextPageIndex])) {
  125. return views[nextPageIndex];
  126. }
  127. } else {
  128. var previousPageIndex = visible.first.id - 2;
  129. if (views[previousPageIndex] && !this.isViewFinished(views[previousPageIndex])) {
  130. return views[previousPageIndex];
  131. }
  132. }
  133. // Everything that needs to be rendered has been.
  134. return null;
  135. },
  136. /**
  137. * @param {IRenderableView} view
  138. * @returns {boolean}
  139. */
  140. isViewFinished: function PDFRenderingQueue_isViewFinished(view) {
  141. return view.renderingState === RenderingStates.FINISHED;
  142. },
  143. /**
  144. * Render a page or thumbnail view. This calls the appropriate function
  145. * based on the views state. If the view is already rendered it will return
  146. * false.
  147. * @param {IRenderableView} view
  148. */
  149. renderView: function PDFRenderingQueue_renderView(view) {
  150. var state = view.renderingState;
  151. switch (state) {
  152. case RenderingStates.FINISHED:
  153. return false;
  154. case RenderingStates.PAUSED:
  155. this.highestPriorityPage = view.renderingId;
  156. view.resume();
  157. break;
  158. case RenderingStates.RUNNING:
  159. this.highestPriorityPage = view.renderingId;
  160. break;
  161. case RenderingStates.INITIAL:
  162. this.highestPriorityPage = view.renderingId;
  163. var continueRendering = function () {
  164. this.renderHighestPriority();
  165. }.bind(this);
  166. view.draw().then(continueRendering, continueRendering);
  167. break;
  168. }
  169. return true;
  170. }
  171. };
  172. return PDFRenderingQueue;
  173. }();
  174. exports.RenderingStates = RenderingStates;
  175. exports.PDFRenderingQueue = PDFRenderingQueue;
  176. }));
  177. (function (root, factory) {
  178. factory(root.pdfjsWebDownloadManager = {}, root.pdfjsWebPDFJS);
  179. }(this, function (exports, pdfjsLib) {
  180. function download(blobUrl, filename) {
  181. var a = document.createElement('a');
  182. if (a.click) {
  183. // Use a.click() if available. Otherwise, Chrome might show
  184. // "Unsafe JavaScript attempt to initiate a navigation change
  185. // for frame with URL" and not open the PDF at all.
  186. // Supported by (not mentioned = untested):
  187. // - Firefox 6 - 19 (4- does not support a.click, 5 ignores a.click)
  188. // - Chrome 19 - 26 (18- does not support a.click)
  189. // - Opera 9 - 12.15
  190. // - Internet Explorer 6 - 10
  191. // - Safari 6 (5.1- does not support a.click)
  192. a.href = blobUrl;
  193. a.target = '_parent';
  194. // Use a.download if available. This increases the likelihood that
  195. // the file is downloaded instead of opened by another PDF plugin.
  196. if ('download' in a) {
  197. a.download = filename;
  198. }
  199. // <a> must be in the document for IE and recent Firefox versions.
  200. // (otherwise .click() is ignored)
  201. (document.body || document.documentElement).appendChild(a);
  202. a.click();
  203. a.parentNode.removeChild(a);
  204. } else {
  205. if (window.top === window && blobUrl.split('#')[0] === window.location.href.split('#')[0]) {
  206. // If _parent == self, then opening an identical URL with different
  207. // location hash will only cause a navigation, not a download.
  208. var padCharacter = blobUrl.indexOf('?') === -1 ? '?' : '&';
  209. blobUrl = blobUrl.replace(/#|$/, padCharacter + '$&');
  210. }
  211. window.open(blobUrl, '_parent');
  212. }
  213. }
  214. function DownloadManager() {
  215. }
  216. DownloadManager.prototype = {
  217. downloadUrl: function DownloadManager_downloadUrl(url, filename) {
  218. if (!pdfjsLib.createValidAbsoluteUrl(url, 'http://example.com')) {
  219. return;
  220. }
  221. // restricted/invalid URL
  222. download(url + '#pdfjs.action=download', filename);
  223. },
  224. downloadData: function DownloadManager_downloadData(data, filename, contentType) {
  225. if (navigator.msSaveBlob) {
  226. // IE10 and above
  227. return navigator.msSaveBlob(new Blob([data], { type: contentType }), filename);
  228. }
  229. var blobUrl = pdfjsLib.createObjectURL(data, contentType, pdfjsLib.PDFJS.disableCreateObjectURL);
  230. download(blobUrl, filename);
  231. },
  232. download: function DownloadManager_download(blob, url, filename) {
  233. if (!URL) {
  234. // URL.createObjectURL is not supported
  235. this.downloadUrl(url, filename);
  236. return;
  237. }
  238. if (navigator.msSaveBlob) {
  239. // IE10 / IE11
  240. if (!navigator.msSaveBlob(blob, filename)) {
  241. this.downloadUrl(url, filename);
  242. }
  243. return;
  244. }
  245. var blobUrl = URL.createObjectURL(blob);
  246. download(blobUrl, filename);
  247. }
  248. };
  249. exports.DownloadManager = DownloadManager;
  250. }));
  251. (function (root, factory) {
  252. factory(root.pdfjsWebUIUtils = {}, root.pdfjsWebPDFJS);
  253. }(this, function (exports, pdfjsLib) {
  254. var CSS_UNITS = 96.0 / 72.0;
  255. var DEFAULT_SCALE_VALUE = 'auto';
  256. var DEFAULT_SCALE = 1.0;
  257. var UNKNOWN_SCALE = 0;
  258. var MAX_AUTO_SCALE = 1.25;
  259. var SCROLLBAR_PADDING = 40;
  260. var VERTICAL_PADDING = 5;
  261. var mozL10n = document.mozL10n || document.webL10n;
  262. var PDFJS = pdfjsLib.PDFJS;
  263. /**
  264. * Disables fullscreen support, and by extension Presentation Mode,
  265. * in browsers which support the fullscreen API.
  266. * @var {boolean}
  267. */
  268. PDFJS.disableFullscreen = PDFJS.disableFullscreen === undefined ? false : PDFJS.disableFullscreen;
  269. /**
  270. * Enables CSS only zooming.
  271. * @var {boolean}
  272. */
  273. PDFJS.useOnlyCssZoom = PDFJS.useOnlyCssZoom === undefined ? false : PDFJS.useOnlyCssZoom;
  274. /**
  275. * The maximum supported canvas size in total pixels e.g. width * height.
  276. * The default value is 4096 * 4096. Use -1 for no limit.
  277. * @var {number}
  278. */
  279. PDFJS.maxCanvasPixels = PDFJS.maxCanvasPixels === undefined ? 16777216 : PDFJS.maxCanvasPixels;
  280. /**
  281. * Disables saving of the last position of the viewed PDF.
  282. * @var {boolean}
  283. */
  284. PDFJS.disableHistory = PDFJS.disableHistory === undefined ? false : PDFJS.disableHistory;
  285. /**
  286. * Disables creation of the text layer that used for text selection and search.
  287. * @var {boolean}
  288. */
  289. PDFJS.disableTextLayer = PDFJS.disableTextLayer === undefined ? false : PDFJS.disableTextLayer;
  290. /**
  291. * Disables maintaining the current position in the document when zooming.
  292. */
  293. PDFJS.ignoreCurrentPositionOnZoom = PDFJS.ignoreCurrentPositionOnZoom === undefined ? false : PDFJS.ignoreCurrentPositionOnZoom;
  294. /**
  295. * Interface locale settings.
  296. * @var {string}
  297. */
  298. PDFJS.locale = PDFJS.locale === undefined ? navigator.language : PDFJS.locale;
  299. /**
  300. * Returns scale factor for the canvas. It makes sense for the HiDPI displays.
  301. * @return {Object} The object with horizontal (sx) and vertical (sy)
  302. scales. The scaled property is set to false if scaling is
  303. not required, true otherwise.
  304. */
  305. function getOutputScale(ctx) {
  306. var devicePixelRatio = window.devicePixelRatio || 1;
  307. var backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
  308. var pixelRatio = devicePixelRatio / backingStoreRatio;
  309. return {
  310. sx: pixelRatio,
  311. sy: pixelRatio,
  312. scaled: pixelRatio !== 1
  313. };
  314. }
  315. /**
  316. * Scrolls specified element into view of its parent.
  317. * @param {Object} element - The element to be visible.
  318. * @param {Object} spot - An object with optional top and left properties,
  319. * specifying the offset from the top left edge.
  320. * @param {boolean} skipOverflowHiddenElements - Ignore elements that have
  321. * the CSS rule `overflow: hidden;` set. The default is false.
  322. */
  323. function scrollIntoView(element, spot, skipOverflowHiddenElements) {
  324. // Assuming offsetParent is available (it's not available when viewer is in
  325. // hidden iframe or object). We have to scroll: if the offsetParent is not set
  326. // producing the error. See also animationStartedClosure.
  327. var parent = element.offsetParent;
  328. if (!parent) {
  329. console.error('offsetParent is not set -- cannot scroll');
  330. return;
  331. }
  332. var checkOverflow = skipOverflowHiddenElements || false;
  333. var offsetY = element.offsetTop + element.clientTop;
  334. var offsetX = element.offsetLeft + element.clientLeft;
  335. while (parent.clientHeight === parent.scrollHeight || checkOverflow && getComputedStyle(parent).overflow === 'hidden') {
  336. if (parent.dataset._scaleY) {
  337. offsetY /= parent.dataset._scaleY;
  338. offsetX /= parent.dataset._scaleX;
  339. }
  340. offsetY += parent.offsetTop;
  341. offsetX += parent.offsetLeft;
  342. parent = parent.offsetParent;
  343. if (!parent) {
  344. return;
  345. }
  346. }
  347. // no need to scroll
  348. if (spot) {
  349. if (spot.top !== undefined) {
  350. offsetY += spot.top;
  351. }
  352. if (spot.left !== undefined) {
  353. offsetX += spot.left;
  354. parent.scrollLeft = offsetX;
  355. }
  356. }
  357. parent.scrollTop = offsetY;
  358. }
  359. /**
  360. * Helper function to start monitoring the scroll event and converting them into
  361. * PDF.js friendly one: with scroll debounce and scroll direction.
  362. */
  363. function watchScroll(viewAreaElement, callback) {
  364. var debounceScroll = function debounceScroll(evt) {
  365. if (rAF) {
  366. return;
  367. }
  368. // schedule an invocation of scroll for next animation frame.
  369. rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
  370. rAF = null;
  371. var currentY = viewAreaElement.scrollTop;
  372. var lastY = state.lastY;
  373. if (currentY !== lastY) {
  374. state.down = currentY > lastY;
  375. }
  376. state.lastY = currentY;
  377. callback(state);
  378. });
  379. };
  380. var state = {
  381. down: true,
  382. lastY: viewAreaElement.scrollTop,
  383. _eventHandler: debounceScroll
  384. };
  385. var rAF = null;
  386. viewAreaElement.addEventListener('scroll', debounceScroll, true);
  387. return state;
  388. }
  389. /**
  390. * Helper function to parse query string (e.g. ?param1=value&parm2=...).
  391. */
  392. function parseQueryString(query) {
  393. var parts = query.split('&');
  394. var params = {};
  395. for (var i = 0, ii = parts.length; i < ii; ++i) {
  396. var param = parts[i].split('=');
  397. var key = param[0].toLowerCase();
  398. var value = param.length > 1 ? param[1] : null;
  399. params[decodeURIComponent(key)] = decodeURIComponent(value);
  400. }
  401. return params;
  402. }
  403. /**
  404. * Use binary search to find the index of the first item in a given array which
  405. * passes a given condition. The items are expected to be sorted in the sense
  406. * that if the condition is true for one item in the array, then it is also true
  407. * for all following items.
  408. *
  409. * @returns {Number} Index of the first array element to pass the test,
  410. * or |items.length| if no such element exists.
  411. */
  412. function binarySearchFirstItem(items, condition) {
  413. var minIndex = 0;
  414. var maxIndex = items.length - 1;
  415. if (items.length === 0 || !condition(items[maxIndex])) {
  416. return items.length;
  417. }
  418. if (condition(items[minIndex])) {
  419. return minIndex;
  420. }
  421. while (minIndex < maxIndex) {
  422. var currentIndex = minIndex + maxIndex >> 1;
  423. var currentItem = items[currentIndex];
  424. if (condition(currentItem)) {
  425. maxIndex = currentIndex;
  426. } else {
  427. minIndex = currentIndex + 1;
  428. }
  429. }
  430. return minIndex;
  431. }
  432. /* === maxIndex */
  433. /**
  434. * Approximates float number as a fraction using Farey sequence (max order
  435. * of 8).
  436. * @param {number} x - Positive float number.
  437. * @returns {Array} Estimated fraction: the first array item is a numerator,
  438. * the second one is a denominator.
  439. */
  440. function approximateFraction(x) {
  441. // Fast paths for int numbers or their inversions.
  442. if (Math.floor(x) === x) {
  443. return [
  444. x,
  445. 1
  446. ];
  447. }
  448. var xinv = 1 / x;
  449. var limit = 8;
  450. if (xinv > limit) {
  451. return [
  452. 1,
  453. limit
  454. ];
  455. } else if (Math.floor(xinv) === xinv) {
  456. return [
  457. 1,
  458. xinv
  459. ];
  460. }
  461. var x_ = x > 1 ? xinv : x;
  462. // a/b and c/d are neighbours in Farey sequence.
  463. var a = 0, b = 1, c = 1, d = 1;
  464. // Limiting search to order 8.
  465. while (true) {
  466. // Generating next term in sequence (order of q).
  467. var p = a + c, q = b + d;
  468. if (q > limit) {
  469. break;
  470. }
  471. if (x_ <= p / q) {
  472. c = p;
  473. d = q;
  474. } else {
  475. a = p;
  476. b = q;
  477. }
  478. }
  479. // Select closest of the neighbours to x.
  480. if (x_ - a / b < c / d - x_) {
  481. return x_ === x ? [
  482. a,
  483. b
  484. ] : [
  485. b,
  486. a
  487. ];
  488. } else {
  489. return x_ === x ? [
  490. c,
  491. d
  492. ] : [
  493. d,
  494. c
  495. ];
  496. }
  497. }
  498. function roundToDivide(x, div) {
  499. var r = x % div;
  500. return r === 0 ? x : Math.round(x - r + div);
  501. }
  502. /**
  503. * Generic helper to find out what elements are visible within a scroll pane.
  504. */
  505. function getVisibleElements(scrollEl, views, sortByVisibility) {
  506. var top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight;
  507. var left = scrollEl.scrollLeft, right = left + scrollEl.clientWidth;
  508. function isElementBottomBelowViewTop(view) {
  509. var element = view.div;
  510. var elementBottom = element.offsetTop + element.clientTop + element.clientHeight;
  511. return elementBottom > top;
  512. }
  513. var visible = [], view, element;
  514. var currentHeight, viewHeight, hiddenHeight, percentHeight;
  515. var currentWidth, viewWidth;
  516. var firstVisibleElementInd = views.length === 0 ? 0 : binarySearchFirstItem(views, isElementBottomBelowViewTop);
  517. for (var i = firstVisibleElementInd, ii = views.length; i < ii; i++) {
  518. view = views[i];
  519. element = view.div;
  520. currentHeight = element.offsetTop + element.clientTop;
  521. viewHeight = element.clientHeight;
  522. if (currentHeight > bottom) {
  523. break;
  524. }
  525. currentWidth = element.offsetLeft + element.clientLeft;
  526. viewWidth = element.clientWidth;
  527. if (currentWidth + viewWidth < left || currentWidth > right) {
  528. continue;
  529. }
  530. hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, currentHeight + viewHeight - bottom);
  531. percentHeight = (viewHeight - hiddenHeight) * 100 / viewHeight | 0;
  532. visible.push({
  533. id: view.id,
  534. x: currentWidth,
  535. y: currentHeight,
  536. view: view,
  537. percent: percentHeight
  538. });
  539. }
  540. var first = visible[0];
  541. var last = visible[visible.length - 1];
  542. if (sortByVisibility) {
  543. visible.sort(function (a, b) {
  544. var pc = a.percent - b.percent;
  545. if (Math.abs(pc) > 0.001) {
  546. return -pc;
  547. }
  548. return a.id - b.id;
  549. });
  550. }
  551. // ensure stability
  552. return {
  553. first: first,
  554. last: last,
  555. views: visible
  556. };
  557. }
  558. /**
  559. * Event handler to suppress context menu.
  560. */
  561. function noContextMenuHandler(e) {
  562. e.preventDefault();
  563. }
  564. /**
  565. * Returns the filename or guessed filename from the url (see issue 3455).
  566. * url {String} The original PDF location.
  567. * @return {String} Guessed PDF file name.
  568. */
  569. function getPDFFileNameFromURL(url) {
  570. var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  571. // SCHEME HOST 1.PATH 2.QUERY 3.REF
  572. // Pattern to get last matching NAME.pdf
  573. var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  574. var splitURI = reURI.exec(url);
  575. var suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  576. if (suggestedFilename) {
  577. suggestedFilename = suggestedFilename[0];
  578. if (suggestedFilename.indexOf('%') !== -1) {
  579. // URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
  580. try {
  581. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  582. } catch (e) {
  583. }
  584. }
  585. }
  586. return suggestedFilename || 'document.pdf';
  587. }
  588. function normalizeWheelEventDelta(evt) {
  589. var delta = Math.sqrt(evt.deltaX * evt.deltaX + evt.deltaY * evt.deltaY);
  590. var angle = Math.atan2(evt.deltaY, evt.deltaX);
  591. if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) {
  592. // All that is left-up oriented has to change the sign.
  593. delta = -delta;
  594. }
  595. var MOUSE_DOM_DELTA_PIXEL_MODE = 0;
  596. var MOUSE_DOM_DELTA_LINE_MODE = 1;
  597. var MOUSE_PIXELS_PER_LINE = 30;
  598. var MOUSE_LINES_PER_PAGE = 30;
  599. // Converts delta to per-page units
  600. if (evt.deltaMode === MOUSE_DOM_DELTA_PIXEL_MODE) {
  601. delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE;
  602. } else if (evt.deltaMode === MOUSE_DOM_DELTA_LINE_MODE) {
  603. delta /= MOUSE_LINES_PER_PAGE;
  604. }
  605. return delta;
  606. }
  607. /**
  608. * Simple event bus for an application. Listeners are attached using the
  609. * `on` and `off` methods. To raise an event, the `dispatch` method shall be
  610. * used.
  611. */
  612. var EventBus = function EventBusClosure() {
  613. function EventBus() {
  614. this._listeners = Object.create(null);
  615. }
  616. EventBus.prototype = {
  617. on: function EventBus_on(eventName, listener) {
  618. var eventListeners = this._listeners[eventName];
  619. if (!eventListeners) {
  620. eventListeners = [];
  621. this._listeners[eventName] = eventListeners;
  622. }
  623. eventListeners.push(listener);
  624. },
  625. off: function EventBus_on(eventName, listener) {
  626. var eventListeners = this._listeners[eventName];
  627. var i;
  628. if (!eventListeners || (i = eventListeners.indexOf(listener)) < 0) {
  629. return;
  630. }
  631. eventListeners.splice(i, 1);
  632. },
  633. dispatch: function EventBus_dispath(eventName) {
  634. var eventListeners = this._listeners[eventName];
  635. if (!eventListeners || eventListeners.length === 0) {
  636. return;
  637. }
  638. // Passing all arguments after the eventName to the listeners.
  639. var args = Array.prototype.slice.call(arguments, 1);
  640. // Making copy of the listeners array in case if it will be modified
  641. // during dispatch.
  642. eventListeners.slice(0).forEach(function (listener) {
  643. listener.apply(null, args);
  644. });
  645. }
  646. };
  647. return EventBus;
  648. }();
  649. var ProgressBar = function ProgressBarClosure() {
  650. function clamp(v, min, max) {
  651. return Math.min(Math.max(v, min), max);
  652. }
  653. function ProgressBar(id, opts) {
  654. this.visible = true;
  655. // Fetch the sub-elements for later.
  656. this.div = document.querySelector(id + ' .progress');
  657. // Get the loading bar element, so it can be resized to fit the viewer.
  658. this.bar = this.div.parentNode;
  659. // Get options, with sensible defaults.
  660. this.height = opts.height || 100;
  661. this.width = opts.width || 100;
  662. this.units = opts.units || '%';
  663. // Initialize heights.
  664. this.div.style.height = this.height + this.units;
  665. this.percent = 0;
  666. }
  667. ProgressBar.prototype = {
  668. updateBar: function ProgressBar_updateBar() {
  669. if (this._indeterminate) {
  670. this.div.classList.add('indeterminate');
  671. this.div.style.width = this.width + this.units;
  672. return;
  673. }
  674. this.div.classList.remove('indeterminate');
  675. var progressSize = this.width * this._percent / 100;
  676. this.div.style.width = progressSize + this.units;
  677. },
  678. get percent() {
  679. return this._percent;
  680. },
  681. set percent(val) {
  682. this._indeterminate = isNaN(val);
  683. this._percent = clamp(val, 0, 100);
  684. this.updateBar();
  685. },
  686. setWidth: function ProgressBar_setWidth(viewer) {
  687. if (viewer) {
  688. var container = viewer.parentNode;
  689. var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
  690. if (scrollbarWidth > 0) {
  691. this.bar.setAttribute('style', 'width: calc(100% - ' + scrollbarWidth + 'px);');
  692. }
  693. }
  694. },
  695. hide: function ProgressBar_hide() {
  696. if (!this.visible) {
  697. return;
  698. }
  699. this.visible = false;
  700. this.bar.classList.add('hidden');
  701. document.body.classList.remove('loadingInProgress');
  702. },
  703. show: function ProgressBar_show() {
  704. if (this.visible) {
  705. return;
  706. }
  707. this.visible = true;
  708. document.body.classList.add('loadingInProgress');
  709. this.bar.classList.remove('hidden');
  710. }
  711. };
  712. return ProgressBar;
  713. }();
  714. exports.CSS_UNITS = CSS_UNITS;
  715. exports.DEFAULT_SCALE_VALUE = DEFAULT_SCALE_VALUE;
  716. exports.DEFAULT_SCALE = DEFAULT_SCALE;
  717. exports.UNKNOWN_SCALE = UNKNOWN_SCALE;
  718. exports.MAX_AUTO_SCALE = MAX_AUTO_SCALE;
  719. exports.SCROLLBAR_PADDING = SCROLLBAR_PADDING;
  720. exports.VERTICAL_PADDING = VERTICAL_PADDING;
  721. exports.mozL10n = mozL10n;
  722. exports.EventBus = EventBus;
  723. exports.ProgressBar = ProgressBar;
  724. exports.getPDFFileNameFromURL = getPDFFileNameFromURL;
  725. exports.noContextMenuHandler = noContextMenuHandler;
  726. exports.parseQueryString = parseQueryString;
  727. exports.getVisibleElements = getVisibleElements;
  728. exports.roundToDivide = roundToDivide;
  729. exports.approximateFraction = approximateFraction;
  730. exports.getOutputScale = getOutputScale;
  731. exports.scrollIntoView = scrollIntoView;
  732. exports.watchScroll = watchScroll;
  733. exports.binarySearchFirstItem = binarySearchFirstItem;
  734. exports.normalizeWheelEventDelta = normalizeWheelEventDelta;
  735. }));
  736. (function (root, factory) {
  737. factory(root.pdfjsWebDOMEvents = {}, root.pdfjsWebUIUtils);
  738. }(this, function (exports, uiUtils) {
  739. var EventBus = uiUtils.EventBus;
  740. // Attaching to the application event bus to dispatch events to the DOM for
  741. // backwards viewer API compatibility.
  742. function attachDOMEventsToEventBus(eventBus) {
  743. eventBus.on('documentload', function () {
  744. var event = document.createEvent('CustomEvent');
  745. event.initCustomEvent('documentload', true, true, {});
  746. window.dispatchEvent(event);
  747. });
  748. eventBus.on('pagerendered', function (e) {
  749. var event = document.createEvent('CustomEvent');
  750. event.initCustomEvent('pagerendered', true, true, {
  751. pageNumber: e.pageNumber,
  752. cssTransform: e.cssTransform
  753. });
  754. e.source.div.dispatchEvent(event);
  755. });
  756. eventBus.on('textlayerrendered', function (e) {
  757. var event = document.createEvent('CustomEvent');
  758. event.initCustomEvent('textlayerrendered', true, true, { pageNumber: e.pageNumber });
  759. e.source.textLayerDiv.dispatchEvent(event);
  760. });
  761. eventBus.on('pagechange', function (e) {
  762. var event = document.createEvent('UIEvents');
  763. event.initUIEvent('pagechange', true, true, window, 0);
  764. event.pageNumber = e.pageNumber;
  765. e.source.container.dispatchEvent(event);
  766. });
  767. eventBus.on('pagesinit', function (e) {
  768. var event = document.createEvent('CustomEvent');
  769. event.initCustomEvent('pagesinit', true, true, null);
  770. e.source.container.dispatchEvent(event);
  771. });
  772. eventBus.on('pagesloaded', function (e) {
  773. var event = document.createEvent('CustomEvent');
  774. event.initCustomEvent('pagesloaded', true, true, { pagesCount: e.pagesCount });
  775. e.source.container.dispatchEvent(event);
  776. });
  777. eventBus.on('scalechange', function (e) {
  778. var event = document.createEvent('UIEvents');
  779. event.initUIEvent('scalechange', true, true, window, 0);
  780. event.scale = e.scale;
  781. event.presetValue = e.presetValue;
  782. e.source.container.dispatchEvent(event);
  783. });
  784. eventBus.on('updateviewarea', function (e) {
  785. var event = document.createEvent('UIEvents');
  786. event.initUIEvent('updateviewarea', true, true, window, 0);
  787. event.location = e.location;
  788. e.source.container.dispatchEvent(event);
  789. });
  790. eventBus.on('find', function (e) {
  791. if (e.source === window) {
  792. return;
  793. }
  794. // event comes from FirefoxCom, no need to replicate
  795. var event = document.createEvent('CustomEvent');
  796. event.initCustomEvent('find' + e.type, true, true, {
  797. query: e.query,
  798. phraseSearch: e.phraseSearch,
  799. caseSensitive: e.caseSensitive,
  800. highlightAll: e.highlightAll,
  801. findPrevious: e.findPrevious
  802. });
  803. window.dispatchEvent(event);
  804. });
  805. eventBus.on('attachmentsloaded', function (e) {
  806. var event = document.createEvent('CustomEvent');
  807. event.initCustomEvent('attachmentsloaded', true, true, { attachmentsCount: e.attachmentsCount });
  808. e.source.container.dispatchEvent(event);
  809. });
  810. eventBus.on('sidebarviewchanged', function (e) {
  811. var event = document.createEvent('CustomEvent');
  812. event.initCustomEvent('sidebarviewchanged', true, true, { view: e.view });
  813. e.source.outerContainer.dispatchEvent(event);
  814. });
  815. eventBus.on('pagemode', function (e) {
  816. var event = document.createEvent('CustomEvent');
  817. event.initCustomEvent('pagemode', true, true, { mode: e.mode });
  818. e.source.pdfViewer.container.dispatchEvent(event);
  819. });
  820. eventBus.on('namedaction', function (e) {
  821. var event = document.createEvent('CustomEvent');
  822. event.initCustomEvent('namedaction', true, true, { action: e.action });
  823. e.source.pdfViewer.container.dispatchEvent(event);
  824. });
  825. eventBus.on('presentationmodechanged', function (e) {
  826. var event = document.createEvent('CustomEvent');
  827. event.initCustomEvent('presentationmodechanged', true, true, {
  828. active: e.active,
  829. switchInProgress: e.switchInProgress
  830. });
  831. window.dispatchEvent(event);
  832. });
  833. eventBus.on('outlineloaded', function (e) {
  834. var event = document.createEvent('CustomEvent');
  835. event.initCustomEvent('outlineloaded', true, true, { outlineCount: e.outlineCount });
  836. e.source.container.dispatchEvent(event);
  837. });
  838. }
  839. var globalEventBus = null;
  840. function getGlobalEventBus() {
  841. if (globalEventBus) {
  842. return globalEventBus;
  843. }
  844. globalEventBus = new EventBus();
  845. attachDOMEventsToEventBus(globalEventBus);
  846. return globalEventBus;
  847. }
  848. exports.attachDOMEventsToEventBus = attachDOMEventsToEventBus;
  849. exports.getGlobalEventBus = getGlobalEventBus;
  850. }));
  851. (function (root, factory) {
  852. factory(root.pdfjsWebPDFFindController = {}, root.pdfjsWebUIUtils);
  853. }(this, function (exports, uiUtils) {
  854. var scrollIntoView = uiUtils.scrollIntoView;
  855. var FindStates = {
  856. FIND_FOUND: 0,
  857. FIND_NOTFOUND: 1,
  858. FIND_WRAPPED: 2,
  859. FIND_PENDING: 3
  860. };
  861. var FIND_SCROLL_OFFSET_TOP = -50;
  862. var FIND_SCROLL_OFFSET_LEFT = -400;
  863. var CHARACTERS_TO_NORMALIZE = {
  864. '\u2018': '\'',
  865. // Left single quotation mark
  866. '\u2019': '\'',
  867. // Right single quotation mark
  868. '\u201A': '\'',
  869. // Single low-9 quotation mark
  870. '\u201B': '\'',
  871. // Single high-reversed-9 quotation mark
  872. '\u201C': '"',
  873. // Left double quotation mark
  874. '\u201D': '"',
  875. // Right double quotation mark
  876. '\u201E': '"',
  877. // Double low-9 quotation mark
  878. '\u201F': '"',
  879. // Double high-reversed-9 quotation mark
  880. '\u00BC': '1/4',
  881. // Vulgar fraction one quarter
  882. '\u00BD': '1/2',
  883. // Vulgar fraction one half
  884. '\u00BE': '3/4'
  885. };
  886. // Vulgar fraction three quarters
  887. /**
  888. * Provides "search" or "find" functionality for the PDF.
  889. * This object actually performs the search for a given string.
  890. */
  891. var PDFFindController = function PDFFindControllerClosure() {
  892. function PDFFindController(options) {
  893. this.pdfViewer = options.pdfViewer || null;
  894. this.onUpdateResultsCount = null;
  895. this.onUpdateState = null;
  896. this.reset();
  897. // Compile the regular expression for text normalization once.
  898. var replace = Object.keys(CHARACTERS_TO_NORMALIZE).join('');
  899. this.normalizationRegex = new RegExp('[' + replace + ']', 'g');
  900. }
  901. PDFFindController.prototype = {
  902. reset: function PDFFindController_reset() {
  903. this.startedTextExtraction = false;
  904. this.extractTextPromises = [];
  905. this.pendingFindMatches = Object.create(null);
  906. this.active = false;
  907. // If active, find results will be highlighted.
  908. this.pageContents = [];
  909. // Stores the text for each page.
  910. this.pageMatches = [];
  911. this.pageMatchesLength = null;
  912. this.matchCount = 0;
  913. this.selected = {
  914. // Currently selected match.
  915. pageIdx: -1,
  916. matchIdx: -1
  917. };
  918. this.offset = {
  919. // Where the find algorithm currently is in the document.
  920. pageIdx: null,
  921. matchIdx: null
  922. };
  923. this.pagesToSearch = null;
  924. this.resumePageIdx = null;
  925. this.state = null;
  926. this.dirtyMatch = false;
  927. this.findTimeout = null;
  928. this.firstPagePromise = new Promise(function (resolve) {
  929. this.resolveFirstPage = resolve;
  930. }.bind(this));
  931. },
  932. normalize: function PDFFindController_normalize(text) {
  933. return text.replace(this.normalizationRegex, function (ch) {
  934. return CHARACTERS_TO_NORMALIZE[ch];
  935. });
  936. },
  937. // Helper for multiple search - fills matchesWithLength array
  938. // and takes into account cases when one search term
  939. // include another search term (for example, "tamed tame" or "this is").
  940. // Looking for intersecting terms in the 'matches' and
  941. // leave elements with a longer match-length.
  942. _prepareMatches: function PDFFindController_prepareMatches(matchesWithLength, matches, matchesLength) {
  943. function isSubTerm(matchesWithLength, currentIndex) {
  944. var currentElem, prevElem, nextElem;
  945. currentElem = matchesWithLength[currentIndex];
  946. nextElem = matchesWithLength[currentIndex + 1];
  947. // checking for cases like "TAMEd TAME"
  948. if (currentIndex < matchesWithLength.length - 1 && currentElem.match === nextElem.match) {
  949. currentElem.skipped = true;
  950. return true;
  951. }
  952. // checking for cases like "thIS IS"
  953. for (var i = currentIndex - 1; i >= 0; i--) {
  954. prevElem = matchesWithLength[i];
  955. if (prevElem.skipped) {
  956. continue;
  957. }
  958. if (prevElem.match + prevElem.matchLength < currentElem.match) {
  959. break;
  960. }
  961. if (prevElem.match + prevElem.matchLength >= currentElem.match + currentElem.matchLength) {
  962. currentElem.skipped = true;
  963. return true;
  964. }
  965. }
  966. return false;
  967. }
  968. var i, len;
  969. // Sorting array of objects { match: <match>, matchLength: <matchLength> }
  970. // in increasing index first and then the lengths.
  971. matchesWithLength.sort(function (a, b) {
  972. return a.match === b.match ? a.matchLength - b.matchLength : a.match - b.match;
  973. });
  974. for (i = 0, len = matchesWithLength.length; i < len; i++) {
  975. if (isSubTerm(matchesWithLength, i)) {
  976. continue;
  977. }
  978. matches.push(matchesWithLength[i].match);
  979. matchesLength.push(matchesWithLength[i].matchLength);
  980. }
  981. },
  982. calcFindPhraseMatch: function PDFFindController_calcFindPhraseMatch(query, pageIndex, pageContent) {
  983. var matches = [];
  984. var queryLen = query.length;
  985. var matchIdx = -queryLen;
  986. while (true) {
  987. matchIdx = pageContent.indexOf(query, matchIdx + queryLen);
  988. if (matchIdx === -1) {
  989. break;
  990. }
  991. matches.push(matchIdx);
  992. }
  993. this.pageMatches[pageIndex] = matches;
  994. },
  995. calcFindWordMatch: function PDFFindController_calcFindWordMatch(query, pageIndex, pageContent) {
  996. var matchesWithLength = [];
  997. // Divide the query into pieces and search for text on each piece.
  998. var queryArray = query.match(/\S+/g);
  999. var subquery, subqueryLen, matchIdx;
  1000. for (var i = 0, len = queryArray.length; i < len; i++) {
  1001. subquery = queryArray[i];
  1002. subqueryLen = subquery.length;
  1003. matchIdx = -subqueryLen;
  1004. while (true) {
  1005. matchIdx = pageContent.indexOf(subquery, matchIdx + subqueryLen);
  1006. if (matchIdx === -1) {
  1007. break;
  1008. }
  1009. // Other searches do not, so we store the length.
  1010. matchesWithLength.push({
  1011. match: matchIdx,
  1012. matchLength: subqueryLen,
  1013. skipped: false
  1014. });
  1015. }
  1016. }
  1017. // Prepare arrays for store the matches.
  1018. if (!this.pageMatchesLength) {
  1019. this.pageMatchesLength = [];
  1020. }
  1021. this.pageMatchesLength[pageIndex] = [];
  1022. this.pageMatches[pageIndex] = [];
  1023. // Sort matchesWithLength, clean up intersecting terms
  1024. // and put the result into the two arrays.
  1025. this._prepareMatches(matchesWithLength, this.pageMatches[pageIndex], this.pageMatchesLength[pageIndex]);
  1026. },
  1027. calcFindMatch: function PDFFindController_calcFindMatch(pageIndex) {
  1028. var pageContent = this.normalize(this.pageContents[pageIndex]);
  1029. var query = this.normalize(this.state.query);
  1030. var caseSensitive = this.state.caseSensitive;
  1031. var phraseSearch = this.state.phraseSearch;
  1032. var queryLen = query.length;
  1033. if (queryLen === 0) {
  1034. // Do nothing: the matches should be wiped out already.
  1035. return;
  1036. }
  1037. if (!caseSensitive) {
  1038. pageContent = pageContent.toLowerCase();
  1039. query = query.toLowerCase();
  1040. }
  1041. if (phraseSearch) {
  1042. this.calcFindPhraseMatch(query, pageIndex, pageContent);
  1043. } else {
  1044. this.calcFindWordMatch(query, pageIndex, pageContent);
  1045. }
  1046. this.updatePage(pageIndex);
  1047. if (this.resumePageIdx === pageIndex) {
  1048. this.resumePageIdx = null;
  1049. this.nextPageMatch();
  1050. }
  1051. // Update the matches count
  1052. if (this.pageMatches[pageIndex].length > 0) {
  1053. this.matchCount += this.pageMatches[pageIndex].length;
  1054. this.updateUIResultsCount();
  1055. }
  1056. },
  1057. extractText: function PDFFindController_extractText() {
  1058. if (this.startedTextExtraction) {
  1059. return;
  1060. }
  1061. this.startedTextExtraction = true;
  1062. this.pageContents = [];
  1063. var extractTextPromisesResolves = [];
  1064. var numPages = this.pdfViewer.pagesCount;
  1065. for (var i = 0; i < numPages; i++) {
  1066. this.extractTextPromises.push(new Promise(function (resolve) {
  1067. extractTextPromisesResolves.push(resolve);
  1068. }));
  1069. }
  1070. var self = this;
  1071. function extractPageText(pageIndex) {
  1072. self.pdfViewer.getPageTextContent(pageIndex).then(function textContentResolved(textContent) {
  1073. var textItems = textContent.items;
  1074. var str = [];
  1075. for (var i = 0, len = textItems.length; i < len; i++) {
  1076. str.push(textItems[i].str);
  1077. }
  1078. // Store the pageContent as a string.
  1079. self.pageContents.push(str.join(''));
  1080. extractTextPromisesResolves[pageIndex](pageIndex);
  1081. if (pageIndex + 1 < self.pdfViewer.pagesCount) {
  1082. extractPageText(pageIndex + 1);
  1083. }
  1084. });
  1085. }
  1086. extractPageText(0);
  1087. },
  1088. executeCommand: function PDFFindController_executeCommand(cmd, state) {
  1089. if (this.state === null || cmd !== 'findagain') {
  1090. this.dirtyMatch = true;
  1091. }
  1092. this.state = state;
  1093. this.updateUIState(FindStates.FIND_PENDING);
  1094. this.firstPagePromise.then(function () {
  1095. this.extractText();
  1096. clearTimeout(this.findTimeout);
  1097. if (cmd === 'find') {
  1098. // Only trigger the find action after 250ms of silence.
  1099. this.findTimeout = setTimeout(this.nextMatch.bind(this), 250);
  1100. } else {
  1101. this.nextMatch();
  1102. }
  1103. }.bind(this));
  1104. },
  1105. updatePage: function PDFFindController_updatePage(index) {
  1106. if (this.selected.pageIdx === index) {
  1107. // If the page is selected, scroll the page into view, which triggers
  1108. // rendering the page, which adds the textLayer. Once the textLayer is
  1109. // build, it will scroll onto the selected match.
  1110. this.pdfViewer.currentPageNumber = index + 1;
  1111. }
  1112. var page = this.pdfViewer.getPageView(index);
  1113. if (page.textLayer) {
  1114. page.textLayer.updateMatches();
  1115. }
  1116. },
  1117. nextMatch: function PDFFindController_nextMatch() {
  1118. var previous = this.state.findPrevious;
  1119. var currentPageIndex = this.pdfViewer.currentPageNumber - 1;
  1120. var numPages = this.pdfViewer.pagesCount;
  1121. this.active = true;
  1122. if (this.dirtyMatch) {
  1123. // Need to recalculate the matches, reset everything.
  1124. this.dirtyMatch = false;
  1125. this.selected.pageIdx = this.selected.matchIdx = -1;
  1126. this.offset.pageIdx = currentPageIndex;
  1127. this.offset.matchIdx = null;
  1128. this.hadMatch = false;
  1129. this.resumePageIdx = null;
  1130. this.pageMatches = [];
  1131. this.matchCount = 0;
  1132. this.pageMatchesLength = null;
  1133. var self = this;
  1134. for (var i = 0; i < numPages; i++) {
  1135. // Wipe out any previous highlighted matches.
  1136. this.updatePage(i);
  1137. // As soon as the text is extracted start finding the matches.
  1138. if (!(i in this.pendingFindMatches)) {
  1139. this.pendingFindMatches[i] = true;
  1140. this.extractTextPromises[i].then(function (pageIdx) {
  1141. delete self.pendingFindMatches[pageIdx];
  1142. self.calcFindMatch(pageIdx);
  1143. });
  1144. }
  1145. }
  1146. }
  1147. // If there's no query there's no point in searching.
  1148. if (this.state.query === '') {
  1149. this.updateUIState(FindStates.FIND_FOUND);
  1150. return;
  1151. }
  1152. // If we're waiting on a page, we return since we can't do anything else.
  1153. if (this.resumePageIdx) {
  1154. return;
  1155. }
  1156. var offset = this.offset;
  1157. // Keep track of how many pages we should maximally iterate through.
  1158. this.pagesToSearch = numPages;
  1159. // If there's already a matchIdx that means we are iterating through a
  1160. // page's matches.
  1161. if (offset.matchIdx !== null) {
  1162. var numPageMatches = this.pageMatches[offset.pageIdx].length;
  1163. if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) {
  1164. // The simple case; we just have advance the matchIdx to select
  1165. // the next match on the page.
  1166. this.hadMatch = true;
  1167. offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1;
  1168. this.updateMatch(true);
  1169. return;
  1170. }
  1171. // We went beyond the current page's matches, so we advance to
  1172. // the next page.
  1173. this.advanceOffsetPage(previous);
  1174. }
  1175. // Start searching through the page.
  1176. this.nextPageMatch();
  1177. },
  1178. matchesReady: function PDFFindController_matchesReady(matches) {
  1179. var offset = this.offset;
  1180. var numMatches = matches.length;
  1181. var previous = this.state.findPrevious;
  1182. if (numMatches) {
  1183. // There were matches for the page, so initialize the matchIdx.
  1184. this.hadMatch = true;
  1185. offset.matchIdx = previous ? numMatches - 1 : 0;
  1186. this.updateMatch(true);
  1187. return true;
  1188. } else {
  1189. // No matches, so attempt to search the next page.
  1190. this.advanceOffsetPage(previous);
  1191. if (offset.wrapped) {
  1192. offset.matchIdx = null;
  1193. if (this.pagesToSearch < 0) {
  1194. // No point in wrapping again, there were no matches.
  1195. this.updateMatch(false);
  1196. // while matches were not found, searching for a page
  1197. // with matches should nevertheless halt.
  1198. return true;
  1199. }
  1200. }
  1201. // Matches were not found (and searching is not done).
  1202. return false;
  1203. }
  1204. },
  1205. /**
  1206. * The method is called back from the text layer when match presentation
  1207. * is updated.
  1208. * @param {number} pageIndex - page index.
  1209. * @param {number} index - match index.
  1210. * @param {Array} elements - text layer div elements array.
  1211. * @param {number} beginIdx - start index of the div array for the match.
  1212. */
  1213. updateMatchPosition: function PDFFindController_updateMatchPosition(pageIndex, index, elements, beginIdx) {
  1214. if (this.selected.matchIdx === index && this.selected.pageIdx === pageIndex) {
  1215. var spot = {
  1216. top: FIND_SCROLL_OFFSET_TOP,
  1217. left: FIND_SCROLL_OFFSET_LEFT
  1218. };
  1219. scrollIntoView(elements[beginIdx], spot, /* skipOverflowHiddenElements = */
  1220. true);
  1221. }
  1222. },
  1223. nextPageMatch: function PDFFindController_nextPageMatch() {
  1224. if (this.resumePageIdx !== null) {
  1225. console.error('There can only be one pending page.');
  1226. }
  1227. do {
  1228. var pageIdx = this.offset.pageIdx;
  1229. var matches = this.pageMatches[pageIdx];
  1230. if (!matches) {
  1231. // The matches don't exist yet for processing by "matchesReady",
  1232. // so set a resume point for when they do exist.
  1233. this.resumePageIdx = pageIdx;
  1234. break;
  1235. }
  1236. } while (!this.matchesReady(matches));
  1237. },
  1238. advanceOffsetPage: function PDFFindController_advanceOffsetPage(previous) {
  1239. var offset = this.offset;
  1240. var numPages = this.extractTextPromises.length;
  1241. offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1;
  1242. offset.matchIdx = null;
  1243. this.pagesToSearch--;
  1244. if (offset.pageIdx >= numPages || offset.pageIdx < 0) {
  1245. offset.pageIdx = previous ? numPages - 1 : 0;
  1246. offset.wrapped = true;
  1247. }
  1248. },
  1249. updateMatch: function PDFFindController_updateMatch(found) {
  1250. var state = FindStates.FIND_NOTFOUND;
  1251. var wrapped = this.offset.wrapped;
  1252. this.offset.wrapped = false;
  1253. if (found) {
  1254. var previousPage = this.selected.pageIdx;
  1255. this.selected.pageIdx = this.offset.pageIdx;
  1256. this.selected.matchIdx = this.offset.matchIdx;
  1257. state = wrapped ? FindStates.FIND_WRAPPED : FindStates.FIND_FOUND;
  1258. // Update the currently selected page to wipe out any selected matches.
  1259. if (previousPage !== -1 && previousPage !== this.selected.pageIdx) {
  1260. this.updatePage(previousPage);
  1261. }
  1262. }
  1263. this.updateUIState(state, this.state.findPrevious);
  1264. if (this.selected.pageIdx !== -1) {
  1265. this.updatePage(this.selected.pageIdx);
  1266. }
  1267. },
  1268. updateUIResultsCount: function PDFFindController_updateUIResultsCount() {
  1269. if (this.onUpdateResultsCount) {
  1270. this.onUpdateResultsCount(this.matchCount);
  1271. }
  1272. },
  1273. updateUIState: function PDFFindController_updateUIState(state, previous) {
  1274. if (this.onUpdateState) {
  1275. this.onUpdateState(state, previous, this.matchCount);
  1276. }
  1277. }
  1278. };
  1279. return PDFFindController;
  1280. }();
  1281. exports.FindStates = FindStates;
  1282. exports.PDFFindController = PDFFindController;
  1283. }));
  1284. (function (root, factory) {
  1285. factory(root.pdfjsWebPDFHistory = {}, root.pdfjsWebDOMEvents);
  1286. }(this, function (exports, domEvents) {
  1287. function PDFHistory(options) {
  1288. this.linkService = options.linkService;
  1289. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  1290. this.initialized = false;
  1291. this.initialDestination = null;
  1292. this.initialBookmark = null;
  1293. }
  1294. PDFHistory.prototype = {
  1295. /**
  1296. * @param {string} fingerprint
  1297. */
  1298. initialize: function pdfHistoryInitialize(fingerprint) {
  1299. this.initialized = true;
  1300. this.reInitialized = false;
  1301. this.allowHashChange = true;
  1302. this.historyUnlocked = true;
  1303. this.isViewerInPresentationMode = false;
  1304. this.previousHash = window.location.hash.substring(1);
  1305. this.currentBookmark = '';
  1306. this.currentPage = 0;
  1307. this.updatePreviousBookmark = false;
  1308. this.previousBookmark = '';
  1309. this.previousPage = 0;
  1310. this.nextHashParam = '';
  1311. this.fingerprint = fingerprint;
  1312. this.currentUid = this.uid = 0;
  1313. this.current = {};
  1314. var state = window.history.state;
  1315. if (this._isStateObjectDefined(state)) {
  1316. // This corresponds to navigating back to the document
  1317. // from another page in the browser history.
  1318. if (state.target.dest) {
  1319. this.initialDestination = state.target.dest;
  1320. } else {
  1321. this.initialBookmark = state.target.hash;
  1322. }
  1323. this.currentUid = state.uid;
  1324. this.uid = state.uid + 1;
  1325. this.current = state.target;
  1326. } else {
  1327. // This corresponds to the loading of a new document.
  1328. if (state && state.fingerprint && this.fingerprint !== state.fingerprint) {
  1329. // Reinitialize the browsing history when a new document
  1330. // is opened in the web viewer.
  1331. this.reInitialized = true;
  1332. }
  1333. this._pushOrReplaceState({ fingerprint: this.fingerprint }, true);
  1334. }
  1335. var self = this;
  1336. window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
  1337. if (!self.historyUnlocked) {
  1338. return;
  1339. }
  1340. if (evt.state) {
  1341. // Move back/forward in the history.
  1342. self._goTo(evt.state);
  1343. return;
  1344. }
  1345. // If the state is not set, then the user tried to navigate to a
  1346. // different hash by manually editing the URL and pressing Enter, or by
  1347. // clicking on an in-page link (e.g. the "current view" link).
  1348. // Save the current view state to the browser history.
  1349. // Note: In Firefox, history.null could also be null after an in-page
  1350. // navigation to the same URL, and without dispatching the popstate
  1351. // event: https://bugzilla.mozilla.org/show_bug.cgi?id=1183881
  1352. if (self.uid === 0) {
  1353. // Replace the previous state if it was not explicitly set.
  1354. var previousParams = self.previousHash && self.currentBookmark && self.previousHash !== self.currentBookmark ? {
  1355. hash: self.currentBookmark,
  1356. page: self.currentPage
  1357. } : { page: 1 };
  1358. replacePreviousHistoryState(previousParams, function () {
  1359. updateHistoryWithCurrentHash();
  1360. });
  1361. } else {
  1362. updateHistoryWithCurrentHash();
  1363. }
  1364. }, false);
  1365. function updateHistoryWithCurrentHash() {
  1366. self.previousHash = window.location.hash.slice(1);
  1367. self._pushToHistory({ hash: self.previousHash }, false, true);
  1368. self._updatePreviousBookmark();
  1369. }
  1370. function replacePreviousHistoryState(params, callback) {
  1371. // To modify the previous history entry, the following happens:
  1372. // 1. history.back()
  1373. // 2. _pushToHistory, which calls history.replaceState( ... )
  1374. // 3. history.forward()
  1375. // Because a navigation via the history API does not immediately update
  1376. // the history state, the popstate event is used for synchronization.
  1377. self.historyUnlocked = false;
  1378. // Suppress the hashchange event to avoid side effects caused by
  1379. // navigating back and forward.
  1380. self.allowHashChange = false;
  1381. window.addEventListener('popstate', rewriteHistoryAfterBack);
  1382. history.back();
  1383. function rewriteHistoryAfterBack() {
  1384. window.removeEventListener('popstate', rewriteHistoryAfterBack);
  1385. window.addEventListener('popstate', rewriteHistoryAfterForward);
  1386. self._pushToHistory(params, false, true);
  1387. history.forward();
  1388. }
  1389. function rewriteHistoryAfterForward() {
  1390. window.removeEventListener('popstate', rewriteHistoryAfterForward);
  1391. self.allowHashChange = true;
  1392. self.historyUnlocked = true;
  1393. callback();
  1394. }
  1395. }
  1396. function pdfHistoryBeforeUnload() {
  1397. var previousParams = self._getPreviousParams(null, true);
  1398. if (previousParams) {
  1399. var replacePrevious = !self.current.dest && self.current.hash !== self.previousHash;
  1400. self._pushToHistory(previousParams, false, replacePrevious);
  1401. self._updatePreviousBookmark();
  1402. }
  1403. // Remove the event listener when navigating away from the document,
  1404. // since 'beforeunload' prevents Firefox from caching the document.
  1405. window.removeEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  1406. }
  1407. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  1408. window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
  1409. // If the entire viewer (including the PDF file) is cached in
  1410. // the browser, we need to reattach the 'beforeunload' event listener
  1411. // since the 'DOMContentLoaded' event is not fired on 'pageshow'.
  1412. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  1413. }, false);
  1414. self.eventBus.on('presentationmodechanged', function (e) {
  1415. self.isViewerInPresentationMode = e.active;
  1416. });
  1417. },
  1418. clearHistoryState: function pdfHistory_clearHistoryState() {
  1419. this._pushOrReplaceState(null, true);
  1420. },
  1421. _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
  1422. return state && state.uid >= 0 && state.fingerprint && this.fingerprint === state.fingerprint && state.target && state.target.hash ? true : false;
  1423. },
  1424. _pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj, replace) {
  1425. if (replace) {
  1426. window.history.replaceState(stateObj, '', document.URL);
  1427. } else {
  1428. window.history.pushState(stateObj, '', document.URL);
  1429. }
  1430. },
  1431. get isHashChangeUnlocked() {
  1432. if (!this.initialized) {
  1433. return true;
  1434. }
  1435. return this.allowHashChange;
  1436. },
  1437. _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
  1438. if (this.updatePreviousBookmark && this.currentBookmark && this.currentPage) {
  1439. this.previousBookmark = this.currentBookmark;
  1440. this.previousPage = this.currentPage;
  1441. this.updatePreviousBookmark = false;
  1442. }
  1443. },
  1444. updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark, pageNum) {
  1445. if (this.initialized) {
  1446. this.currentBookmark = bookmark.substring(1);
  1447. this.currentPage = pageNum | 0;
  1448. this._updatePreviousBookmark();
  1449. }
  1450. },
  1451. updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
  1452. if (this.initialized) {
  1453. this.nextHashParam = param;
  1454. }
  1455. },
  1456. push: function pdfHistoryPush(params, isInitialBookmark) {
  1457. if (!(this.initialized && this.historyUnlocked)) {
  1458. return;
  1459. }
  1460. if (params.dest && !params.hash) {
  1461. params.hash = this.current.hash && this.current.dest && this.current.dest === params.dest ? this.current.hash : this.linkService.getDestinationHash(params.dest).split('#')[1];
  1462. }
  1463. if (params.page) {
  1464. params.page |= 0;
  1465. }
  1466. if (isInitialBookmark) {
  1467. var target = window.history.state.target;
  1468. if (!target) {
  1469. // Invoked when the user specifies an initial bookmark,
  1470. // thus setting initialBookmark, when the document is loaded.
  1471. this._pushToHistory(params, false);
  1472. this.previousHash = window.location.hash.substring(1);
  1473. }
  1474. this.updatePreviousBookmark = this.nextHashParam ? false : true;
  1475. if (target) {
  1476. // If the current document is reloaded,
  1477. // avoid creating duplicate entries in the history.
  1478. this._updatePreviousBookmark();
  1479. }
  1480. return;
  1481. }
  1482. if (this.nextHashParam) {
  1483. if (this.nextHashParam === params.hash) {
  1484. this.nextHashParam = null;
  1485. this.updatePreviousBookmark = true;
  1486. return;
  1487. } else {
  1488. this.nextHashParam = null;
  1489. }
  1490. }
  1491. if (params.hash) {
  1492. if (this.current.hash) {
  1493. if (this.current.hash !== params.hash) {
  1494. this._pushToHistory(params, true);
  1495. } else {
  1496. if (!this.current.page && params.page) {
  1497. this._pushToHistory(params, false, true);
  1498. }
  1499. this.updatePreviousBookmark = true;
  1500. }
  1501. } else {
  1502. this._pushToHistory(params, true);
  1503. }
  1504. } else if (this.current.page && params.page && this.current.page !== params.page) {
  1505. this._pushToHistory(params, true);
  1506. }
  1507. },
  1508. _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage, beforeUnload) {
  1509. if (!(this.currentBookmark && this.currentPage)) {
  1510. return null;
  1511. } else if (this.updatePreviousBookmark) {
  1512. this.updatePreviousBookmark = false;
  1513. }
  1514. if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {
  1515. // Prevent the history from getting stuck in the current state,
  1516. // effectively preventing the user from going back/forward in
  1517. // the history.
  1518. //
  1519. // This happens if the current position in the document didn't change
  1520. // when the history was previously updated. The reasons for this are
  1521. // either:
  1522. // 1. The current zoom value is such that the document does not need to,
  1523. // or cannot, be scrolled to display the destination.
  1524. // 2. The previous destination is broken, and doesn't actally point to a
  1525. // position within the document.
  1526. // (This is either due to a bad PDF generator, or the user making a
  1527. // mistake when entering a destination in the hash parameters.)
  1528. return null;
  1529. }
  1530. if (!this.current.dest && !onlyCheckPage || beforeUnload) {
  1531. if (this.previousBookmark === this.currentBookmark) {
  1532. return null;
  1533. }
  1534. } else if (this.current.page || onlyCheckPage) {
  1535. if (this.previousPage === this.currentPage) {
  1536. return null;
  1537. }
  1538. } else {
  1539. return null;
  1540. }
  1541. var params = {
  1542. hash: this.currentBookmark,
  1543. page: this.currentPage
  1544. };
  1545. if (this.isViewerInPresentationMode) {
  1546. params.hash = null;
  1547. }
  1548. return params;
  1549. },
  1550. _stateObj: function pdfHistory_stateObj(params) {
  1551. return {
  1552. fingerprint: this.fingerprint,
  1553. uid: this.uid,
  1554. target: params
  1555. };
  1556. },
  1557. _pushToHistory: function pdfHistory_pushToHistory(params, addPrevious, overwrite) {
  1558. if (!this.initialized) {
  1559. return;
  1560. }
  1561. if (!params.hash && params.page) {
  1562. params.hash = 'page=' + params.page;
  1563. }
  1564. if (addPrevious && !overwrite) {
  1565. var previousParams = this._getPreviousParams();
  1566. if (previousParams) {
  1567. var replacePrevious = !this.current.dest && this.current.hash !== this.previousHash;
  1568. this._pushToHistory(previousParams, false, replacePrevious);
  1569. }
  1570. }
  1571. this._pushOrReplaceState(this._stateObj(params), overwrite || this.uid === 0);
  1572. this.currentUid = this.uid++;
  1573. this.current = params;
  1574. this.updatePreviousBookmark = true;
  1575. },
  1576. _goTo: function pdfHistory_goTo(state) {
  1577. if (!(this.initialized && this.historyUnlocked && this._isStateObjectDefined(state))) {
  1578. return;
  1579. }
  1580. if (!this.reInitialized && state.uid < this.currentUid) {
  1581. var previousParams = this._getPreviousParams(true);
  1582. if (previousParams) {
  1583. this._pushToHistory(this.current, false);
  1584. this._pushToHistory(previousParams, false);
  1585. this.currentUid = state.uid;
  1586. window.history.back();
  1587. return;
  1588. }
  1589. }
  1590. this.historyUnlocked = false;
  1591. if (state.target.dest) {
  1592. this.linkService.navigateTo(state.target.dest);
  1593. } else {
  1594. this.linkService.setHash(state.target.hash);
  1595. }
  1596. this.currentUid = state.uid;
  1597. if (state.uid > this.uid) {
  1598. this.uid = state.uid;
  1599. }
  1600. this.current = state.target;
  1601. this.updatePreviousBookmark = true;
  1602. var currentHash = window.location.hash.substring(1);
  1603. if (this.previousHash !== currentHash) {
  1604. this.allowHashChange = false;
  1605. }
  1606. this.previousHash = currentHash;
  1607. this.historyUnlocked = true;
  1608. },
  1609. back: function pdfHistoryBack() {
  1610. this.go(-1);
  1611. },
  1612. forward: function pdfHistoryForward() {
  1613. this.go(1);
  1614. },
  1615. go: function pdfHistoryGo(direction) {
  1616. if (this.initialized && this.historyUnlocked) {
  1617. var state = window.history.state;
  1618. if (direction === -1 && state && state.uid > 0) {
  1619. window.history.back();
  1620. } else if (direction === 1 && state && state.uid < this.uid - 1) {
  1621. window.history.forward();
  1622. }
  1623. }
  1624. }
  1625. };
  1626. exports.PDFHistory = PDFHistory;
  1627. }));
  1628. (function (root, factory) {
  1629. factory(root.pdfjsWebPDFLinkService = {}, root.pdfjsWebUIUtils, root.pdfjsWebDOMEvents);
  1630. }(this, function (exports, uiUtils, domEvents) {
  1631. var parseQueryString = uiUtils.parseQueryString;
  1632. var PageNumberRegExp = /^\d+$/;
  1633. function isPageNumber(str) {
  1634. return PageNumberRegExp.test(str);
  1635. }
  1636. /**
  1637. * @typedef {Object} PDFLinkServiceOptions
  1638. * @property {EventBus} eventBus - The application event bus.
  1639. */
  1640. /**
  1641. * Performs navigation functions inside PDF, such as opening specified page,
  1642. * or destination.
  1643. * @class
  1644. * @implements {IPDFLinkService}
  1645. */
  1646. var PDFLinkService = function PDFLinkServiceClosure() {
  1647. /**
  1648. * @constructs PDFLinkService
  1649. * @param {PDFLinkServiceOptions} options
  1650. */
  1651. function PDFLinkService(options) {
  1652. options = options || {};
  1653. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  1654. this.baseUrl = null;
  1655. this.pdfDocument = null;
  1656. this.pdfViewer = null;
  1657. this.pdfHistory = null;
  1658. this._pagesRefCache = null;
  1659. }
  1660. PDFLinkService.prototype = {
  1661. setDocument: function PDFLinkService_setDocument(pdfDocument, baseUrl) {
  1662. this.baseUrl = baseUrl;
  1663. this.pdfDocument = pdfDocument;
  1664. this._pagesRefCache = Object.create(null);
  1665. },
  1666. setViewer: function PDFLinkService_setViewer(pdfViewer) {
  1667. this.pdfViewer = pdfViewer;
  1668. },
  1669. setHistory: function PDFLinkService_setHistory(pdfHistory) {
  1670. this.pdfHistory = pdfHistory;
  1671. },
  1672. /**
  1673. * @returns {number}
  1674. */
  1675. get pagesCount() {
  1676. return this.pdfDocument ? this.pdfDocument.numPages : 0;
  1677. },
  1678. /**
  1679. * @returns {number}
  1680. */
  1681. get page() {
  1682. return this.pdfViewer.currentPageNumber;
  1683. },
  1684. /**
  1685. * @param {number} value
  1686. */
  1687. set page(value) {
  1688. this.pdfViewer.currentPageNumber = value;
  1689. },
  1690. /**
  1691. * @param dest - The PDF destination object.
  1692. */
  1693. navigateTo: function PDFLinkService_navigateTo(dest) {
  1694. var destString = '';
  1695. var self = this;
  1696. var goToDestination = function (destRef) {
  1697. // dest array looks like that: <page-ref> </XYZ|/FitXXX> <args..>
  1698. var pageNumber;
  1699. if (destRef instanceof Object) {
  1700. pageNumber = self._cachedPageNumber(destRef);
  1701. } else if ((destRef | 0) === destRef) {
  1702. // Integer
  1703. pageNumber = destRef + 1;
  1704. } else {
  1705. console.error('PDFLinkService_navigateTo: "' + destRef + '" is not a valid destination reference.');
  1706. return;
  1707. }
  1708. if (pageNumber) {
  1709. if (pageNumber < 1 || pageNumber > self.pagesCount) {
  1710. console.error('PDFLinkService_navigateTo: "' + pageNumber + '" is a non-existent page number.');
  1711. return;
  1712. }
  1713. self.pdfViewer.scrollPageIntoView({
  1714. pageNumber: pageNumber,
  1715. destArray: dest
  1716. });
  1717. if (self.pdfHistory) {
  1718. // Update the browsing history.
  1719. self.pdfHistory.push({
  1720. dest: dest,
  1721. hash: destString,
  1722. page: pageNumber
  1723. });
  1724. }
  1725. } else {
  1726. self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
  1727. self.cachePageRef(pageIndex + 1, destRef);
  1728. goToDestination(destRef);
  1729. }).catch(function () {
  1730. console.error('PDFLinkService_navigateTo: "' + destRef + '" is not a valid page reference.');
  1731. return;
  1732. });
  1733. }
  1734. };
  1735. var destinationPromise;
  1736. if (typeof dest === 'string') {
  1737. destString = dest;
  1738. destinationPromise = this.pdfDocument.getDestination(dest);
  1739. } else {
  1740. destinationPromise = Promise.resolve(dest);
  1741. }
  1742. destinationPromise.then(function (destination) {
  1743. dest = destination;
  1744. if (!(destination instanceof Array)) {
  1745. console.error('PDFLinkService_navigateTo: "' + destination + '" is not a valid destination array.');
  1746. return;
  1747. }
  1748. goToDestination(destination[0]);
  1749. });
  1750. },
  1751. /**
  1752. * @param dest - The PDF destination object.
  1753. * @returns {string} The hyperlink to the PDF object.
  1754. */
  1755. getDestinationHash: function PDFLinkService_getDestinationHash(dest) {
  1756. if (typeof dest === 'string') {
  1757. // In practice, a named destination may contain only a number.
  1758. // If that happens, use the '#nameddest=' form to avoid the link
  1759. // redirecting to a page, instead of the correct destination.
  1760. return this.getAnchorUrl('#' + (isPageNumber(dest) ? 'nameddest=' : '') + escape(dest));
  1761. }
  1762. if (dest instanceof Array) {
  1763. var str = JSON.stringify(dest);
  1764. return this.getAnchorUrl('#' + escape(str));
  1765. }
  1766. return this.getAnchorUrl('');
  1767. },
  1768. /**
  1769. * Prefix the full url on anchor links to make sure that links are resolved
  1770. * relative to the current URL instead of the one defined in <base href>.
  1771. * @param {String} anchor The anchor hash, including the #.
  1772. * @returns {string} The hyperlink to the PDF object.
  1773. */
  1774. getAnchorUrl: function PDFLinkService_getAnchorUrl(anchor) {
  1775. return (this.baseUrl || '') + anchor;
  1776. },
  1777. /**
  1778. * @param {string} hash
  1779. */
  1780. setHash: function PDFLinkService_setHash(hash) {
  1781. var pageNumber, dest;
  1782. if (hash.indexOf('=') >= 0) {
  1783. var params = parseQueryString(hash);
  1784. if ('search' in params) {
  1785. this.eventBus.dispatch('findfromurlhash', {
  1786. source: this,
  1787. query: params['search'].replace(/"/g, ''),
  1788. phraseSearch: params['phrase'] === 'true'
  1789. });
  1790. }
  1791. // borrowing syntax from "Parameters for Opening PDF Files"
  1792. if ('nameddest' in params) {
  1793. if (this.pdfHistory) {
  1794. this.pdfHistory.updateNextHashParam(params.nameddest);
  1795. }
  1796. this.navigateTo(params.nameddest);
  1797. return;
  1798. }
  1799. if ('page' in params) {
  1800. pageNumber = params.page | 0 || 1;
  1801. }
  1802. if ('zoom' in params) {
  1803. // Build the destination array.
  1804. var zoomArgs = params.zoom.split(',');
  1805. // scale,left,top
  1806. var zoomArg = zoomArgs[0];
  1807. var zoomArgNumber = parseFloat(zoomArg);
  1808. if (zoomArg.indexOf('Fit') === -1) {
  1809. // If the zoomArg is a number, it has to get divided by 100. If it's
  1810. // a string, it should stay as it is.
  1811. dest = [
  1812. null,
  1813. { name: 'XYZ' },
  1814. zoomArgs.length > 1 ? zoomArgs[1] | 0 : null,
  1815. zoomArgs.length > 2 ? zoomArgs[2] | 0 : null,
  1816. zoomArgNumber ? zoomArgNumber / 100 : zoomArg
  1817. ];
  1818. } else {
  1819. if (zoomArg === 'Fit' || zoomArg === 'FitB') {
  1820. dest = [
  1821. null,
  1822. { name: zoomArg }
  1823. ];
  1824. } else if (zoomArg === 'FitH' || zoomArg === 'FitBH' || (zoomArg === 'FitV' || zoomArg === 'FitBV')) {
  1825. dest = [
  1826. null,
  1827. { name: zoomArg },
  1828. zoomArgs.length > 1 ? zoomArgs[1] | 0 : null
  1829. ];
  1830. } else if (zoomArg === 'FitR') {
  1831. if (zoomArgs.length !== 5) {
  1832. console.error('PDFLinkService_setHash: ' + 'Not enough parameters for \'FitR\'.');
  1833. } else {
  1834. dest = [
  1835. null,
  1836. { name: zoomArg },
  1837. zoomArgs[1] | 0,
  1838. zoomArgs[2] | 0,
  1839. zoomArgs[3] | 0,
  1840. zoomArgs[4] | 0
  1841. ];
  1842. }
  1843. } else {
  1844. console.error('PDFLinkService_setHash: \'' + zoomArg + '\' is not a valid zoom value.');
  1845. }
  1846. }
  1847. }
  1848. if (dest) {
  1849. this.pdfViewer.scrollPageIntoView({
  1850. pageNumber: pageNumber || this.page,
  1851. destArray: dest,
  1852. allowNegativeOffset: true
  1853. });
  1854. } else if (pageNumber) {
  1855. this.page = pageNumber;
  1856. }
  1857. // simple page
  1858. if ('pagemode' in params) {
  1859. this.eventBus.dispatch('pagemode', {
  1860. source: this,
  1861. mode: params.pagemode
  1862. });
  1863. }
  1864. } else {
  1865. // Named (or explicit) destination.
  1866. if (isPageNumber(hash) && hash <= this.pagesCount) {
  1867. console.warn('PDFLinkService_setHash: specifying a page number ' + 'directly after the hash symbol (#) is deprecated, ' + 'please use the "#page=' + hash + '" form instead.');
  1868. this.page = hash | 0;
  1869. }
  1870. dest = unescape(hash);
  1871. try {
  1872. dest = JSON.parse(dest);
  1873. if (!(dest instanceof Array)) {
  1874. // Avoid incorrectly rejecting a valid named destination, such as
  1875. // e.g. "4.3" or "true", because `JSON.parse` converted its type.
  1876. dest = dest.toString();
  1877. }
  1878. } catch (ex) {
  1879. }
  1880. if (typeof dest === 'string' || isValidExplicitDestination(dest)) {
  1881. if (this.pdfHistory) {
  1882. this.pdfHistory.updateNextHashParam(dest);
  1883. }
  1884. this.navigateTo(dest);
  1885. return;
  1886. }
  1887. console.error('PDFLinkService_setHash: \'' + unescape(hash) + '\' is not a valid destination.');
  1888. }
  1889. },
  1890. /**
  1891. * @param {string} action
  1892. */
  1893. executeNamedAction: function PDFLinkService_executeNamedAction(action) {
  1894. // See PDF reference, table 8.45 - Named action
  1895. switch (action) {
  1896. case 'GoBack':
  1897. if (this.pdfHistory) {
  1898. this.pdfHistory.back();
  1899. }
  1900. break;
  1901. case 'GoForward':
  1902. if (this.pdfHistory) {
  1903. this.pdfHistory.forward();
  1904. }
  1905. break;
  1906. case 'NextPage':
  1907. if (this.page < this.pagesCount) {
  1908. this.page++;
  1909. }
  1910. break;
  1911. case 'PrevPage':
  1912. if (this.page > 1) {
  1913. this.page--;
  1914. }
  1915. break;
  1916. case 'LastPage':
  1917. this.page = this.pagesCount;
  1918. break;
  1919. case 'FirstPage':
  1920. this.page = 1;
  1921. break;
  1922. default:
  1923. break;
  1924. }
  1925. // No action according to spec
  1926. this.eventBus.dispatch('namedaction', {
  1927. source: this,
  1928. action: action
  1929. });
  1930. },
  1931. /**
  1932. * @param {number} pageNum - page number.
  1933. * @param {Object} pageRef - reference to the page.
  1934. */
  1935. cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) {
  1936. var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
  1937. this._pagesRefCache[refStr] = pageNum;
  1938. },
  1939. _cachedPageNumber: function PDFLinkService_cachedPageNumber(pageRef) {
  1940. var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
  1941. return this._pagesRefCache && this._pagesRefCache[refStr] || null;
  1942. }
  1943. };
  1944. function isValidExplicitDestination(dest) {
  1945. if (!(dest instanceof Array)) {
  1946. return false;
  1947. }
  1948. var destLength = dest.length, allowNull = true;
  1949. if (destLength < 2) {
  1950. return false;
  1951. }
  1952. var page = dest[0];
  1953. if (!(typeof page === 'object' && typeof page.num === 'number' && (page.num | 0) === page.num && typeof page.gen === 'number' && (page.gen | 0) === page.gen) && !(typeof page === 'number' && (page | 0) === page && page >= 0)) {
  1954. return false;
  1955. }
  1956. var zoom = dest[1];
  1957. if (!(typeof zoom === 'object' && typeof zoom.name === 'string')) {
  1958. return false;
  1959. }
  1960. switch (zoom.name) {
  1961. case 'XYZ':
  1962. if (destLength !== 5) {
  1963. return false;
  1964. }
  1965. break;
  1966. case 'Fit':
  1967. case 'FitB':
  1968. return destLength === 2;
  1969. case 'FitH':
  1970. case 'FitBH':
  1971. case 'FitV':
  1972. case 'FitBV':
  1973. if (destLength !== 3) {
  1974. return false;
  1975. }
  1976. break;
  1977. case 'FitR':
  1978. if (destLength !== 6) {
  1979. return false;
  1980. }
  1981. allowNull = false;
  1982. break;
  1983. default:
  1984. return false;
  1985. }
  1986. for (var i = 2; i < destLength; i++) {
  1987. var param = dest[i];
  1988. if (!(typeof param === 'number' || allowNull && param === null)) {
  1989. return false;
  1990. }
  1991. }
  1992. return true;
  1993. }
  1994. return PDFLinkService;
  1995. }();
  1996. var SimpleLinkService = function SimpleLinkServiceClosure() {
  1997. function SimpleLinkService() {
  1998. }
  1999. SimpleLinkService.prototype = {
  2000. /**
  2001. * @returns {number}
  2002. */
  2003. get page() {
  2004. return 0;
  2005. },
  2006. /**
  2007. * @param {number} value
  2008. */
  2009. set page(value) {
  2010. },
  2011. /**
  2012. * @param dest - The PDF destination object.
  2013. */
  2014. navigateTo: function (dest) {
  2015. },
  2016. /**
  2017. * @param dest - The PDF destination object.
  2018. * @returns {string} The hyperlink to the PDF object.
  2019. */
  2020. getDestinationHash: function (dest) {
  2021. return '#';
  2022. },
  2023. /**
  2024. * @param hash - The PDF parameters/hash.
  2025. * @returns {string} The hyperlink to the PDF object.
  2026. */
  2027. getAnchorUrl: function (hash) {
  2028. return '#';
  2029. },
  2030. /**
  2031. * @param {string} hash
  2032. */
  2033. setHash: function (hash) {
  2034. },
  2035. /**
  2036. * @param {string} action
  2037. */
  2038. executeNamedAction: function (action) {
  2039. },
  2040. /**
  2041. * @param {number} pageNum - page number.
  2042. * @param {Object} pageRef - reference to the page.
  2043. */
  2044. cachePageRef: function (pageNum, pageRef) {
  2045. }
  2046. };
  2047. return SimpleLinkService;
  2048. }();
  2049. exports.PDFLinkService = PDFLinkService;
  2050. exports.SimpleLinkService = SimpleLinkService;
  2051. }));
  2052. (function (root, factory) {
  2053. factory(root.pdfjsWebPDFPageView = {}, root.pdfjsWebUIUtils, root.pdfjsWebPDFRenderingQueue, root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS);
  2054. }(this, function (exports, uiUtils, pdfRenderingQueue, domEvents, pdfjsLib) {
  2055. var CSS_UNITS = uiUtils.CSS_UNITS;
  2056. var DEFAULT_SCALE = uiUtils.DEFAULT_SCALE;
  2057. var getOutputScale = uiUtils.getOutputScale;
  2058. var approximateFraction = uiUtils.approximateFraction;
  2059. var roundToDivide = uiUtils.roundToDivide;
  2060. var RenderingStates = pdfRenderingQueue.RenderingStates;
  2061. var TEXT_LAYER_RENDER_DELAY = 200;
  2062. // ms
  2063. /**
  2064. * @typedef {Object} PDFPageViewOptions
  2065. * @property {HTMLDivElement} container - The viewer element.
  2066. * @property {EventBus} eventBus - The application event bus.
  2067. * @property {number} id - The page unique ID (normally its number).
  2068. * @property {number} scale - The page scale display.
  2069. * @property {PageViewport} defaultViewport - The page viewport.
  2070. * @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
  2071. * @property {IPDFTextLayerFactory} textLayerFactory
  2072. * @property {IPDFAnnotationLayerFactory} annotationLayerFactory
  2073. * @property {boolean} enhanceTextSelection - Turns on the text selection
  2074. * enhancement. The default is `false`.
  2075. * @property {boolean} renderInteractiveForms - Turns on rendering of
  2076. * interactive form elements. The default is `false`.
  2077. */
  2078. /**
  2079. * @class
  2080. * @implements {IRenderableView}
  2081. */
  2082. var PDFPageView = function PDFPageViewClosure() {
  2083. /**
  2084. * @constructs PDFPageView
  2085. * @param {PDFPageViewOptions} options
  2086. */
  2087. function PDFPageView(options) {
  2088. var container = options.container;
  2089. var id = options.id;
  2090. var scale = options.scale;
  2091. var defaultViewport = options.defaultViewport;
  2092. var renderingQueue = options.renderingQueue;
  2093. var textLayerFactory = options.textLayerFactory;
  2094. var annotationLayerFactory = options.annotationLayerFactory;
  2095. var enhanceTextSelection = options.enhanceTextSelection || false;
  2096. var renderInteractiveForms = options.renderInteractiveForms || false;
  2097. this.id = id;
  2098. this.renderingId = 'page' + id;
  2099. this.rotation = 0;
  2100. this.scale = scale || DEFAULT_SCALE;
  2101. this.viewport = defaultViewport;
  2102. this.pdfPageRotate = defaultViewport.rotation;
  2103. this.hasRestrictedScaling = false;
  2104. this.enhanceTextSelection = enhanceTextSelection;
  2105. this.renderInteractiveForms = renderInteractiveForms;
  2106. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  2107. this.renderingQueue = renderingQueue;
  2108. this.textLayerFactory = textLayerFactory;
  2109. this.annotationLayerFactory = annotationLayerFactory;
  2110. this.renderTask = null;
  2111. this.renderingState = RenderingStates.INITIAL;
  2112. this.resume = null;
  2113. this.onBeforeDraw = null;
  2114. this.onAfterDraw = null;
  2115. this.textLayer = null;
  2116. this.zoomLayer = null;
  2117. this.annotationLayer = null;
  2118. var div = document.createElement('div');
  2119. div.id = 'pageContainer' + this.id;
  2120. div.className = 'page';
  2121. div.style.width = Math.floor(this.viewport.width) + 'px';
  2122. div.style.height = Math.floor(this.viewport.height) + 'px';
  2123. div.setAttribute('data-page-number', this.id);
  2124. this.div = div;
  2125. container.appendChild(div);
  2126. }
  2127. PDFPageView.prototype = {
  2128. setPdfPage: function PDFPageView_setPdfPage(pdfPage) {
  2129. this.pdfPage = pdfPage;
  2130. this.pdfPageRotate = pdfPage.rotate;
  2131. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  2132. this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS, totalRotation);
  2133. this.stats = pdfPage.stats;
  2134. this.reset();
  2135. },
  2136. destroy: function PDFPageView_destroy() {
  2137. this.zoomLayer = null;
  2138. this.reset();
  2139. if (this.pdfPage) {
  2140. this.pdfPage.cleanup();
  2141. }
  2142. },
  2143. reset: function PDFPageView_reset(keepZoomLayer, keepAnnotations) {
  2144. this.cancelRendering();
  2145. var div = this.div;
  2146. div.style.width = Math.floor(this.viewport.width) + 'px';
  2147. div.style.height = Math.floor(this.viewport.height) + 'px';
  2148. var childNodes = div.childNodes;
  2149. var currentZoomLayerNode = keepZoomLayer && this.zoomLayer || null;
  2150. var currentAnnotationNode = keepAnnotations && this.annotationLayer && this.annotationLayer.div || null;
  2151. for (var i = childNodes.length - 1; i >= 0; i--) {
  2152. var node = childNodes[i];
  2153. if (currentZoomLayerNode === node || currentAnnotationNode === node) {
  2154. continue;
  2155. }
  2156. div.removeChild(node);
  2157. }
  2158. div.removeAttribute('data-loaded');
  2159. if (currentAnnotationNode) {
  2160. // Hide annotationLayer until all elements are resized
  2161. // so they are not displayed on the already-resized page
  2162. this.annotationLayer.hide();
  2163. } else {
  2164. this.annotationLayer = null;
  2165. }
  2166. if (this.canvas && !currentZoomLayerNode) {
  2167. // Zeroing the width and height causes Firefox to release graphics
  2168. // resources immediately, which can greatly reduce memory consumption.
  2169. this.canvas.width = 0;
  2170. this.canvas.height = 0;
  2171. delete this.canvas;
  2172. }
  2173. this.loadingIconDiv = document.createElement('div');
  2174. this.loadingIconDiv.className = 'loadingIcon';
  2175. div.appendChild(this.loadingIconDiv);
  2176. },
  2177. update: function PDFPageView_update(scale, rotation) {
  2178. this.scale = scale || this.scale;
  2179. if (typeof rotation !== 'undefined') {
  2180. this.rotation = rotation;
  2181. }
  2182. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  2183. this.viewport = this.viewport.clone({
  2184. scale: this.scale * CSS_UNITS,
  2185. rotation: totalRotation
  2186. });
  2187. var isScalingRestricted = false;
  2188. if (this.canvas && pdfjsLib.PDFJS.maxCanvasPixels > 0) {
  2189. var outputScale = this.outputScale;
  2190. if ((Math.floor(this.viewport.width) * outputScale.sx | 0) * (Math.floor(this.viewport.height) * outputScale.sy | 0) > pdfjsLib.PDFJS.maxCanvasPixels) {
  2191. isScalingRestricted = true;
  2192. }
  2193. }
  2194. if (this.canvas) {
  2195. if (pdfjsLib.PDFJS.useOnlyCssZoom || this.hasRestrictedScaling && isScalingRestricted) {
  2196. this.cssTransform(this.canvas, true);
  2197. this.eventBus.dispatch('pagerendered', {
  2198. source: this,
  2199. pageNumber: this.id,
  2200. cssTransform: true
  2201. });
  2202. return;
  2203. }
  2204. if (!this.zoomLayer) {
  2205. this.zoomLayer = this.canvas.parentNode;
  2206. this.zoomLayer.style.position = 'absolute';
  2207. }
  2208. }
  2209. if (this.zoomLayer) {
  2210. this.cssTransform(this.zoomLayer.firstChild);
  2211. }
  2212. this.reset(/* keepZoomLayer = */
  2213. true, /* keepAnnotations = */
  2214. true);
  2215. },
  2216. cancelRendering: function PDFPageView_cancelRendering() {
  2217. if (this.renderTask) {
  2218. this.renderTask.cancel();
  2219. this.renderTask = null;
  2220. }
  2221. this.renderingState = RenderingStates.INITIAL;
  2222. this.resume = null;
  2223. if (this.textLayer) {
  2224. this.textLayer.cancel();
  2225. this.textLayer = null;
  2226. }
  2227. },
  2228. /**
  2229. * Called when moved in the parent's container.
  2230. */
  2231. updatePosition: function PDFPageView_updatePosition() {
  2232. if (this.textLayer) {
  2233. this.textLayer.render(TEXT_LAYER_RENDER_DELAY);
  2234. }
  2235. },
  2236. cssTransform: function PDFPageView_transform(canvas, redrawAnnotations) {
  2237. var CustomStyle = pdfjsLib.CustomStyle;
  2238. // Scale canvas, canvas wrapper, and page container.
  2239. var width = this.viewport.width;
  2240. var height = this.viewport.height;
  2241. var div = this.div;
  2242. canvas.style.width = canvas.parentNode.style.width = div.style.width = Math.floor(width) + 'px';
  2243. canvas.style.height = canvas.parentNode.style.height = div.style.height = Math.floor(height) + 'px';
  2244. // The canvas may have been originally rotated, rotate relative to that.
  2245. var relativeRotation = this.viewport.rotation - canvas._viewport.rotation;
  2246. var absRotation = Math.abs(relativeRotation);
  2247. var scaleX = 1, scaleY = 1;
  2248. if (absRotation === 90 || absRotation === 270) {
  2249. // Scale x and y because of the rotation.
  2250. scaleX = height / width;
  2251. scaleY = width / height;
  2252. }
  2253. var cssTransform = 'rotate(' + relativeRotation + 'deg) ' + 'scale(' + scaleX + ',' + scaleY + ')';
  2254. CustomStyle.setProp('transform', canvas, cssTransform);
  2255. if (this.textLayer) {
  2256. // Rotating the text layer is more complicated since the divs inside the
  2257. // the text layer are rotated.
  2258. // TODO: This could probably be simplified by drawing the text layer in
  2259. // one orientation then rotating overall.
  2260. var textLayerViewport = this.textLayer.viewport;
  2261. var textRelativeRotation = this.viewport.rotation - textLayerViewport.rotation;
  2262. var textAbsRotation = Math.abs(textRelativeRotation);
  2263. var scale = width / textLayerViewport.width;
  2264. if (textAbsRotation === 90 || textAbsRotation === 270) {
  2265. scale = width / textLayerViewport.height;
  2266. }
  2267. var textLayerDiv = this.textLayer.textLayerDiv;
  2268. var transX, transY;
  2269. switch (textAbsRotation) {
  2270. case 0:
  2271. transX = transY = 0;
  2272. break;
  2273. case 90:
  2274. transX = 0;
  2275. transY = '-' + textLayerDiv.style.height;
  2276. break;
  2277. case 180:
  2278. transX = '-' + textLayerDiv.style.width;
  2279. transY = '-' + textLayerDiv.style.height;
  2280. break;
  2281. case 270:
  2282. transX = '-' + textLayerDiv.style.width;
  2283. transY = 0;
  2284. break;
  2285. default:
  2286. console.error('Bad rotation value.');
  2287. break;
  2288. }
  2289. CustomStyle.setProp('transform', textLayerDiv, 'rotate(' + textAbsRotation + 'deg) ' + 'scale(' + scale + ', ' + scale + ') ' + 'translate(' + transX + ', ' + transY + ')');
  2290. CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');
  2291. }
  2292. if (redrawAnnotations && this.annotationLayer) {
  2293. this.annotationLayer.render(this.viewport, 'display');
  2294. }
  2295. },
  2296. get width() {
  2297. return this.viewport.width;
  2298. },
  2299. get height() {
  2300. return this.viewport.height;
  2301. },
  2302. getPagePoint: function PDFPageView_getPagePoint(x, y) {
  2303. return this.viewport.convertToPdfPoint(x, y);
  2304. },
  2305. draw: function PDFPageView_draw() {
  2306. if (this.renderingState !== RenderingStates.INITIAL) {
  2307. console.error('Must be in new state before drawing');
  2308. this.reset();
  2309. }
  2310. // Ensure that we reset all state to prevent issues.
  2311. this.renderingState = RenderingStates.RUNNING;
  2312. var pdfPage = this.pdfPage;
  2313. var viewport = this.viewport;
  2314. var div = this.div;
  2315. // Wrap the canvas so if it has a css transform for highdpi the overflow
  2316. // will be hidden in FF.
  2317. var canvasWrapper = document.createElement('div');
  2318. canvasWrapper.style.width = div.style.width;
  2319. canvasWrapper.style.height = div.style.height;
  2320. canvasWrapper.classList.add('canvasWrapper');
  2321. var canvas = document.createElement('canvas');
  2322. canvas.id = 'page' + this.id;
  2323. // Keep the canvas hidden until the first draw callback, or until drawing
  2324. // is complete when `!this.renderingQueue`, to prevent black flickering.
  2325. canvas.setAttribute('hidden', 'hidden');
  2326. var isCanvasHidden = true;
  2327. canvasWrapper.appendChild(canvas);
  2328. if (this.annotationLayer && this.annotationLayer.div) {
  2329. // annotationLayer needs to stay on top
  2330. div.insertBefore(canvasWrapper, this.annotationLayer.div);
  2331. } else {
  2332. div.appendChild(canvasWrapper);
  2333. }
  2334. this.canvas = canvas;
  2335. canvas.mozOpaque = true;
  2336. var ctx = canvas.getContext('2d', { alpha: false });
  2337. var outputScale = getOutputScale(ctx);
  2338. this.outputScale = outputScale;
  2339. if (pdfjsLib.PDFJS.useOnlyCssZoom) {
  2340. var actualSizeViewport = viewport.clone({ scale: CSS_UNITS });
  2341. // Use a scale that will make the canvas be the original intended size
  2342. // of the page.
  2343. outputScale.sx *= actualSizeViewport.width / viewport.width;
  2344. outputScale.sy *= actualSizeViewport.height / viewport.height;
  2345. outputScale.scaled = true;
  2346. }
  2347. if (pdfjsLib.PDFJS.maxCanvasPixels > 0) {
  2348. var pixelsInViewport = viewport.width * viewport.height;
  2349. var maxScale = Math.sqrt(pdfjsLib.PDFJS.maxCanvasPixels / pixelsInViewport);
  2350. if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
  2351. outputScale.sx = maxScale;
  2352. outputScale.sy = maxScale;
  2353. outputScale.scaled = true;
  2354. this.hasRestrictedScaling = true;
  2355. } else {
  2356. this.hasRestrictedScaling = false;
  2357. }
  2358. }
  2359. var sfx = approximateFraction(outputScale.sx);
  2360. var sfy = approximateFraction(outputScale.sy);
  2361. canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]);
  2362. canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]);
  2363. canvas.style.width = roundToDivide(viewport.width, sfx[1]) + 'px';
  2364. canvas.style.height = roundToDivide(viewport.height, sfy[1]) + 'px';
  2365. // Add the viewport so it's known what it was originally drawn with.
  2366. canvas._viewport = viewport;
  2367. var textLayerDiv = null;
  2368. var textLayer = null;
  2369. if (this.textLayerFactory) {
  2370. textLayerDiv = document.createElement('div');
  2371. textLayerDiv.className = 'textLayer';
  2372. textLayerDiv.style.width = canvasWrapper.style.width;
  2373. textLayerDiv.style.height = canvasWrapper.style.height;
  2374. if (this.annotationLayer && this.annotationLayer.div) {
  2375. // annotationLayer needs to stay on top
  2376. div.insertBefore(textLayerDiv, this.annotationLayer.div);
  2377. } else {
  2378. div.appendChild(textLayerDiv);
  2379. }
  2380. textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv, this.id - 1, this.viewport, this.enhanceTextSelection);
  2381. }
  2382. this.textLayer = textLayer;
  2383. var resolveRenderPromise, rejectRenderPromise;
  2384. var promise = new Promise(function (resolve, reject) {
  2385. resolveRenderPromise = resolve;
  2386. rejectRenderPromise = reject;
  2387. });
  2388. // Rendering area
  2389. var self = this;
  2390. function pageViewDrawCallback(error) {
  2391. // The renderTask may have been replaced by a new one, so only remove
  2392. // the reference to the renderTask if it matches the one that is
  2393. // triggering this callback.
  2394. if (renderTask === self.renderTask) {
  2395. self.renderTask = null;
  2396. }
  2397. if (error === 'cancelled') {
  2398. rejectRenderPromise(error);
  2399. return;
  2400. }
  2401. self.renderingState = RenderingStates.FINISHED;
  2402. if (isCanvasHidden) {
  2403. self.canvas.removeAttribute('hidden');
  2404. isCanvasHidden = false;
  2405. }
  2406. if (self.loadingIconDiv) {
  2407. div.removeChild(self.loadingIconDiv);
  2408. delete self.loadingIconDiv;
  2409. }
  2410. if (self.zoomLayer) {
  2411. // Zeroing the width and height causes Firefox to release graphics
  2412. // resources immediately, which can greatly reduce memory consumption.
  2413. var zoomLayerCanvas = self.zoomLayer.firstChild;
  2414. zoomLayerCanvas.width = 0;
  2415. zoomLayerCanvas.height = 0;
  2416. if (div.contains(self.zoomLayer)) {
  2417. // Prevent "Node was not found" errors if the `zoomLayer` was
  2418. // already removed. This may occur intermittently if the scale
  2419. // changes many times in very quick succession.
  2420. div.removeChild(self.zoomLayer);
  2421. }
  2422. self.zoomLayer = null;
  2423. }
  2424. self.error = error;
  2425. self.stats = pdfPage.stats;
  2426. if (self.onAfterDraw) {
  2427. self.onAfterDraw();
  2428. }
  2429. self.eventBus.dispatch('pagerendered', {
  2430. source: self,
  2431. pageNumber: self.id,
  2432. cssTransform: false
  2433. });
  2434. if (!error) {
  2435. resolveRenderPromise(undefined);
  2436. } else {
  2437. rejectRenderPromise(error);
  2438. }
  2439. }
  2440. var renderContinueCallback = null;
  2441. if (this.renderingQueue) {
  2442. renderContinueCallback = function renderContinueCallback(cont) {
  2443. if (!self.renderingQueue.isHighestPriority(self)) {
  2444. self.renderingState = RenderingStates.PAUSED;
  2445. self.resume = function resumeCallback() {
  2446. self.renderingState = RenderingStates.RUNNING;
  2447. cont();
  2448. };
  2449. return;
  2450. }
  2451. if (isCanvasHidden) {
  2452. self.canvas.removeAttribute('hidden');
  2453. isCanvasHidden = false;
  2454. }
  2455. cont();
  2456. };
  2457. }
  2458. var transform = !outputScale.scaled ? null : [
  2459. outputScale.sx,
  2460. 0,
  2461. 0,
  2462. outputScale.sy,
  2463. 0,
  2464. 0
  2465. ];
  2466. var renderContext = {
  2467. canvasContext: ctx,
  2468. transform: transform,
  2469. viewport: this.viewport,
  2470. renderInteractiveForms: this.renderInteractiveForms
  2471. };
  2472. // intent: 'default', // === 'display'
  2473. var renderTask = this.renderTask = this.pdfPage.render(renderContext);
  2474. renderTask.onContinue = renderContinueCallback;
  2475. this.renderTask.promise.then(function pdfPageRenderCallback() {
  2476. pageViewDrawCallback(null);
  2477. if (textLayer) {
  2478. self.pdfPage.getTextContent({ normalizeWhitespace: true }).then(function textContentResolved(textContent) {
  2479. textLayer.setTextContent(textContent);
  2480. textLayer.render(TEXT_LAYER_RENDER_DELAY);
  2481. });
  2482. }
  2483. }, function pdfPageRenderError(error) {
  2484. pageViewDrawCallback(error);
  2485. });
  2486. if (this.annotationLayerFactory) {
  2487. if (!this.annotationLayer) {
  2488. this.annotationLayer = this.annotationLayerFactory.createAnnotationLayerBuilder(div, this.pdfPage, this.renderInteractiveForms);
  2489. }
  2490. this.annotationLayer.render(this.viewport, 'display');
  2491. }
  2492. div.setAttribute('data-loaded', true);
  2493. if (self.onBeforeDraw) {
  2494. self.onBeforeDraw();
  2495. }
  2496. return promise;
  2497. }
  2498. };
  2499. return PDFPageView;
  2500. }();
  2501. exports.PDFPageView = PDFPageView;
  2502. }));
  2503. (function (root, factory) {
  2504. factory(root.pdfjsWebTextLayerBuilder = {}, root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS);
  2505. }(this, function (exports, domEvents, pdfjsLib) {
  2506. var EXPAND_DIVS_TIMEOUT = 300;
  2507. // ms
  2508. /**
  2509. * @typedef {Object} TextLayerBuilderOptions
  2510. * @property {HTMLDivElement} textLayerDiv - The text layer container.
  2511. * @property {EventBus} eventBus - The application event bus.
  2512. * @property {number} pageIndex - The page index.
  2513. * @property {PageViewport} viewport - The viewport of the text layer.
  2514. * @property {PDFFindController} findController
  2515. * @property {boolean} enhanceTextSelection - Option to turn on improved
  2516. * text selection.
  2517. */
  2518. /**
  2519. * TextLayerBuilder provides text-selection functionality for the PDF.
  2520. * It does this by creating overlay divs over the PDF text. These divs
  2521. * contain text that matches the PDF text they are overlaying. This object
  2522. * also provides a way to highlight text that is being searched for.
  2523. * @class
  2524. */
  2525. var TextLayerBuilder = function TextLayerBuilderClosure() {
  2526. function TextLayerBuilder(options) {
  2527. this.textLayerDiv = options.textLayerDiv;
  2528. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  2529. this.textContent = null;
  2530. this.renderingDone = false;
  2531. this.pageIdx = options.pageIndex;
  2532. this.pageNumber = this.pageIdx + 1;
  2533. this.matches = [];
  2534. this.viewport = options.viewport;
  2535. this.textDivs = [];
  2536. this.findController = options.findController || null;
  2537. this.textLayerRenderTask = null;
  2538. this.enhanceTextSelection = options.enhanceTextSelection;
  2539. this._bindMouse();
  2540. }
  2541. TextLayerBuilder.prototype = {
  2542. /**
  2543. * @private
  2544. */
  2545. _finishRendering: function TextLayerBuilder_finishRendering() {
  2546. this.renderingDone = true;
  2547. if (!this.enhanceTextSelection) {
  2548. var endOfContent = document.createElement('div');
  2549. endOfContent.className = 'endOfContent';
  2550. this.textLayerDiv.appendChild(endOfContent);
  2551. }
  2552. this.eventBus.dispatch('textlayerrendered', {
  2553. source: this,
  2554. pageNumber: this.pageNumber,
  2555. numTextDivs: this.textDivs.length
  2556. });
  2557. },
  2558. /**
  2559. * Renders the text layer.
  2560. * @param {number} timeout (optional) if specified, the rendering waits
  2561. * for specified amount of ms.
  2562. */
  2563. render: function TextLayerBuilder_render(timeout) {
  2564. if (!this.textContent || this.renderingDone) {
  2565. return;
  2566. }
  2567. this.cancel();
  2568. this.textDivs = [];
  2569. var textLayerFrag = document.createDocumentFragment();
  2570. this.textLayerRenderTask = pdfjsLib.renderTextLayer({
  2571. textContent: this.textContent,
  2572. container: textLayerFrag,
  2573. viewport: this.viewport,
  2574. textDivs: this.textDivs,
  2575. timeout: timeout,
  2576. enhanceTextSelection: this.enhanceTextSelection
  2577. });
  2578. this.textLayerRenderTask.promise.then(function () {
  2579. this.textLayerDiv.appendChild(textLayerFrag);
  2580. this._finishRendering();
  2581. this.updateMatches();
  2582. }.bind(this), function (reason) {
  2583. });
  2584. },
  2585. /**
  2586. * Cancels rendering of the text layer.
  2587. */
  2588. cancel: function TextLayerBuilder_cancel() {
  2589. if (this.textLayerRenderTask) {
  2590. this.textLayerRenderTask.cancel();
  2591. this.textLayerRenderTask = null;
  2592. }
  2593. },
  2594. setTextContent: function TextLayerBuilder_setTextContent(textContent) {
  2595. this.cancel();
  2596. this.textContent = textContent;
  2597. },
  2598. convertMatches: function TextLayerBuilder_convertMatches(matches, matchesLength) {
  2599. var i = 0;
  2600. var iIndex = 0;
  2601. var bidiTexts = this.textContent.items;
  2602. var end = bidiTexts.length - 1;
  2603. var queryLen = this.findController === null ? 0 : this.findController.state.query.length;
  2604. var ret = [];
  2605. if (!matches) {
  2606. return ret;
  2607. }
  2608. for (var m = 0, len = matches.length; m < len; m++) {
  2609. // Calculate the start position.
  2610. var matchIdx = matches[m];
  2611. // Loop over the divIdxs.
  2612. while (i !== end && matchIdx >= iIndex + bidiTexts[i].str.length) {
  2613. iIndex += bidiTexts[i].str.length;
  2614. i++;
  2615. }
  2616. if (i === bidiTexts.length) {
  2617. console.error('Could not find a matching mapping');
  2618. }
  2619. var match = {
  2620. begin: {
  2621. divIdx: i,
  2622. offset: matchIdx - iIndex
  2623. }
  2624. };
  2625. // Calculate the end position.
  2626. if (matchesLength) {
  2627. // multiterm search
  2628. matchIdx += matchesLength[m];
  2629. } else {
  2630. // phrase search
  2631. matchIdx += queryLen;
  2632. }
  2633. // Somewhat the same array as above, but use > instead of >= to get
  2634. // the end position right.
  2635. while (i !== end && matchIdx > iIndex + bidiTexts[i].str.length) {
  2636. iIndex += bidiTexts[i].str.length;
  2637. i++;
  2638. }
  2639. match.end = {
  2640. divIdx: i,
  2641. offset: matchIdx - iIndex
  2642. };
  2643. ret.push(match);
  2644. }
  2645. return ret;
  2646. },
  2647. renderMatches: function TextLayerBuilder_renderMatches(matches) {
  2648. // Early exit if there is nothing to render.
  2649. if (matches.length === 0) {
  2650. return;
  2651. }
  2652. var bidiTexts = this.textContent.items;
  2653. var textDivs = this.textDivs;
  2654. var prevEnd = null;
  2655. var pageIdx = this.pageIdx;
  2656. var isSelectedPage = this.findController === null ? false : pageIdx === this.findController.selected.pageIdx;
  2657. var selectedMatchIdx = this.findController === null ? -1 : this.findController.selected.matchIdx;
  2658. var highlightAll = this.findController === null ? false : this.findController.state.highlightAll;
  2659. var infinity = {
  2660. divIdx: -1,
  2661. offset: undefined
  2662. };
  2663. function beginText(begin, className) {
  2664. var divIdx = begin.divIdx;
  2665. textDivs[divIdx].textContent = '';
  2666. appendTextToDiv(divIdx, 0, begin.offset, className);
  2667. }
  2668. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  2669. var div = textDivs[divIdx];
  2670. var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
  2671. var node = document.createTextNode(content);
  2672. if (className) {
  2673. var span = document.createElement('span');
  2674. span.className = className;
  2675. span.appendChild(node);
  2676. div.appendChild(span);
  2677. return;
  2678. }
  2679. div.appendChild(node);
  2680. }
  2681. var i0 = selectedMatchIdx, i1 = i0 + 1;
  2682. if (highlightAll) {
  2683. i0 = 0;
  2684. i1 = matches.length;
  2685. } else if (!isSelectedPage) {
  2686. // Not highlighting all and this isn't the selected page, so do nothing.
  2687. return;
  2688. }
  2689. for (var i = i0; i < i1; i++) {
  2690. var match = matches[i];
  2691. var begin = match.begin;
  2692. var end = match.end;
  2693. var isSelected = isSelectedPage && i === selectedMatchIdx;
  2694. var highlightSuffix = isSelected ? ' selected' : '';
  2695. if (this.findController) {
  2696. this.findController.updateMatchPosition(pageIdx, i, textDivs, begin.divIdx);
  2697. }
  2698. // Match inside new div.
  2699. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  2700. // If there was a previous div, then add the text at the end.
  2701. if (prevEnd !== null) {
  2702. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  2703. }
  2704. // Clear the divs and set the content until the starting point.
  2705. beginText(begin);
  2706. } else {
  2707. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  2708. }
  2709. if (begin.divIdx === end.divIdx) {
  2710. appendTextToDiv(begin.divIdx, begin.offset, end.offset, 'highlight' + highlightSuffix);
  2711. } else {
  2712. appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, 'highlight begin' + highlightSuffix);
  2713. for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  2714. textDivs[n0].className = 'highlight middle' + highlightSuffix;
  2715. }
  2716. beginText(end, 'highlight end' + highlightSuffix);
  2717. }
  2718. prevEnd = end;
  2719. }
  2720. if (prevEnd) {
  2721. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  2722. }
  2723. },
  2724. updateMatches: function TextLayerBuilder_updateMatches() {
  2725. // Only show matches when all rendering is done.
  2726. if (!this.renderingDone) {
  2727. return;
  2728. }
  2729. // Clear all matches.
  2730. var matches = this.matches;
  2731. var textDivs = this.textDivs;
  2732. var bidiTexts = this.textContent.items;
  2733. var clearedUntilDivIdx = -1;
  2734. // Clear all current matches.
  2735. for (var i = 0, len = matches.length; i < len; i++) {
  2736. var match = matches[i];
  2737. var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  2738. for (var n = begin, end = match.end.divIdx; n <= end; n++) {
  2739. var div = textDivs[n];
  2740. div.textContent = bidiTexts[n].str;
  2741. div.className = '';
  2742. }
  2743. clearedUntilDivIdx = match.end.divIdx + 1;
  2744. }
  2745. if (this.findController === null || !this.findController.active) {
  2746. return;
  2747. }
  2748. // Convert the matches on the page controller into the match format
  2749. // used for the textLayer.
  2750. var pageMatches, pageMatchesLength;
  2751. if (this.findController !== null) {
  2752. pageMatches = this.findController.pageMatches[this.pageIdx] || null;
  2753. pageMatchesLength = this.findController.pageMatchesLength ? this.findController.pageMatchesLength[this.pageIdx] || null : null;
  2754. }
  2755. this.matches = this.convertMatches(pageMatches, pageMatchesLength);
  2756. this.renderMatches(this.matches);
  2757. },
  2758. /**
  2759. * Fixes text selection: adds additional div where mouse was clicked.
  2760. * This reduces flickering of the content if mouse slowly dragged down/up.
  2761. * @private
  2762. */
  2763. _bindMouse: function TextLayerBuilder_bindMouse() {
  2764. var div = this.textLayerDiv;
  2765. var self = this;
  2766. var expandDivsTimer = null;
  2767. div.addEventListener('mousedown', function (e) {
  2768. if (self.enhanceTextSelection && self.textLayerRenderTask) {
  2769. self.textLayerRenderTask.expandTextDivs(true);
  2770. if (expandDivsTimer) {
  2771. clearTimeout(expandDivsTimer);
  2772. expandDivsTimer = null;
  2773. }
  2774. return;
  2775. }
  2776. var end = div.querySelector('.endOfContent');
  2777. if (!end) {
  2778. return;
  2779. }
  2780. // On non-Firefox browsers, the selection will feel better if the height
  2781. // of the endOfContent div will be adjusted to start at mouse click
  2782. // location -- this will avoid flickering when selections moves up.
  2783. // However it does not work when selection started on empty space.
  2784. var adjustTop = e.target !== div;
  2785. adjustTop = adjustTop && window.getComputedStyle(end).getPropertyValue('-moz-user-select') !== 'none';
  2786. if (adjustTop) {
  2787. var divBounds = div.getBoundingClientRect();
  2788. var r = Math.max(0, (e.pageY - divBounds.top) / divBounds.height);
  2789. end.style.top = (r * 100).toFixed(2) + '%';
  2790. }
  2791. end.classList.add('active');
  2792. });
  2793. div.addEventListener('mouseup', function (e) {
  2794. if (self.enhanceTextSelection && self.textLayerRenderTask) {
  2795. expandDivsTimer = setTimeout(function () {
  2796. if (self.textLayerRenderTask) {
  2797. self.textLayerRenderTask.expandTextDivs(false);
  2798. }
  2799. expandDivsTimer = null;
  2800. }, EXPAND_DIVS_TIMEOUT);
  2801. return;
  2802. }
  2803. var end = div.querySelector('.endOfContent');
  2804. if (!end) {
  2805. return;
  2806. }
  2807. end.style.top = '';
  2808. end.classList.remove('active');
  2809. });
  2810. }
  2811. };
  2812. return TextLayerBuilder;
  2813. }();
  2814. /**
  2815. * @constructor
  2816. * @implements IPDFTextLayerFactory
  2817. */
  2818. function DefaultTextLayerFactory() {
  2819. }
  2820. DefaultTextLayerFactory.prototype = {
  2821. /**
  2822. * @param {HTMLDivElement} textLayerDiv
  2823. * @param {number} pageIndex
  2824. * @param {PageViewport} viewport
  2825. * @param {boolean} enhanceTextSelection
  2826. * @returns {TextLayerBuilder}
  2827. */
  2828. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport, enhanceTextSelection) {
  2829. return new TextLayerBuilder({
  2830. textLayerDiv: textLayerDiv,
  2831. pageIndex: pageIndex,
  2832. viewport: viewport,
  2833. enhanceTextSelection: enhanceTextSelection
  2834. });
  2835. }
  2836. };
  2837. exports.TextLayerBuilder = TextLayerBuilder;
  2838. exports.DefaultTextLayerFactory = DefaultTextLayerFactory;
  2839. }));
  2840. (function (root, factory) {
  2841. factory(root.pdfjsWebAnnotationLayerBuilder = {}, root.pdfjsWebUIUtils, root.pdfjsWebPDFLinkService, root.pdfjsWebPDFJS);
  2842. }(this, function (exports, uiUtils, pdfLinkService, pdfjsLib) {
  2843. var mozL10n = uiUtils.mozL10n;
  2844. var SimpleLinkService = pdfLinkService.SimpleLinkService;
  2845. /**
  2846. * @typedef {Object} AnnotationLayerBuilderOptions
  2847. * @property {HTMLDivElement} pageDiv
  2848. * @property {PDFPage} pdfPage
  2849. * @property {boolean} renderInteractiveForms
  2850. * @property {IPDFLinkService} linkService
  2851. * @property {DownloadManager} downloadManager
  2852. */
  2853. /**
  2854. * @class
  2855. */
  2856. var AnnotationLayerBuilder = function AnnotationLayerBuilderClosure() {
  2857. /**
  2858. * @param {AnnotationLayerBuilderOptions} options
  2859. * @constructs AnnotationLayerBuilder
  2860. */
  2861. function AnnotationLayerBuilder(options) {
  2862. this.pageDiv = options.pageDiv;
  2863. this.pdfPage = options.pdfPage;
  2864. this.renderInteractiveForms = options.renderInteractiveForms;
  2865. this.linkService = options.linkService;
  2866. this.downloadManager = options.downloadManager;
  2867. this.div = null;
  2868. }
  2869. AnnotationLayerBuilder.prototype = /** @lends AnnotationLayerBuilder.prototype */
  2870. {
  2871. /**
  2872. * @param {PageViewport} viewport
  2873. * @param {string} intent (default value is 'display')
  2874. */
  2875. render: function AnnotationLayerBuilder_render(viewport, intent) {
  2876. var self = this;
  2877. var parameters = { intent: intent === undefined ? 'display' : intent };
  2878. this.pdfPage.getAnnotations(parameters).then(function (annotations) {
  2879. viewport = viewport.clone({ dontFlip: true });
  2880. parameters = {
  2881. viewport: viewport,
  2882. div: self.div,
  2883. annotations: annotations,
  2884. page: self.pdfPage,
  2885. renderInteractiveForms: self.renderInteractiveForms,
  2886. linkService: self.linkService,
  2887. downloadManager: self.downloadManager
  2888. };
  2889. if (self.div) {
  2890. // If an annotationLayer already exists, refresh its children's
  2891. // transformation matrices.
  2892. pdfjsLib.AnnotationLayer.update(parameters);
  2893. } else {
  2894. // Create an annotation layer div and render the annotations
  2895. // if there is at least one annotation.
  2896. if (annotations.length === 0) {
  2897. return;
  2898. }
  2899. self.div = document.createElement('div');
  2900. self.div.className = 'annotationLayer';
  2901. self.pageDiv.appendChild(self.div);
  2902. parameters.div = self.div;
  2903. pdfjsLib.AnnotationLayer.render(parameters);
  2904. if (typeof mozL10n !== 'undefined') {
  2905. mozL10n.translate(self.div);
  2906. }
  2907. }
  2908. });
  2909. },
  2910. hide: function AnnotationLayerBuilder_hide() {
  2911. if (!this.div) {
  2912. return;
  2913. }
  2914. this.div.setAttribute('hidden', 'true');
  2915. }
  2916. };
  2917. return AnnotationLayerBuilder;
  2918. }();
  2919. /**
  2920. * @constructor
  2921. * @implements IPDFAnnotationLayerFactory
  2922. */
  2923. function DefaultAnnotationLayerFactory() {
  2924. }
  2925. DefaultAnnotationLayerFactory.prototype = {
  2926. /**
  2927. * @param {HTMLDivElement} pageDiv
  2928. * @param {PDFPage} pdfPage
  2929. * @param {boolean} renderInteractiveForms
  2930. * @returns {AnnotationLayerBuilder}
  2931. */
  2932. createAnnotationLayerBuilder: function (pageDiv, pdfPage, renderInteractiveForms) {
  2933. return new AnnotationLayerBuilder({
  2934. pageDiv: pageDiv,
  2935. pdfPage: pdfPage,
  2936. renderInteractiveForms: renderInteractiveForms,
  2937. linkService: new SimpleLinkService()
  2938. });
  2939. }
  2940. };
  2941. exports.AnnotationLayerBuilder = AnnotationLayerBuilder;
  2942. exports.DefaultAnnotationLayerFactory = DefaultAnnotationLayerFactory;
  2943. }));
  2944. (function (root, factory) {
  2945. factory(root.pdfjsWebPDFViewer = {}, root.pdfjsWebUIUtils, root.pdfjsWebPDFPageView, root.pdfjsWebPDFRenderingQueue, root.pdfjsWebTextLayerBuilder, root.pdfjsWebAnnotationLayerBuilder, root.pdfjsWebPDFLinkService, root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS);
  2946. }(this, function (exports, uiUtils, pdfPageView, pdfRenderingQueue, textLayerBuilder, annotationLayerBuilder, pdfLinkService, domEvents, pdfjsLib) {
  2947. var UNKNOWN_SCALE = uiUtils.UNKNOWN_SCALE;
  2948. var SCROLLBAR_PADDING = uiUtils.SCROLLBAR_PADDING;
  2949. var VERTICAL_PADDING = uiUtils.VERTICAL_PADDING;
  2950. var MAX_AUTO_SCALE = uiUtils.MAX_AUTO_SCALE;
  2951. var CSS_UNITS = uiUtils.CSS_UNITS;
  2952. var DEFAULT_SCALE = uiUtils.DEFAULT_SCALE;
  2953. var DEFAULT_SCALE_VALUE = uiUtils.DEFAULT_SCALE_VALUE;
  2954. var scrollIntoView = uiUtils.scrollIntoView;
  2955. var watchScroll = uiUtils.watchScroll;
  2956. var getVisibleElements = uiUtils.getVisibleElements;
  2957. var PDFPageView = pdfPageView.PDFPageView;
  2958. var RenderingStates = pdfRenderingQueue.RenderingStates;
  2959. var PDFRenderingQueue = pdfRenderingQueue.PDFRenderingQueue;
  2960. var TextLayerBuilder = textLayerBuilder.TextLayerBuilder;
  2961. var AnnotationLayerBuilder = annotationLayerBuilder.AnnotationLayerBuilder;
  2962. var SimpleLinkService = pdfLinkService.SimpleLinkService;
  2963. var PresentationModeState = {
  2964. UNKNOWN: 0,
  2965. NORMAL: 1,
  2966. CHANGING: 2,
  2967. FULLSCREEN: 3
  2968. };
  2969. var DEFAULT_CACHE_SIZE = 10;
  2970. /**
  2971. * @typedef {Object} PDFViewerOptions
  2972. * @property {HTMLDivElement} container - The container for the viewer element.
  2973. * @property {HTMLDivElement} viewer - (optional) The viewer element.
  2974. * @property {EventBus} eventBus - The application event bus.
  2975. * @property {IPDFLinkService} linkService - The navigation/linking service.
  2976. * @property {DownloadManager} downloadManager - (optional) The download
  2977. * manager component.
  2978. * @property {PDFRenderingQueue} renderingQueue - (optional) The rendering
  2979. * queue object.
  2980. * @property {boolean} removePageBorders - (optional) Removes the border shadow
  2981. * around the pages. The default is false.
  2982. * @property {boolean} enhanceTextSelection - (optional) Enables the improved
  2983. * text selection behaviour. The default is `false`.
  2984. * @property {boolean} renderInteractiveForms - (optional) Enables rendering of
  2985. * interactive form elements. The default is `false`.
  2986. */
  2987. /**
  2988. * Simple viewer control to display PDF content/pages.
  2989. * @class
  2990. * @implements {IRenderableView}
  2991. */
  2992. var PDFViewer = function pdfViewer() {
  2993. function PDFPageViewBuffer(size) {
  2994. var data = [];
  2995. this.push = function cachePush(view) {
  2996. var i = data.indexOf(view);
  2997. if (i >= 0) {
  2998. data.splice(i, 1);
  2999. }
  3000. data.push(view);
  3001. if (data.length > size) {
  3002. data.shift().destroy();
  3003. }
  3004. };
  3005. this.resize = function (newSize) {
  3006. size = newSize;
  3007. while (data.length > size) {
  3008. data.shift().destroy();
  3009. }
  3010. };
  3011. }
  3012. function isSameScale(oldScale, newScale) {
  3013. if (newScale === oldScale) {
  3014. return true;
  3015. }
  3016. if (Math.abs(newScale - oldScale) < 1e-15) {
  3017. // Prevent unnecessary re-rendering of all pages when the scale
  3018. // changes only because of limited numerical precision.
  3019. return true;
  3020. }
  3021. return false;
  3022. }
  3023. /**
  3024. * @constructs PDFViewer
  3025. * @param {PDFViewerOptions} options
  3026. */
  3027. function PDFViewer(options) {
  3028. this.container = options.container;
  3029. this.viewer = options.viewer || options.container.firstElementChild;
  3030. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  3031. this.linkService = options.linkService || new SimpleLinkService();
  3032. this.downloadManager = options.downloadManager || null;
  3033. this.removePageBorders = options.removePageBorders || false;
  3034. this.enhanceTextSelection = options.enhanceTextSelection || false;
  3035. this.renderInteractiveForms = options.renderInteractiveForms || false;
  3036. this.defaultRenderingQueue = !options.renderingQueue;
  3037. if (this.defaultRenderingQueue) {
  3038. // Custom rendering queue is not specified, using default one
  3039. this.renderingQueue = new PDFRenderingQueue();
  3040. this.renderingQueue.setViewer(this);
  3041. } else {
  3042. this.renderingQueue = options.renderingQueue;
  3043. }
  3044. this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this));
  3045. this.presentationModeState = PresentationModeState.UNKNOWN;
  3046. this._resetView();
  3047. if (this.removePageBorders) {
  3048. this.viewer.classList.add('removePageBorders');
  3049. }
  3050. }
  3051. PDFViewer.prototype = /** @lends PDFViewer.prototype */
  3052. {
  3053. get pagesCount() {
  3054. return this._pages.length;
  3055. },
  3056. getPageView: function (index) {
  3057. return this._pages[index];
  3058. },
  3059. /**
  3060. * @returns {boolean} true if all {PDFPageView} objects are initialized.
  3061. */
  3062. get pageViewsReady() {
  3063. return this._pageViewsReady;
  3064. },
  3065. /**
  3066. * @returns {number}
  3067. */
  3068. get currentPageNumber() {
  3069. return this._currentPageNumber;
  3070. },
  3071. /**
  3072. * @param {number} val - The page number.
  3073. */
  3074. set currentPageNumber(val) {
  3075. if ((val | 0) !== val) {
  3076. // Ensure that `val` is an integer.
  3077. throw new Error('Invalid page number.');
  3078. }
  3079. if (!this.pdfDocument) {
  3080. this._currentPageNumber = val;
  3081. return;
  3082. }
  3083. // The intent can be to just reset a scroll position and/or scale.
  3084. this._setCurrentPageNumber(val, /* resetCurrentPageView = */
  3085. true);
  3086. },
  3087. /**
  3088. * @private
  3089. */
  3090. _setCurrentPageNumber: function PDFViewer_setCurrentPageNumber(val, resetCurrentPageView) {
  3091. if (this._currentPageNumber === val) {
  3092. if (resetCurrentPageView) {
  3093. this._resetCurrentPageView();
  3094. }
  3095. return;
  3096. }
  3097. if (!(0 < val && val <= this.pagesCount)) {
  3098. console.error('PDFViewer_setCurrentPageNumber: "' + val + '" is out of bounds.');
  3099. return;
  3100. }
  3101. var arg = {
  3102. source: this,
  3103. pageNumber: val
  3104. };
  3105. this._currentPageNumber = val;
  3106. this.eventBus.dispatch('pagechanging', arg);
  3107. this.eventBus.dispatch('pagechange', arg);
  3108. if (resetCurrentPageView) {
  3109. this._resetCurrentPageView();
  3110. }
  3111. },
  3112. /**
  3113. * @returns {number}
  3114. */
  3115. get currentScale() {
  3116. return this._currentScale !== UNKNOWN_SCALE ? this._currentScale : DEFAULT_SCALE;
  3117. },
  3118. /**
  3119. * @param {number} val - Scale of the pages in percents.
  3120. */
  3121. set currentScale(val) {
  3122. if (isNaN(val)) {
  3123. throw new Error('Invalid numeric scale');
  3124. }
  3125. if (!this.pdfDocument) {
  3126. this._currentScale = val;
  3127. this._currentScaleValue = val !== UNKNOWN_SCALE ? val.toString() : null;
  3128. return;
  3129. }
  3130. this._setScale(val, false);
  3131. },
  3132. /**
  3133. * @returns {string}
  3134. */
  3135. get currentScaleValue() {
  3136. return this._currentScaleValue;
  3137. },
  3138. /**
  3139. * @param val - The scale of the pages (in percent or predefined value).
  3140. */
  3141. set currentScaleValue(val) {
  3142. if (!this.pdfDocument) {
  3143. this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val;
  3144. this._currentScaleValue = val.toString();
  3145. return;
  3146. }
  3147. this._setScale(val, false);
  3148. },
  3149. /**
  3150. * @returns {number}
  3151. */
  3152. get pagesRotation() {
  3153. return this._pagesRotation;
  3154. },
  3155. /**
  3156. * @param {number} rotation - The rotation of the pages (0, 90, 180, 270).
  3157. */
  3158. set pagesRotation(rotation) {
  3159. if (!(typeof rotation === 'number' && rotation % 90 === 0)) {
  3160. throw new Error('Invalid pages rotation angle.');
  3161. }
  3162. this._pagesRotation = rotation;
  3163. if (!this.pdfDocument) {
  3164. return;
  3165. }
  3166. for (var i = 0, l = this._pages.length; i < l; i++) {
  3167. var pageView = this._pages[i];
  3168. pageView.update(pageView.scale, rotation);
  3169. }
  3170. this._setScale(this._currentScaleValue, true);
  3171. if (this.defaultRenderingQueue) {
  3172. this.update();
  3173. }
  3174. },
  3175. /**
  3176. * @param pdfDocument {PDFDocument}
  3177. */
  3178. setDocument: function (pdfDocument) {
  3179. if (this.pdfDocument) {
  3180. this._cancelRendering();
  3181. this._resetView();
  3182. }
  3183. this.pdfDocument = pdfDocument;
  3184. if (!pdfDocument) {
  3185. return;
  3186. }
  3187. var pagesCount = pdfDocument.numPages;
  3188. var self = this;
  3189. var resolvePagesPromise;
  3190. var pagesPromise = new Promise(function (resolve) {
  3191. resolvePagesPromise = resolve;
  3192. });
  3193. this.pagesPromise = pagesPromise;
  3194. pagesPromise.then(function () {
  3195. self._pageViewsReady = true;
  3196. self.eventBus.dispatch('pagesloaded', {
  3197. source: self,
  3198. pagesCount: pagesCount
  3199. });
  3200. });
  3201. var isOnePageRenderedResolved = false;
  3202. var resolveOnePageRendered = null;
  3203. var onePageRendered = new Promise(function (resolve) {
  3204. resolveOnePageRendered = resolve;
  3205. });
  3206. this.onePageRendered = onePageRendered;
  3207. var bindOnAfterAndBeforeDraw = function (pageView) {
  3208. pageView.onBeforeDraw = function pdfViewLoadOnBeforeDraw() {
  3209. // Add the page to the buffer at the start of drawing. That way it can
  3210. // be evicted from the buffer and destroyed even if we pause its
  3211. // rendering.
  3212. self._buffer.push(this);
  3213. };
  3214. pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {
  3215. if (!isOnePageRenderedResolved) {
  3216. isOnePageRenderedResolved = true;
  3217. resolveOnePageRendered();
  3218. }
  3219. };
  3220. };
  3221. var firstPagePromise = pdfDocument.getPage(1);
  3222. this.firstPagePromise = firstPagePromise;
  3223. // Fetch a single page so we can get a viewport that will be the default
  3224. // viewport for all pages
  3225. return firstPagePromise.then(function (pdfPage) {
  3226. var scale = this.currentScale;
  3227. var viewport = pdfPage.getViewport(scale * CSS_UNITS);
  3228. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  3229. var textLayerFactory = null;
  3230. if (!pdfjsLib.PDFJS.disableTextLayer) {
  3231. textLayerFactory = this;
  3232. }
  3233. var pageView = new PDFPageView({
  3234. container: this.viewer,
  3235. eventBus: this.eventBus,
  3236. id: pageNum,
  3237. scale: scale,
  3238. defaultViewport: viewport.clone(),
  3239. renderingQueue: this.renderingQueue,
  3240. textLayerFactory: textLayerFactory,
  3241. annotationLayerFactory: this,
  3242. enhanceTextSelection: this.enhanceTextSelection,
  3243. renderInteractiveForms: this.renderInteractiveForms
  3244. });
  3245. bindOnAfterAndBeforeDraw(pageView);
  3246. this._pages.push(pageView);
  3247. }
  3248. var linkService = this.linkService;
  3249. // Fetch all the pages since the viewport is needed before printing
  3250. // starts to create the correct size canvas. Wait until one page is
  3251. // rendered so we don't tie up too many resources early on.
  3252. onePageRendered.then(function () {
  3253. if (!pdfjsLib.PDFJS.disableAutoFetch) {
  3254. var getPagesLeft = pagesCount;
  3255. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  3256. pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) {
  3257. var pageView = self._pages[pageNum - 1];
  3258. if (!pageView.pdfPage) {
  3259. pageView.setPdfPage(pdfPage);
  3260. }
  3261. linkService.cachePageRef(pageNum, pdfPage.ref);
  3262. getPagesLeft--;
  3263. if (!getPagesLeft) {
  3264. resolvePagesPromise();
  3265. }
  3266. }.bind(null, pageNum));
  3267. }
  3268. } else {
  3269. // XXX: Printing is semi-broken with auto fetch disabled.
  3270. resolvePagesPromise();
  3271. }
  3272. });
  3273. self.eventBus.dispatch('pagesinit', { source: self });
  3274. if (this.defaultRenderingQueue) {
  3275. this.update();
  3276. }
  3277. if (this.findController) {
  3278. this.findController.resolveFirstPage();
  3279. }
  3280. }.bind(this));
  3281. },
  3282. _resetView: function () {
  3283. this._pages = [];
  3284. this._currentPageNumber = 1;
  3285. this._currentScale = UNKNOWN_SCALE;
  3286. this._currentScaleValue = null;
  3287. this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
  3288. this._location = null;
  3289. this._pagesRotation = 0;
  3290. this._pagesRequests = [];
  3291. this._pageViewsReady = false;
  3292. // Remove the pages from the DOM.
  3293. this.viewer.textContent = '';
  3294. },
  3295. _scrollUpdate: function PDFViewer_scrollUpdate() {
  3296. if (this.pagesCount === 0) {
  3297. return;
  3298. }
  3299. this.update();
  3300. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  3301. this._pages[i].updatePosition();
  3302. }
  3303. },
  3304. _setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent(newScale, newValue, preset) {
  3305. var arg = {
  3306. source: this,
  3307. scale: newScale,
  3308. presetValue: preset ? newValue : undefined
  3309. };
  3310. this.eventBus.dispatch('scalechanging', arg);
  3311. this.eventBus.dispatch('scalechange', arg);
  3312. },
  3313. _setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(newScale, newValue, noScroll, preset) {
  3314. this._currentScaleValue = newValue.toString();
  3315. if (isSameScale(this._currentScale, newScale)) {
  3316. if (preset) {
  3317. this._setScaleDispatchEvent(newScale, newValue, true);
  3318. }
  3319. return;
  3320. }
  3321. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  3322. this._pages[i].update(newScale);
  3323. }
  3324. this._currentScale = newScale;
  3325. if (!noScroll) {
  3326. var page = this._currentPageNumber, dest;
  3327. if (this._location && !pdfjsLib.PDFJS.ignoreCurrentPositionOnZoom && !(this.isInPresentationMode || this.isChangingPresentationMode)) {
  3328. page = this._location.pageNumber;
  3329. dest = [
  3330. null,
  3331. { name: 'XYZ' },
  3332. this._location.left,
  3333. this._location.top,
  3334. null
  3335. ];
  3336. }
  3337. this.scrollPageIntoView({
  3338. pageNumber: page,
  3339. destArray: dest,
  3340. allowNegativeOffset: true
  3341. });
  3342. }
  3343. this._setScaleDispatchEvent(newScale, newValue, preset);
  3344. if (this.defaultRenderingQueue) {
  3345. this.update();
  3346. }
  3347. },
  3348. _setScale: function PDFViewer_setScale(value, noScroll) {
  3349. var scale = parseFloat(value);
  3350. if (scale > 0) {
  3351. this._setScaleUpdatePages(scale, value, noScroll, false);
  3352. } else {
  3353. var currentPage = this._pages[this._currentPageNumber - 1];
  3354. if (!currentPage) {
  3355. return;
  3356. }
  3357. var hPadding = this.isInPresentationMode || this.removePageBorders ? 0 : SCROLLBAR_PADDING;
  3358. var vPadding = this.isInPresentationMode || this.removePageBorders ? 0 : VERTICAL_PADDING;
  3359. var pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale;
  3360. var pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale;
  3361. switch (value) {
  3362. case 'page-actual':
  3363. scale = 1;
  3364. break;
  3365. case 'page-width':
  3366. scale = pageWidthScale;
  3367. break;
  3368. case 'page-height':
  3369. scale = pageHeightScale;
  3370. break;
  3371. case 'page-fit':
  3372. scale = Math.min(pageWidthScale, pageHeightScale);
  3373. break;
  3374. case 'auto':
  3375. var isLandscape = currentPage.width > currentPage.height;
  3376. // For pages in landscape mode, fit the page height to the viewer
  3377. // *unless* the page would thus become too wide to fit horizontally.
  3378. var horizontalScale = isLandscape ? Math.min(pageHeightScale, pageWidthScale) : pageWidthScale;
  3379. scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
  3380. break;
  3381. default:
  3382. console.error('PDFViewer_setScale: "' + value + '" is an unknown zoom value.');
  3383. return;
  3384. }
  3385. this._setScaleUpdatePages(scale, value, noScroll, true);
  3386. }
  3387. },
  3388. /**
  3389. * Refreshes page view: scrolls to the current page and updates the scale.
  3390. * @private
  3391. */
  3392. _resetCurrentPageView: function () {
  3393. if (this.isInPresentationMode) {
  3394. // Fixes the case when PDF has different page sizes.
  3395. this._setScale(this._currentScaleValue, true);
  3396. }
  3397. var pageView = this._pages[this._currentPageNumber - 1];
  3398. scrollIntoView(pageView.div);
  3399. },
  3400. /**
  3401. * @typedef ScrollPageIntoViewParameters
  3402. * @property {number} pageNumber - The page number.
  3403. * @property {Array} destArray - (optional) The original PDF destination
  3404. * array, in the format: <page-ref> </XYZ|/FitXXX> <args..>
  3405. * @property {boolean} allowNegativeOffset - (optional) Allow negative page
  3406. * offsets. The default value is `false`.
  3407. */
  3408. /**
  3409. * Scrolls page into view.
  3410. * @param {ScrollPageIntoViewParameters} params
  3411. */
  3412. scrollPageIntoView: function PDFViewer_scrollPageIntoView(params) {
  3413. if (!this.pdfDocument) {
  3414. return;
  3415. }
  3416. if (arguments.length > 1 || typeof params === 'number') {
  3417. console.warn('Call of scrollPageIntoView() with obsolete signature.');
  3418. var paramObj = {};
  3419. if (typeof params === 'number') {
  3420. paramObj.pageNumber = params;
  3421. }
  3422. // pageNumber argument was found.
  3423. if (arguments[1] instanceof Array) {
  3424. paramObj.destArray = arguments[1];
  3425. }
  3426. // destArray argument was found.
  3427. params = paramObj;
  3428. }
  3429. var pageNumber = params.pageNumber || 0;
  3430. var dest = params.destArray || null;
  3431. var allowNegativeOffset = params.allowNegativeOffset || false;
  3432. if (this.isInPresentationMode || !dest) {
  3433. this._setCurrentPageNumber(pageNumber, /* resetCurrentPageView */
  3434. true);
  3435. return;
  3436. }
  3437. var pageView = this._pages[pageNumber - 1];
  3438. if (!pageView) {
  3439. console.error('PDFViewer_scrollPageIntoView: ' + 'Invalid "pageNumber" parameter.');
  3440. return;
  3441. }
  3442. var x = 0, y = 0;
  3443. var width = 0, height = 0, widthScale, heightScale;
  3444. var changeOrientation = pageView.rotation % 180 === 0 ? false : true;
  3445. var pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / CSS_UNITS;
  3446. var pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / CSS_UNITS;
  3447. var scale = 0;
  3448. switch (dest[1].name) {
  3449. case 'XYZ':
  3450. x = dest[2];
  3451. y = dest[3];
  3452. scale = dest[4];
  3453. // If x and/or y coordinates are not supplied, default to
  3454. // _top_ left of the page (not the obvious bottom left,
  3455. // since aligning the bottom of the intended page with the
  3456. // top of the window is rarely helpful).
  3457. x = x !== null ? x : 0;
  3458. y = y !== null ? y : pageHeight;
  3459. break;
  3460. case 'Fit':
  3461. case 'FitB':
  3462. scale = 'page-fit';
  3463. break;
  3464. case 'FitH':
  3465. case 'FitBH':
  3466. y = dest[2];
  3467. scale = 'page-width';
  3468. // According to the PDF spec, section 12.3.2.2, a `null` value in the
  3469. // parameter should maintain the position relative to the new page.
  3470. if (y === null && this._location) {
  3471. x = this._location.left;
  3472. y = this._location.top;
  3473. }
  3474. break;
  3475. case 'FitV':
  3476. case 'FitBV':
  3477. x = dest[2];
  3478. width = pageWidth;
  3479. height = pageHeight;
  3480. scale = 'page-height';
  3481. break;
  3482. case 'FitR':
  3483. x = dest[2];
  3484. y = dest[3];
  3485. width = dest[4] - x;
  3486. height = dest[5] - y;
  3487. var hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING;
  3488. var vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING;
  3489. widthScale = (this.container.clientWidth - hPadding) / width / CSS_UNITS;
  3490. heightScale = (this.container.clientHeight - vPadding) / height / CSS_UNITS;
  3491. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  3492. break;
  3493. default:
  3494. console.error('PDFViewer_scrollPageIntoView: \'' + dest[1].name + '\' is not a valid destination type.');
  3495. return;
  3496. }
  3497. if (scale && scale !== this._currentScale) {
  3498. this.currentScaleValue = scale;
  3499. } else if (this._currentScale === UNKNOWN_SCALE) {
  3500. this.currentScaleValue = DEFAULT_SCALE_VALUE;
  3501. }
  3502. if (scale === 'page-fit' && !dest[4]) {
  3503. scrollIntoView(pageView.div);
  3504. return;
  3505. }
  3506. var boundingRect = [
  3507. pageView.viewport.convertToViewportPoint(x, y),
  3508. pageView.viewport.convertToViewportPoint(x + width, y + height)
  3509. ];
  3510. var left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  3511. var top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  3512. if (!allowNegativeOffset) {
  3513. // Some bad PDF generators will create destinations with e.g. top values
  3514. // that exceeds the page height. Ensure that offsets are not negative,
  3515. // to prevent a previous page from becoming visible (fixes bug 874482).
  3516. left = Math.max(left, 0);
  3517. top = Math.max(top, 0);
  3518. }
  3519. scrollIntoView(pageView.div, {
  3520. left: left,
  3521. top: top
  3522. });
  3523. },
  3524. _updateLocation: function (firstPage) {
  3525. var currentScale = this._currentScale;
  3526. var currentScaleValue = this._currentScaleValue;
  3527. var normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue;
  3528. var pageNumber = firstPage.id;
  3529. var pdfOpenParams = '#page=' + pageNumber;
  3530. pdfOpenParams += '&zoom=' + normalizedScaleValue;
  3531. var currentPageView = this._pages[pageNumber - 1];
  3532. var container = this.container;
  3533. var topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y);
  3534. var intLeft = Math.round(topLeft[0]);
  3535. var intTop = Math.round(topLeft[1]);
  3536. pdfOpenParams += ',' + intLeft + ',' + intTop;
  3537. this._location = {
  3538. pageNumber: pageNumber,
  3539. scale: normalizedScaleValue,
  3540. top: intTop,
  3541. left: intLeft,
  3542. pdfOpenParams: pdfOpenParams
  3543. };
  3544. },
  3545. update: function PDFViewer_update() {
  3546. var visible = this._getVisiblePages();
  3547. var visiblePages = visible.views;
  3548. if (visiblePages.length === 0) {
  3549. return;
  3550. }
  3551. var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * visiblePages.length + 1);
  3552. this._buffer.resize(suggestedCacheSize);
  3553. this.renderingQueue.renderHighestPriority(visible);
  3554. var currentId = this._currentPageNumber;
  3555. var firstPage = visible.first;
  3556. for (var i = 0, ii = visiblePages.length, stillFullyVisible = false; i < ii; ++i) {
  3557. var page = visiblePages[i];
  3558. if (page.percent < 100) {
  3559. break;
  3560. }
  3561. if (page.id === currentId) {
  3562. stillFullyVisible = true;
  3563. break;
  3564. }
  3565. }
  3566. if (!stillFullyVisible) {
  3567. currentId = visiblePages[0].id;
  3568. }
  3569. if (!this.isInPresentationMode) {
  3570. this._setCurrentPageNumber(currentId);
  3571. }
  3572. this._updateLocation(firstPage);
  3573. this.eventBus.dispatch('updateviewarea', {
  3574. source: this,
  3575. location: this._location
  3576. });
  3577. },
  3578. containsElement: function (element) {
  3579. return this.container.contains(element);
  3580. },
  3581. focus: function () {
  3582. this.container.focus();
  3583. },
  3584. get isInPresentationMode() {
  3585. return this.presentationModeState === PresentationModeState.FULLSCREEN;
  3586. },
  3587. get isChangingPresentationMode() {
  3588. return this.presentationModeState === PresentationModeState.CHANGING;
  3589. },
  3590. get isHorizontalScrollbarEnabled() {
  3591. return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth;
  3592. },
  3593. _getVisiblePages: function () {
  3594. if (!this.isInPresentationMode) {
  3595. return getVisibleElements(this.container, this._pages, true);
  3596. } else {
  3597. // The algorithm in getVisibleElements doesn't work in all browsers and
  3598. // configurations when presentation mode is active.
  3599. var visible = [];
  3600. var currentPage = this._pages[this._currentPageNumber - 1];
  3601. visible.push({
  3602. id: currentPage.id,
  3603. view: currentPage
  3604. });
  3605. return {
  3606. first: currentPage,
  3607. last: currentPage,
  3608. views: visible
  3609. };
  3610. }
  3611. },
  3612. cleanup: function () {
  3613. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  3614. if (this._pages[i] && this._pages[i].renderingState !== RenderingStates.FINISHED) {
  3615. this._pages[i].reset();
  3616. }
  3617. }
  3618. },
  3619. /**
  3620. * @private
  3621. */
  3622. _cancelRendering: function PDFViewer_cancelRendering() {
  3623. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  3624. if (this._pages[i]) {
  3625. this._pages[i].cancelRendering();
  3626. }
  3627. }
  3628. },
  3629. /**
  3630. * @param {PDFPageView} pageView
  3631. * @returns {PDFPage}
  3632. * @private
  3633. */
  3634. _ensurePdfPageLoaded: function (pageView) {
  3635. if (pageView.pdfPage) {
  3636. return Promise.resolve(pageView.pdfPage);
  3637. }
  3638. var pageNumber = pageView.id;
  3639. if (this._pagesRequests[pageNumber]) {
  3640. return this._pagesRequests[pageNumber];
  3641. }
  3642. var promise = this.pdfDocument.getPage(pageNumber).then(function (pdfPage) {
  3643. pageView.setPdfPage(pdfPage);
  3644. this._pagesRequests[pageNumber] = null;
  3645. return pdfPage;
  3646. }.bind(this));
  3647. this._pagesRequests[pageNumber] = promise;
  3648. return promise;
  3649. },
  3650. forceRendering: function (currentlyVisiblePages) {
  3651. var visiblePages = currentlyVisiblePages || this._getVisiblePages();
  3652. var pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, this.scroll.down);
  3653. if (pageView) {
  3654. this._ensurePdfPageLoaded(pageView).then(function () {
  3655. this.renderingQueue.renderView(pageView);
  3656. }.bind(this));
  3657. return true;
  3658. }
  3659. return false;
  3660. },
  3661. getPageTextContent: function (pageIndex) {
  3662. return this.pdfDocument.getPage(pageIndex + 1).then(function (page) {
  3663. return page.getTextContent({ normalizeWhitespace: true });
  3664. });
  3665. },
  3666. /**
  3667. * @param {HTMLDivElement} textLayerDiv
  3668. * @param {number} pageIndex
  3669. * @param {PageViewport} viewport
  3670. * @returns {TextLayerBuilder}
  3671. */
  3672. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport, enhanceTextSelection) {
  3673. return new TextLayerBuilder({
  3674. textLayerDiv: textLayerDiv,
  3675. eventBus: this.eventBus,
  3676. pageIndex: pageIndex,
  3677. viewport: viewport,
  3678. findController: this.isInPresentationMode ? null : this.findController,
  3679. enhanceTextSelection: this.isInPresentationMode ? false : enhanceTextSelection
  3680. });
  3681. },
  3682. /**
  3683. * @param {HTMLDivElement} pageDiv
  3684. * @param {PDFPage} pdfPage
  3685. * @param {boolean} renderInteractiveForms
  3686. * @returns {AnnotationLayerBuilder}
  3687. */
  3688. createAnnotationLayerBuilder: function (pageDiv, pdfPage, renderInteractiveForms) {
  3689. return new AnnotationLayerBuilder({
  3690. pageDiv: pageDiv,
  3691. pdfPage: pdfPage,
  3692. renderInteractiveForms: renderInteractiveForms,
  3693. linkService: this.linkService,
  3694. downloadManager: this.downloadManager
  3695. });
  3696. },
  3697. setFindController: function (findController) {
  3698. this.findController = findController;
  3699. },
  3700. /**
  3701. * Returns sizes of the pages.
  3702. * @returns {Array} Array of objects with width/height fields.
  3703. */
  3704. getPagesOverview: function () {
  3705. return this._pages.map(function (pageView) {
  3706. var viewport = pageView.pdfPage.getViewport(1);
  3707. return {
  3708. width: viewport.width,
  3709. height: viewport.height
  3710. };
  3711. });
  3712. }
  3713. };
  3714. return PDFViewer;
  3715. }();
  3716. exports.PresentationModeState = PresentationModeState;
  3717. exports.PDFViewer = PDFViewer;
  3718. }));
  3719. }.call(pdfViewerLibs));
  3720. var PDFJS = pdfjsLib.PDFJS;
  3721. PDFJS.PDFViewer = pdfViewerLibs.pdfjsWebPDFViewer.PDFViewer;
  3722. PDFJS.PDFPageView = pdfViewerLibs.pdfjsWebPDFPageView.PDFPageView;
  3723. PDFJS.PDFLinkService = pdfViewerLibs.pdfjsWebPDFLinkService.PDFLinkService;
  3724. PDFJS.TextLayerBuilder = pdfViewerLibs.pdfjsWebTextLayerBuilder.TextLayerBuilder;
  3725. PDFJS.DefaultTextLayerFactory = pdfViewerLibs.pdfjsWebTextLayerBuilder.DefaultTextLayerFactory;
  3726. PDFJS.AnnotationLayerBuilder = pdfViewerLibs.pdfjsWebAnnotationLayerBuilder.AnnotationLayerBuilder;
  3727. PDFJS.DefaultAnnotationLayerFactory = pdfViewerLibs.pdfjsWebAnnotationLayerBuilder.DefaultAnnotationLayerFactory;
  3728. PDFJS.PDFHistory = pdfViewerLibs.pdfjsWebPDFHistory.PDFHistory;
  3729. PDFJS.PDFFindController = pdfViewerLibs.pdfjsWebPDFFindController.PDFFindController;
  3730. PDFJS.EventBus = pdfViewerLibs.pdfjsWebUIUtils.EventBus;
  3731. PDFJS.DownloadManager = pdfViewerLibs.pdfjsWebDownloadManager.DownloadManager;
  3732. PDFJS.ProgressBar = pdfViewerLibs.pdfjsWebUIUtils.ProgressBar;
  3733. exports.PDFJS = PDFJS;
  3734. }));