2
0

pdf_viewer.js 152 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714
  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.isValidUrl(url, true)) {
  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 = destRef instanceof Object ? self._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] : destRef + 1;
  1699. if (pageNumber) {
  1700. if (pageNumber > self.pagesCount) {
  1701. console.error('PDFLinkService_navigateTo: ' + 'Trying to navigate to a non-existent page.');
  1702. return;
  1703. }
  1704. self.pdfViewer.scrollPageIntoView({
  1705. pageNumber: pageNumber,
  1706. destArray: dest
  1707. });
  1708. if (self.pdfHistory) {
  1709. // Update the browsing history.
  1710. self.pdfHistory.push({
  1711. dest: dest,
  1712. hash: destString,
  1713. page: pageNumber
  1714. });
  1715. }
  1716. } else {
  1717. self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
  1718. var pageNum = pageIndex + 1;
  1719. var cacheKey = destRef.num + ' ' + destRef.gen + ' R';
  1720. self._pagesRefCache[cacheKey] = pageNum;
  1721. goToDestination(destRef);
  1722. });
  1723. }
  1724. };
  1725. var destinationPromise;
  1726. if (typeof dest === 'string') {
  1727. destString = dest;
  1728. destinationPromise = this.pdfDocument.getDestination(dest);
  1729. } else {
  1730. destinationPromise = Promise.resolve(dest);
  1731. }
  1732. destinationPromise.then(function (destination) {
  1733. dest = destination;
  1734. if (!(destination instanceof Array)) {
  1735. return;
  1736. }
  1737. // invalid destination
  1738. goToDestination(destination[0]);
  1739. });
  1740. },
  1741. /**
  1742. * @param dest - The PDF destination object.
  1743. * @returns {string} The hyperlink to the PDF object.
  1744. */
  1745. getDestinationHash: function PDFLinkService_getDestinationHash(dest) {
  1746. if (typeof dest === 'string') {
  1747. // In practice, a named destination may contain only a number.
  1748. // If that happens, use the '#nameddest=' form to avoid the link
  1749. // redirecting to a page, instead of the correct destination.
  1750. return this.getAnchorUrl('#' + (isPageNumber(dest) ? 'nameddest=' : '') + escape(dest));
  1751. }
  1752. if (dest instanceof Array) {
  1753. var str = JSON.stringify(dest);
  1754. return this.getAnchorUrl('#' + escape(str));
  1755. }
  1756. return this.getAnchorUrl('');
  1757. },
  1758. /**
  1759. * Prefix the full url on anchor links to make sure that links are resolved
  1760. * relative to the current URL instead of the one defined in <base href>.
  1761. * @param {String} anchor The anchor hash, including the #.
  1762. * @returns {string} The hyperlink to the PDF object.
  1763. */
  1764. getAnchorUrl: function PDFLinkService_getAnchorUrl(anchor) {
  1765. return (this.baseUrl || '') + anchor;
  1766. },
  1767. /**
  1768. * @param {string} hash
  1769. */
  1770. setHash: function PDFLinkService_setHash(hash) {
  1771. var pageNumber, dest;
  1772. if (hash.indexOf('=') >= 0) {
  1773. var params = parseQueryString(hash);
  1774. if ('search' in params) {
  1775. this.eventBus.dispatch('findfromurlhash', {
  1776. source: this,
  1777. query: params['search'].replace(/"/g, ''),
  1778. phraseSearch: params['phrase'] === 'true'
  1779. });
  1780. }
  1781. // borrowing syntax from "Parameters for Opening PDF Files"
  1782. if ('nameddest' in params) {
  1783. if (this.pdfHistory) {
  1784. this.pdfHistory.updateNextHashParam(params.nameddest);
  1785. }
  1786. this.navigateTo(params.nameddest);
  1787. return;
  1788. }
  1789. if ('page' in params) {
  1790. pageNumber = params.page | 0 || 1;
  1791. }
  1792. if ('zoom' in params) {
  1793. // Build the destination array.
  1794. var zoomArgs = params.zoom.split(',');
  1795. // scale,left,top
  1796. var zoomArg = zoomArgs[0];
  1797. var zoomArgNumber = parseFloat(zoomArg);
  1798. if (zoomArg.indexOf('Fit') === -1) {
  1799. // If the zoomArg is a number, it has to get divided by 100. If it's
  1800. // a string, it should stay as it is.
  1801. dest = [
  1802. null,
  1803. { name: 'XYZ' },
  1804. zoomArgs.length > 1 ? zoomArgs[1] | 0 : null,
  1805. zoomArgs.length > 2 ? zoomArgs[2] | 0 : null,
  1806. zoomArgNumber ? zoomArgNumber / 100 : zoomArg
  1807. ];
  1808. } else {
  1809. if (zoomArg === 'Fit' || zoomArg === 'FitB') {
  1810. dest = [
  1811. null,
  1812. { name: zoomArg }
  1813. ];
  1814. } else if (zoomArg === 'FitH' || zoomArg === 'FitBH' || (zoomArg === 'FitV' || zoomArg === 'FitBV')) {
  1815. dest = [
  1816. null,
  1817. { name: zoomArg },
  1818. zoomArgs.length > 1 ? zoomArgs[1] | 0 : null
  1819. ];
  1820. } else if (zoomArg === 'FitR') {
  1821. if (zoomArgs.length !== 5) {
  1822. console.error('PDFLinkService_setHash: ' + 'Not enough parameters for \'FitR\'.');
  1823. } else {
  1824. dest = [
  1825. null,
  1826. { name: zoomArg },
  1827. zoomArgs[1] | 0,
  1828. zoomArgs[2] | 0,
  1829. zoomArgs[3] | 0,
  1830. zoomArgs[4] | 0
  1831. ];
  1832. }
  1833. } else {
  1834. console.error('PDFLinkService_setHash: \'' + zoomArg + '\' is not a valid zoom value.');
  1835. }
  1836. }
  1837. }
  1838. if (dest) {
  1839. this.pdfViewer.scrollPageIntoView({
  1840. pageNumber: pageNumber || this.page,
  1841. destArray: dest,
  1842. allowNegativeOffset: true
  1843. });
  1844. } else if (pageNumber) {
  1845. this.page = pageNumber;
  1846. }
  1847. // simple page
  1848. if ('pagemode' in params) {
  1849. this.eventBus.dispatch('pagemode', {
  1850. source: this,
  1851. mode: params.pagemode
  1852. });
  1853. }
  1854. } else if (isPageNumber(hash)) {
  1855. // Page number.
  1856. this.page = hash | 0;
  1857. } else {
  1858. // Named (or explicit) destination.
  1859. dest = unescape(hash);
  1860. try {
  1861. dest = JSON.parse(dest);
  1862. } catch (ex) {
  1863. }
  1864. if (typeof dest === 'string' || isValidExplicitDestination(dest)) {
  1865. if (this.pdfHistory) {
  1866. this.pdfHistory.updateNextHashParam(dest);
  1867. }
  1868. this.navigateTo(dest);
  1869. return;
  1870. }
  1871. console.error('PDFLinkService_setHash: \'' + unescape(hash) + '\' is not a valid destination.');
  1872. }
  1873. },
  1874. /**
  1875. * @param {string} action
  1876. */
  1877. executeNamedAction: function PDFLinkService_executeNamedAction(action) {
  1878. // See PDF reference, table 8.45 - Named action
  1879. switch (action) {
  1880. case 'GoBack':
  1881. if (this.pdfHistory) {
  1882. this.pdfHistory.back();
  1883. }
  1884. break;
  1885. case 'GoForward':
  1886. if (this.pdfHistory) {
  1887. this.pdfHistory.forward();
  1888. }
  1889. break;
  1890. case 'NextPage':
  1891. if (this.page < this.pagesCount) {
  1892. this.page++;
  1893. }
  1894. break;
  1895. case 'PrevPage':
  1896. if (this.page > 1) {
  1897. this.page--;
  1898. }
  1899. break;
  1900. case 'LastPage':
  1901. this.page = this.pagesCount;
  1902. break;
  1903. case 'FirstPage':
  1904. this.page = 1;
  1905. break;
  1906. default:
  1907. break;
  1908. }
  1909. // No action according to spec
  1910. this.eventBus.dispatch('namedaction', {
  1911. source: this,
  1912. action: action
  1913. });
  1914. },
  1915. /**
  1916. * @param {number} pageNum - page number.
  1917. * @param {Object} pageRef - reference to the page.
  1918. */
  1919. cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) {
  1920. var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
  1921. this._pagesRefCache[refStr] = pageNum;
  1922. }
  1923. };
  1924. function isValidExplicitDestination(dest) {
  1925. if (!(dest instanceof Array)) {
  1926. return false;
  1927. }
  1928. var destLength = dest.length, allowNull = true;
  1929. if (destLength < 2) {
  1930. return false;
  1931. }
  1932. var page = dest[0];
  1933. 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)) {
  1934. return false;
  1935. }
  1936. var zoom = dest[1];
  1937. if (!(typeof zoom === 'object' && typeof zoom.name === 'string')) {
  1938. return false;
  1939. }
  1940. switch (zoom.name) {
  1941. case 'XYZ':
  1942. if (destLength !== 5) {
  1943. return false;
  1944. }
  1945. break;
  1946. case 'Fit':
  1947. case 'FitB':
  1948. return destLength === 2;
  1949. case 'FitH':
  1950. case 'FitBH':
  1951. case 'FitV':
  1952. case 'FitBV':
  1953. if (destLength !== 3) {
  1954. return false;
  1955. }
  1956. break;
  1957. case 'FitR':
  1958. if (destLength !== 6) {
  1959. return false;
  1960. }
  1961. allowNull = false;
  1962. break;
  1963. default:
  1964. return false;
  1965. }
  1966. for (var i = 2; i < destLength; i++) {
  1967. var param = dest[i];
  1968. if (!(typeof param === 'number' || allowNull && param === null)) {
  1969. return false;
  1970. }
  1971. }
  1972. return true;
  1973. }
  1974. return PDFLinkService;
  1975. }();
  1976. var SimpleLinkService = function SimpleLinkServiceClosure() {
  1977. function SimpleLinkService() {
  1978. }
  1979. SimpleLinkService.prototype = {
  1980. /**
  1981. * @returns {number}
  1982. */
  1983. get page() {
  1984. return 0;
  1985. },
  1986. /**
  1987. * @param {number} value
  1988. */
  1989. set page(value) {
  1990. },
  1991. /**
  1992. * @param dest - The PDF destination object.
  1993. */
  1994. navigateTo: function (dest) {
  1995. },
  1996. /**
  1997. * @param dest - The PDF destination object.
  1998. * @returns {string} The hyperlink to the PDF object.
  1999. */
  2000. getDestinationHash: function (dest) {
  2001. return '#';
  2002. },
  2003. /**
  2004. * @param hash - The PDF parameters/hash.
  2005. * @returns {string} The hyperlink to the PDF object.
  2006. */
  2007. getAnchorUrl: function (hash) {
  2008. return '#';
  2009. },
  2010. /**
  2011. * @param {string} hash
  2012. */
  2013. setHash: function (hash) {
  2014. },
  2015. /**
  2016. * @param {string} action
  2017. */
  2018. executeNamedAction: function (action) {
  2019. },
  2020. /**
  2021. * @param {number} pageNum - page number.
  2022. * @param {Object} pageRef - reference to the page.
  2023. */
  2024. cachePageRef: function (pageNum, pageRef) {
  2025. }
  2026. };
  2027. return SimpleLinkService;
  2028. }();
  2029. exports.PDFLinkService = PDFLinkService;
  2030. exports.SimpleLinkService = SimpleLinkService;
  2031. }));
  2032. (function (root, factory) {
  2033. factory(root.pdfjsWebPDFPageView = {}, root.pdfjsWebUIUtils, root.pdfjsWebPDFRenderingQueue, root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS);
  2034. }(this, function (exports, uiUtils, pdfRenderingQueue, domEvents, pdfjsLib) {
  2035. var CSS_UNITS = uiUtils.CSS_UNITS;
  2036. var DEFAULT_SCALE = uiUtils.DEFAULT_SCALE;
  2037. var getOutputScale = uiUtils.getOutputScale;
  2038. var approximateFraction = uiUtils.approximateFraction;
  2039. var roundToDivide = uiUtils.roundToDivide;
  2040. var RenderingStates = pdfRenderingQueue.RenderingStates;
  2041. var TEXT_LAYER_RENDER_DELAY = 200;
  2042. // ms
  2043. /**
  2044. * @typedef {Object} PDFPageViewOptions
  2045. * @property {HTMLDivElement} container - The viewer element.
  2046. * @property {EventBus} eventBus - The application event bus.
  2047. * @property {number} id - The page unique ID (normally its number).
  2048. * @property {number} scale - The page scale display.
  2049. * @property {PageViewport} defaultViewport - The page viewport.
  2050. * @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
  2051. * @property {IPDFTextLayerFactory} textLayerFactory
  2052. * @property {IPDFAnnotationLayerFactory} annotationLayerFactory
  2053. * @property {boolean} enhanceTextSelection - Turns on the text selection
  2054. * enhancement. The default is `false`.
  2055. * @property {boolean} renderInteractiveForms - Turns on rendering of
  2056. * interactive form elements. The default is `false`.
  2057. */
  2058. /**
  2059. * @class
  2060. * @implements {IRenderableView}
  2061. */
  2062. var PDFPageView = function PDFPageViewClosure() {
  2063. /**
  2064. * @constructs PDFPageView
  2065. * @param {PDFPageViewOptions} options
  2066. */
  2067. function PDFPageView(options) {
  2068. var container = options.container;
  2069. var id = options.id;
  2070. var scale = options.scale;
  2071. var defaultViewport = options.defaultViewport;
  2072. var renderingQueue = options.renderingQueue;
  2073. var textLayerFactory = options.textLayerFactory;
  2074. var annotationLayerFactory = options.annotationLayerFactory;
  2075. var enhanceTextSelection = options.enhanceTextSelection || false;
  2076. var renderInteractiveForms = options.renderInteractiveForms || false;
  2077. this.id = id;
  2078. this.renderingId = 'page' + id;
  2079. this.rotation = 0;
  2080. this.scale = scale || DEFAULT_SCALE;
  2081. this.viewport = defaultViewport;
  2082. this.pdfPageRotate = defaultViewport.rotation;
  2083. this.hasRestrictedScaling = false;
  2084. this.enhanceTextSelection = enhanceTextSelection;
  2085. this.renderInteractiveForms = renderInteractiveForms;
  2086. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  2087. this.renderingQueue = renderingQueue;
  2088. this.textLayerFactory = textLayerFactory;
  2089. this.annotationLayerFactory = annotationLayerFactory;
  2090. this.renderTask = null;
  2091. this.renderingState = RenderingStates.INITIAL;
  2092. this.resume = null;
  2093. this.onBeforeDraw = null;
  2094. this.onAfterDraw = null;
  2095. this.textLayer = null;
  2096. this.zoomLayer = null;
  2097. this.annotationLayer = null;
  2098. var div = document.createElement('div');
  2099. div.id = 'pageContainer' + this.id;
  2100. div.className = 'page';
  2101. div.style.width = Math.floor(this.viewport.width) + 'px';
  2102. div.style.height = Math.floor(this.viewport.height) + 'px';
  2103. div.setAttribute('data-page-number', this.id);
  2104. this.div = div;
  2105. container.appendChild(div);
  2106. }
  2107. PDFPageView.prototype = {
  2108. setPdfPage: function PDFPageView_setPdfPage(pdfPage) {
  2109. this.pdfPage = pdfPage;
  2110. this.pdfPageRotate = pdfPage.rotate;
  2111. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  2112. this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS, totalRotation);
  2113. this.stats = pdfPage.stats;
  2114. this.reset();
  2115. },
  2116. destroy: function PDFPageView_destroy() {
  2117. this.zoomLayer = null;
  2118. this.reset();
  2119. if (this.pdfPage) {
  2120. this.pdfPage.cleanup();
  2121. }
  2122. },
  2123. reset: function PDFPageView_reset(keepZoomLayer, keepAnnotations) {
  2124. this.cancelRendering();
  2125. var div = this.div;
  2126. div.style.width = Math.floor(this.viewport.width) + 'px';
  2127. div.style.height = Math.floor(this.viewport.height) + 'px';
  2128. var childNodes = div.childNodes;
  2129. var currentZoomLayerNode = keepZoomLayer && this.zoomLayer || null;
  2130. var currentAnnotationNode = keepAnnotations && this.annotationLayer && this.annotationLayer.div || null;
  2131. for (var i = childNodes.length - 1; i >= 0; i--) {
  2132. var node = childNodes[i];
  2133. if (currentZoomLayerNode === node || currentAnnotationNode === node) {
  2134. continue;
  2135. }
  2136. div.removeChild(node);
  2137. }
  2138. div.removeAttribute('data-loaded');
  2139. if (currentAnnotationNode) {
  2140. // Hide annotationLayer until all elements are resized
  2141. // so they are not displayed on the already-resized page
  2142. this.annotationLayer.hide();
  2143. } else {
  2144. this.annotationLayer = null;
  2145. }
  2146. if (this.canvas && !currentZoomLayerNode) {
  2147. // Zeroing the width and height causes Firefox to release graphics
  2148. // resources immediately, which can greatly reduce memory consumption.
  2149. this.canvas.width = 0;
  2150. this.canvas.height = 0;
  2151. delete this.canvas;
  2152. }
  2153. this.loadingIconDiv = document.createElement('div');
  2154. this.loadingIconDiv.className = 'loadingIcon';
  2155. div.appendChild(this.loadingIconDiv);
  2156. },
  2157. update: function PDFPageView_update(scale, rotation) {
  2158. this.scale = scale || this.scale;
  2159. if (typeof rotation !== 'undefined') {
  2160. this.rotation = rotation;
  2161. }
  2162. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  2163. this.viewport = this.viewport.clone({
  2164. scale: this.scale * CSS_UNITS,
  2165. rotation: totalRotation
  2166. });
  2167. var isScalingRestricted = false;
  2168. if (this.canvas && pdfjsLib.PDFJS.maxCanvasPixels > 0) {
  2169. var outputScale = this.outputScale;
  2170. if ((Math.floor(this.viewport.width) * outputScale.sx | 0) * (Math.floor(this.viewport.height) * outputScale.sy | 0) > pdfjsLib.PDFJS.maxCanvasPixels) {
  2171. isScalingRestricted = true;
  2172. }
  2173. }
  2174. if (this.canvas) {
  2175. if (pdfjsLib.PDFJS.useOnlyCssZoom || this.hasRestrictedScaling && isScalingRestricted) {
  2176. this.cssTransform(this.canvas, true);
  2177. this.eventBus.dispatch('pagerendered', {
  2178. source: this,
  2179. pageNumber: this.id,
  2180. cssTransform: true
  2181. });
  2182. return;
  2183. }
  2184. if (!this.zoomLayer) {
  2185. this.zoomLayer = this.canvas.parentNode;
  2186. this.zoomLayer.style.position = 'absolute';
  2187. }
  2188. }
  2189. if (this.zoomLayer) {
  2190. this.cssTransform(this.zoomLayer.firstChild);
  2191. }
  2192. this.reset(/* keepZoomLayer = */
  2193. true, /* keepAnnotations = */
  2194. true);
  2195. },
  2196. cancelRendering: function PDFPageView_cancelRendering() {
  2197. if (this.renderTask) {
  2198. this.renderTask.cancel();
  2199. this.renderTask = null;
  2200. }
  2201. this.renderingState = RenderingStates.INITIAL;
  2202. this.resume = null;
  2203. if (this.textLayer) {
  2204. this.textLayer.cancel();
  2205. this.textLayer = null;
  2206. }
  2207. },
  2208. /**
  2209. * Called when moved in the parent's container.
  2210. */
  2211. updatePosition: function PDFPageView_updatePosition() {
  2212. if (this.textLayer) {
  2213. this.textLayer.render(TEXT_LAYER_RENDER_DELAY);
  2214. }
  2215. },
  2216. cssTransform: function PDFPageView_transform(canvas, redrawAnnotations) {
  2217. var CustomStyle = pdfjsLib.CustomStyle;
  2218. // Scale canvas, canvas wrapper, and page container.
  2219. var width = this.viewport.width;
  2220. var height = this.viewport.height;
  2221. var div = this.div;
  2222. canvas.style.width = canvas.parentNode.style.width = div.style.width = Math.floor(width) + 'px';
  2223. canvas.style.height = canvas.parentNode.style.height = div.style.height = Math.floor(height) + 'px';
  2224. // The canvas may have been originally rotated, rotate relative to that.
  2225. var relativeRotation = this.viewport.rotation - canvas._viewport.rotation;
  2226. var absRotation = Math.abs(relativeRotation);
  2227. var scaleX = 1, scaleY = 1;
  2228. if (absRotation === 90 || absRotation === 270) {
  2229. // Scale x and y because of the rotation.
  2230. scaleX = height / width;
  2231. scaleY = width / height;
  2232. }
  2233. var cssTransform = 'rotate(' + relativeRotation + 'deg) ' + 'scale(' + scaleX + ',' + scaleY + ')';
  2234. CustomStyle.setProp('transform', canvas, cssTransform);
  2235. if (this.textLayer) {
  2236. // Rotating the text layer is more complicated since the divs inside the
  2237. // the text layer are rotated.
  2238. // TODO: This could probably be simplified by drawing the text layer in
  2239. // one orientation then rotating overall.
  2240. var textLayerViewport = this.textLayer.viewport;
  2241. var textRelativeRotation = this.viewport.rotation - textLayerViewport.rotation;
  2242. var textAbsRotation = Math.abs(textRelativeRotation);
  2243. var scale = width / textLayerViewport.width;
  2244. if (textAbsRotation === 90 || textAbsRotation === 270) {
  2245. scale = width / textLayerViewport.height;
  2246. }
  2247. var textLayerDiv = this.textLayer.textLayerDiv;
  2248. var transX, transY;
  2249. switch (textAbsRotation) {
  2250. case 0:
  2251. transX = transY = 0;
  2252. break;
  2253. case 90:
  2254. transX = 0;
  2255. transY = '-' + textLayerDiv.style.height;
  2256. break;
  2257. case 180:
  2258. transX = '-' + textLayerDiv.style.width;
  2259. transY = '-' + textLayerDiv.style.height;
  2260. break;
  2261. case 270:
  2262. transX = '-' + textLayerDiv.style.width;
  2263. transY = 0;
  2264. break;
  2265. default:
  2266. console.error('Bad rotation value.');
  2267. break;
  2268. }
  2269. CustomStyle.setProp('transform', textLayerDiv, 'rotate(' + textAbsRotation + 'deg) ' + 'scale(' + scale + ', ' + scale + ') ' + 'translate(' + transX + ', ' + transY + ')');
  2270. CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');
  2271. }
  2272. if (redrawAnnotations && this.annotationLayer) {
  2273. this.annotationLayer.render(this.viewport, 'display');
  2274. }
  2275. },
  2276. get width() {
  2277. return this.viewport.width;
  2278. },
  2279. get height() {
  2280. return this.viewport.height;
  2281. },
  2282. getPagePoint: function PDFPageView_getPagePoint(x, y) {
  2283. return this.viewport.convertToPdfPoint(x, y);
  2284. },
  2285. draw: function PDFPageView_draw() {
  2286. if (this.renderingState !== RenderingStates.INITIAL) {
  2287. console.error('Must be in new state before drawing');
  2288. this.reset();
  2289. }
  2290. // Ensure that we reset all state to prevent issues.
  2291. this.renderingState = RenderingStates.RUNNING;
  2292. var pdfPage = this.pdfPage;
  2293. var viewport = this.viewport;
  2294. var div = this.div;
  2295. // Wrap the canvas so if it has a css transform for highdpi the overflow
  2296. // will be hidden in FF.
  2297. var canvasWrapper = document.createElement('div');
  2298. canvasWrapper.style.width = div.style.width;
  2299. canvasWrapper.style.height = div.style.height;
  2300. canvasWrapper.classList.add('canvasWrapper');
  2301. var canvas = document.createElement('canvas');
  2302. canvas.id = 'page' + this.id;
  2303. // Keep the canvas hidden until the first draw callback, or until drawing
  2304. // is complete when `!this.renderingQueue`, to prevent black flickering.
  2305. canvas.setAttribute('hidden', 'hidden');
  2306. var isCanvasHidden = true;
  2307. canvasWrapper.appendChild(canvas);
  2308. if (this.annotationLayer && this.annotationLayer.div) {
  2309. // annotationLayer needs to stay on top
  2310. div.insertBefore(canvasWrapper, this.annotationLayer.div);
  2311. } else {
  2312. div.appendChild(canvasWrapper);
  2313. }
  2314. this.canvas = canvas;
  2315. canvas.mozOpaque = true;
  2316. var ctx = canvas.getContext('2d', { alpha: false });
  2317. var outputScale = getOutputScale(ctx);
  2318. this.outputScale = outputScale;
  2319. if (pdfjsLib.PDFJS.useOnlyCssZoom) {
  2320. var actualSizeViewport = viewport.clone({ scale: CSS_UNITS });
  2321. // Use a scale that will make the canvas be the original intended size
  2322. // of the page.
  2323. outputScale.sx *= actualSizeViewport.width / viewport.width;
  2324. outputScale.sy *= actualSizeViewport.height / viewport.height;
  2325. outputScale.scaled = true;
  2326. }
  2327. if (pdfjsLib.PDFJS.maxCanvasPixels > 0) {
  2328. var pixelsInViewport = viewport.width * viewport.height;
  2329. var maxScale = Math.sqrt(pdfjsLib.PDFJS.maxCanvasPixels / pixelsInViewport);
  2330. if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
  2331. outputScale.sx = maxScale;
  2332. outputScale.sy = maxScale;
  2333. outputScale.scaled = true;
  2334. this.hasRestrictedScaling = true;
  2335. } else {
  2336. this.hasRestrictedScaling = false;
  2337. }
  2338. }
  2339. var sfx = approximateFraction(outputScale.sx);
  2340. var sfy = approximateFraction(outputScale.sy);
  2341. canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]);
  2342. canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]);
  2343. canvas.style.width = roundToDivide(viewport.width, sfx[1]) + 'px';
  2344. canvas.style.height = roundToDivide(viewport.height, sfy[1]) + 'px';
  2345. // Add the viewport so it's known what it was originally drawn with.
  2346. canvas._viewport = viewport;
  2347. var textLayerDiv = null;
  2348. var textLayer = null;
  2349. if (this.textLayerFactory) {
  2350. textLayerDiv = document.createElement('div');
  2351. textLayerDiv.className = 'textLayer';
  2352. textLayerDiv.style.width = canvasWrapper.style.width;
  2353. textLayerDiv.style.height = canvasWrapper.style.height;
  2354. if (this.annotationLayer && this.annotationLayer.div) {
  2355. // annotationLayer needs to stay on top
  2356. div.insertBefore(textLayerDiv, this.annotationLayer.div);
  2357. } else {
  2358. div.appendChild(textLayerDiv);
  2359. }
  2360. textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv, this.id - 1, this.viewport, this.enhanceTextSelection);
  2361. }
  2362. this.textLayer = textLayer;
  2363. var resolveRenderPromise, rejectRenderPromise;
  2364. var promise = new Promise(function (resolve, reject) {
  2365. resolveRenderPromise = resolve;
  2366. rejectRenderPromise = reject;
  2367. });
  2368. // Rendering area
  2369. var self = this;
  2370. function pageViewDrawCallback(error) {
  2371. // The renderTask may have been replaced by a new one, so only remove
  2372. // the reference to the renderTask if it matches the one that is
  2373. // triggering this callback.
  2374. if (renderTask === self.renderTask) {
  2375. self.renderTask = null;
  2376. }
  2377. if (error === 'cancelled') {
  2378. rejectRenderPromise(error);
  2379. return;
  2380. }
  2381. self.renderingState = RenderingStates.FINISHED;
  2382. if (isCanvasHidden) {
  2383. self.canvas.removeAttribute('hidden');
  2384. isCanvasHidden = false;
  2385. }
  2386. if (self.loadingIconDiv) {
  2387. div.removeChild(self.loadingIconDiv);
  2388. delete self.loadingIconDiv;
  2389. }
  2390. if (self.zoomLayer) {
  2391. // Zeroing the width and height causes Firefox to release graphics
  2392. // resources immediately, which can greatly reduce memory consumption.
  2393. var zoomLayerCanvas = self.zoomLayer.firstChild;
  2394. zoomLayerCanvas.width = 0;
  2395. zoomLayerCanvas.height = 0;
  2396. if (div.contains(self.zoomLayer)) {
  2397. // Prevent "Node was not found" errors if the `zoomLayer` was
  2398. // already removed. This may occur intermittently if the scale
  2399. // changes many times in very quick succession.
  2400. div.removeChild(self.zoomLayer);
  2401. }
  2402. self.zoomLayer = null;
  2403. }
  2404. self.error = error;
  2405. self.stats = pdfPage.stats;
  2406. if (self.onAfterDraw) {
  2407. self.onAfterDraw();
  2408. }
  2409. self.eventBus.dispatch('pagerendered', {
  2410. source: self,
  2411. pageNumber: self.id,
  2412. cssTransform: false
  2413. });
  2414. if (!error) {
  2415. resolveRenderPromise(undefined);
  2416. } else {
  2417. rejectRenderPromise(error);
  2418. }
  2419. }
  2420. var renderContinueCallback = null;
  2421. if (this.renderingQueue) {
  2422. renderContinueCallback = function renderContinueCallback(cont) {
  2423. if (!self.renderingQueue.isHighestPriority(self)) {
  2424. self.renderingState = RenderingStates.PAUSED;
  2425. self.resume = function resumeCallback() {
  2426. self.renderingState = RenderingStates.RUNNING;
  2427. cont();
  2428. };
  2429. return;
  2430. }
  2431. if (isCanvasHidden) {
  2432. self.canvas.removeAttribute('hidden');
  2433. isCanvasHidden = false;
  2434. }
  2435. cont();
  2436. };
  2437. }
  2438. var transform = !outputScale.scaled ? null : [
  2439. outputScale.sx,
  2440. 0,
  2441. 0,
  2442. outputScale.sy,
  2443. 0,
  2444. 0
  2445. ];
  2446. var renderContext = {
  2447. canvasContext: ctx,
  2448. transform: transform,
  2449. viewport: this.viewport,
  2450. renderInteractiveForms: this.renderInteractiveForms
  2451. };
  2452. // intent: 'default', // === 'display'
  2453. var renderTask = this.renderTask = this.pdfPage.render(renderContext);
  2454. renderTask.onContinue = renderContinueCallback;
  2455. this.renderTask.promise.then(function pdfPageRenderCallback() {
  2456. pageViewDrawCallback(null);
  2457. if (textLayer) {
  2458. self.pdfPage.getTextContent({ normalizeWhitespace: true }).then(function textContentResolved(textContent) {
  2459. textLayer.setTextContent(textContent);
  2460. textLayer.render(TEXT_LAYER_RENDER_DELAY);
  2461. });
  2462. }
  2463. }, function pdfPageRenderError(error) {
  2464. pageViewDrawCallback(error);
  2465. });
  2466. if (this.annotationLayerFactory) {
  2467. if (!this.annotationLayer) {
  2468. this.annotationLayer = this.annotationLayerFactory.createAnnotationLayerBuilder(div, this.pdfPage, this.renderInteractiveForms);
  2469. }
  2470. this.annotationLayer.render(this.viewport, 'display');
  2471. }
  2472. div.setAttribute('data-loaded', true);
  2473. if (self.onBeforeDraw) {
  2474. self.onBeforeDraw();
  2475. }
  2476. return promise;
  2477. }
  2478. };
  2479. return PDFPageView;
  2480. }();
  2481. exports.PDFPageView = PDFPageView;
  2482. }));
  2483. (function (root, factory) {
  2484. factory(root.pdfjsWebTextLayerBuilder = {}, root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS);
  2485. }(this, function (exports, domEvents, pdfjsLib) {
  2486. var EXPAND_DIVS_TIMEOUT = 300;
  2487. // ms
  2488. /**
  2489. * @typedef {Object} TextLayerBuilderOptions
  2490. * @property {HTMLDivElement} textLayerDiv - The text layer container.
  2491. * @property {EventBus} eventBus - The application event bus.
  2492. * @property {number} pageIndex - The page index.
  2493. * @property {PageViewport} viewport - The viewport of the text layer.
  2494. * @property {PDFFindController} findController
  2495. * @property {boolean} enhanceTextSelection - Option to turn on improved
  2496. * text selection.
  2497. */
  2498. /**
  2499. * TextLayerBuilder provides text-selection functionality for the PDF.
  2500. * It does this by creating overlay divs over the PDF text. These divs
  2501. * contain text that matches the PDF text they are overlaying. This object
  2502. * also provides a way to highlight text that is being searched for.
  2503. * @class
  2504. */
  2505. var TextLayerBuilder = function TextLayerBuilderClosure() {
  2506. function TextLayerBuilder(options) {
  2507. this.textLayerDiv = options.textLayerDiv;
  2508. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  2509. this.textContent = null;
  2510. this.renderingDone = false;
  2511. this.pageIdx = options.pageIndex;
  2512. this.pageNumber = this.pageIdx + 1;
  2513. this.matches = [];
  2514. this.viewport = options.viewport;
  2515. this.textDivs = [];
  2516. this.findController = options.findController || null;
  2517. this.textLayerRenderTask = null;
  2518. this.enhanceTextSelection = options.enhanceTextSelection;
  2519. this._bindMouse();
  2520. }
  2521. TextLayerBuilder.prototype = {
  2522. /**
  2523. * @private
  2524. */
  2525. _finishRendering: function TextLayerBuilder_finishRendering() {
  2526. this.renderingDone = true;
  2527. if (!this.enhanceTextSelection) {
  2528. var endOfContent = document.createElement('div');
  2529. endOfContent.className = 'endOfContent';
  2530. this.textLayerDiv.appendChild(endOfContent);
  2531. }
  2532. this.eventBus.dispatch('textlayerrendered', {
  2533. source: this,
  2534. pageNumber: this.pageNumber,
  2535. numTextDivs: this.textDivs.length
  2536. });
  2537. },
  2538. /**
  2539. * Renders the text layer.
  2540. * @param {number} timeout (optional) if specified, the rendering waits
  2541. * for specified amount of ms.
  2542. */
  2543. render: function TextLayerBuilder_render(timeout) {
  2544. if (!this.textContent || this.renderingDone) {
  2545. return;
  2546. }
  2547. this.cancel();
  2548. this.textDivs = [];
  2549. var textLayerFrag = document.createDocumentFragment();
  2550. this.textLayerRenderTask = pdfjsLib.renderTextLayer({
  2551. textContent: this.textContent,
  2552. container: textLayerFrag,
  2553. viewport: this.viewport,
  2554. textDivs: this.textDivs,
  2555. timeout: timeout,
  2556. enhanceTextSelection: this.enhanceTextSelection
  2557. });
  2558. this.textLayerRenderTask.promise.then(function () {
  2559. this.textLayerDiv.appendChild(textLayerFrag);
  2560. this._finishRendering();
  2561. this.updateMatches();
  2562. }.bind(this), function (reason) {
  2563. });
  2564. },
  2565. /**
  2566. * Cancels rendering of the text layer.
  2567. */
  2568. cancel: function TextLayerBuilder_cancel() {
  2569. if (this.textLayerRenderTask) {
  2570. this.textLayerRenderTask.cancel();
  2571. this.textLayerRenderTask = null;
  2572. }
  2573. },
  2574. setTextContent: function TextLayerBuilder_setTextContent(textContent) {
  2575. this.cancel();
  2576. this.textContent = textContent;
  2577. },
  2578. convertMatches: function TextLayerBuilder_convertMatches(matches, matchesLength) {
  2579. var i = 0;
  2580. var iIndex = 0;
  2581. var bidiTexts = this.textContent.items;
  2582. var end = bidiTexts.length - 1;
  2583. var queryLen = this.findController === null ? 0 : this.findController.state.query.length;
  2584. var ret = [];
  2585. if (!matches) {
  2586. return ret;
  2587. }
  2588. for (var m = 0, len = matches.length; m < len; m++) {
  2589. // Calculate the start position.
  2590. var matchIdx = matches[m];
  2591. // Loop over the divIdxs.
  2592. while (i !== end && matchIdx >= iIndex + bidiTexts[i].str.length) {
  2593. iIndex += bidiTexts[i].str.length;
  2594. i++;
  2595. }
  2596. if (i === bidiTexts.length) {
  2597. console.error('Could not find a matching mapping');
  2598. }
  2599. var match = {
  2600. begin: {
  2601. divIdx: i,
  2602. offset: matchIdx - iIndex
  2603. }
  2604. };
  2605. // Calculate the end position.
  2606. if (matchesLength) {
  2607. // multiterm search
  2608. matchIdx += matchesLength[m];
  2609. } else {
  2610. // phrase search
  2611. matchIdx += queryLen;
  2612. }
  2613. // Somewhat the same array as above, but use > instead of >= to get
  2614. // the end position right.
  2615. while (i !== end && matchIdx > iIndex + bidiTexts[i].str.length) {
  2616. iIndex += bidiTexts[i].str.length;
  2617. i++;
  2618. }
  2619. match.end = {
  2620. divIdx: i,
  2621. offset: matchIdx - iIndex
  2622. };
  2623. ret.push(match);
  2624. }
  2625. return ret;
  2626. },
  2627. renderMatches: function TextLayerBuilder_renderMatches(matches) {
  2628. // Early exit if there is nothing to render.
  2629. if (matches.length === 0) {
  2630. return;
  2631. }
  2632. var bidiTexts = this.textContent.items;
  2633. var textDivs = this.textDivs;
  2634. var prevEnd = null;
  2635. var pageIdx = this.pageIdx;
  2636. var isSelectedPage = this.findController === null ? false : pageIdx === this.findController.selected.pageIdx;
  2637. var selectedMatchIdx = this.findController === null ? -1 : this.findController.selected.matchIdx;
  2638. var highlightAll = this.findController === null ? false : this.findController.state.highlightAll;
  2639. var infinity = {
  2640. divIdx: -1,
  2641. offset: undefined
  2642. };
  2643. function beginText(begin, className) {
  2644. var divIdx = begin.divIdx;
  2645. textDivs[divIdx].textContent = '';
  2646. appendTextToDiv(divIdx, 0, begin.offset, className);
  2647. }
  2648. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  2649. var div = textDivs[divIdx];
  2650. var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
  2651. var node = document.createTextNode(content);
  2652. if (className) {
  2653. var span = document.createElement('span');
  2654. span.className = className;
  2655. span.appendChild(node);
  2656. div.appendChild(span);
  2657. return;
  2658. }
  2659. div.appendChild(node);
  2660. }
  2661. var i0 = selectedMatchIdx, i1 = i0 + 1;
  2662. if (highlightAll) {
  2663. i0 = 0;
  2664. i1 = matches.length;
  2665. } else if (!isSelectedPage) {
  2666. // Not highlighting all and this isn't the selected page, so do nothing.
  2667. return;
  2668. }
  2669. for (var i = i0; i < i1; i++) {
  2670. var match = matches[i];
  2671. var begin = match.begin;
  2672. var end = match.end;
  2673. var isSelected = isSelectedPage && i === selectedMatchIdx;
  2674. var highlightSuffix = isSelected ? ' selected' : '';
  2675. if (this.findController) {
  2676. this.findController.updateMatchPosition(pageIdx, i, textDivs, begin.divIdx);
  2677. }
  2678. // Match inside new div.
  2679. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  2680. // If there was a previous div, then add the text at the end.
  2681. if (prevEnd !== null) {
  2682. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  2683. }
  2684. // Clear the divs and set the content until the starting point.
  2685. beginText(begin);
  2686. } else {
  2687. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  2688. }
  2689. if (begin.divIdx === end.divIdx) {
  2690. appendTextToDiv(begin.divIdx, begin.offset, end.offset, 'highlight' + highlightSuffix);
  2691. } else {
  2692. appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, 'highlight begin' + highlightSuffix);
  2693. for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  2694. textDivs[n0].className = 'highlight middle' + highlightSuffix;
  2695. }
  2696. beginText(end, 'highlight end' + highlightSuffix);
  2697. }
  2698. prevEnd = end;
  2699. }
  2700. if (prevEnd) {
  2701. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  2702. }
  2703. },
  2704. updateMatches: function TextLayerBuilder_updateMatches() {
  2705. // Only show matches when all rendering is done.
  2706. if (!this.renderingDone) {
  2707. return;
  2708. }
  2709. // Clear all matches.
  2710. var matches = this.matches;
  2711. var textDivs = this.textDivs;
  2712. var bidiTexts = this.textContent.items;
  2713. var clearedUntilDivIdx = -1;
  2714. // Clear all current matches.
  2715. for (var i = 0, len = matches.length; i < len; i++) {
  2716. var match = matches[i];
  2717. var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  2718. for (var n = begin, end = match.end.divIdx; n <= end; n++) {
  2719. var div = textDivs[n];
  2720. div.textContent = bidiTexts[n].str;
  2721. div.className = '';
  2722. }
  2723. clearedUntilDivIdx = match.end.divIdx + 1;
  2724. }
  2725. if (this.findController === null || !this.findController.active) {
  2726. return;
  2727. }
  2728. // Convert the matches on the page controller into the match format
  2729. // used for the textLayer.
  2730. var pageMatches, pageMatchesLength;
  2731. if (this.findController !== null) {
  2732. pageMatches = this.findController.pageMatches[this.pageIdx] || null;
  2733. pageMatchesLength = this.findController.pageMatchesLength ? this.findController.pageMatchesLength[this.pageIdx] || null : null;
  2734. }
  2735. this.matches = this.convertMatches(pageMatches, pageMatchesLength);
  2736. this.renderMatches(this.matches);
  2737. },
  2738. /**
  2739. * Fixes text selection: adds additional div where mouse was clicked.
  2740. * This reduces flickering of the content if mouse slowly dragged down/up.
  2741. * @private
  2742. */
  2743. _bindMouse: function TextLayerBuilder_bindMouse() {
  2744. var div = this.textLayerDiv;
  2745. var self = this;
  2746. var expandDivsTimer = null;
  2747. div.addEventListener('mousedown', function (e) {
  2748. if (self.enhanceTextSelection && self.textLayerRenderTask) {
  2749. self.textLayerRenderTask.expandTextDivs(true);
  2750. if (expandDivsTimer) {
  2751. clearTimeout(expandDivsTimer);
  2752. expandDivsTimer = null;
  2753. }
  2754. return;
  2755. }
  2756. var end = div.querySelector('.endOfContent');
  2757. if (!end) {
  2758. return;
  2759. }
  2760. // On non-Firefox browsers, the selection will feel better if the height
  2761. // of the endOfContent div will be adjusted to start at mouse click
  2762. // location -- this will avoid flickering when selections moves up.
  2763. // However it does not work when selection started on empty space.
  2764. var adjustTop = e.target !== div;
  2765. adjustTop = adjustTop && window.getComputedStyle(end).getPropertyValue('-moz-user-select') !== 'none';
  2766. if (adjustTop) {
  2767. var divBounds = div.getBoundingClientRect();
  2768. var r = Math.max(0, (e.pageY - divBounds.top) / divBounds.height);
  2769. end.style.top = (r * 100).toFixed(2) + '%';
  2770. }
  2771. end.classList.add('active');
  2772. });
  2773. div.addEventListener('mouseup', function (e) {
  2774. if (self.enhanceTextSelection && self.textLayerRenderTask) {
  2775. expandDivsTimer = setTimeout(function () {
  2776. if (self.textLayerRenderTask) {
  2777. self.textLayerRenderTask.expandTextDivs(false);
  2778. }
  2779. expandDivsTimer = null;
  2780. }, EXPAND_DIVS_TIMEOUT);
  2781. return;
  2782. }
  2783. var end = div.querySelector('.endOfContent');
  2784. if (!end) {
  2785. return;
  2786. }
  2787. end.style.top = '';
  2788. end.classList.remove('active');
  2789. });
  2790. }
  2791. };
  2792. return TextLayerBuilder;
  2793. }();
  2794. /**
  2795. * @constructor
  2796. * @implements IPDFTextLayerFactory
  2797. */
  2798. function DefaultTextLayerFactory() {
  2799. }
  2800. DefaultTextLayerFactory.prototype = {
  2801. /**
  2802. * @param {HTMLDivElement} textLayerDiv
  2803. * @param {number} pageIndex
  2804. * @param {PageViewport} viewport
  2805. * @param {boolean} enhanceTextSelection
  2806. * @returns {TextLayerBuilder}
  2807. */
  2808. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport, enhanceTextSelection) {
  2809. return new TextLayerBuilder({
  2810. textLayerDiv: textLayerDiv,
  2811. pageIndex: pageIndex,
  2812. viewport: viewport,
  2813. enhanceTextSelection: enhanceTextSelection
  2814. });
  2815. }
  2816. };
  2817. exports.TextLayerBuilder = TextLayerBuilder;
  2818. exports.DefaultTextLayerFactory = DefaultTextLayerFactory;
  2819. }));
  2820. (function (root, factory) {
  2821. factory(root.pdfjsWebAnnotationLayerBuilder = {}, root.pdfjsWebUIUtils, root.pdfjsWebPDFLinkService, root.pdfjsWebPDFJS);
  2822. }(this, function (exports, uiUtils, pdfLinkService, pdfjsLib) {
  2823. var mozL10n = uiUtils.mozL10n;
  2824. var SimpleLinkService = pdfLinkService.SimpleLinkService;
  2825. /**
  2826. * @typedef {Object} AnnotationLayerBuilderOptions
  2827. * @property {HTMLDivElement} pageDiv
  2828. * @property {PDFPage} pdfPage
  2829. * @property {boolean} renderInteractiveForms
  2830. * @property {IPDFLinkService} linkService
  2831. * @property {DownloadManager} downloadManager
  2832. */
  2833. /**
  2834. * @class
  2835. */
  2836. var AnnotationLayerBuilder = function AnnotationLayerBuilderClosure() {
  2837. /**
  2838. * @param {AnnotationLayerBuilderOptions} options
  2839. * @constructs AnnotationLayerBuilder
  2840. */
  2841. function AnnotationLayerBuilder(options) {
  2842. this.pageDiv = options.pageDiv;
  2843. this.pdfPage = options.pdfPage;
  2844. this.renderInteractiveForms = options.renderInteractiveForms;
  2845. this.linkService = options.linkService;
  2846. this.downloadManager = options.downloadManager;
  2847. this.div = null;
  2848. }
  2849. AnnotationLayerBuilder.prototype = /** @lends AnnotationLayerBuilder.prototype */
  2850. {
  2851. /**
  2852. * @param {PageViewport} viewport
  2853. * @param {string} intent (default value is 'display')
  2854. */
  2855. render: function AnnotationLayerBuilder_render(viewport, intent) {
  2856. var self = this;
  2857. var parameters = { intent: intent === undefined ? 'display' : intent };
  2858. this.pdfPage.getAnnotations(parameters).then(function (annotations) {
  2859. viewport = viewport.clone({ dontFlip: true });
  2860. parameters = {
  2861. viewport: viewport,
  2862. div: self.div,
  2863. annotations: annotations,
  2864. page: self.pdfPage,
  2865. renderInteractiveForms: self.renderInteractiveForms,
  2866. linkService: self.linkService,
  2867. downloadManager: self.downloadManager
  2868. };
  2869. if (self.div) {
  2870. // If an annotationLayer already exists, refresh its children's
  2871. // transformation matrices.
  2872. pdfjsLib.AnnotationLayer.update(parameters);
  2873. } else {
  2874. // Create an annotation layer div and render the annotations
  2875. // if there is at least one annotation.
  2876. if (annotations.length === 0) {
  2877. return;
  2878. }
  2879. self.div = document.createElement('div');
  2880. self.div.className = 'annotationLayer';
  2881. self.pageDiv.appendChild(self.div);
  2882. parameters.div = self.div;
  2883. pdfjsLib.AnnotationLayer.render(parameters);
  2884. if (typeof mozL10n !== 'undefined') {
  2885. mozL10n.translate(self.div);
  2886. }
  2887. }
  2888. });
  2889. },
  2890. hide: function AnnotationLayerBuilder_hide() {
  2891. if (!this.div) {
  2892. return;
  2893. }
  2894. this.div.setAttribute('hidden', 'true');
  2895. }
  2896. };
  2897. return AnnotationLayerBuilder;
  2898. }();
  2899. /**
  2900. * @constructor
  2901. * @implements IPDFAnnotationLayerFactory
  2902. */
  2903. function DefaultAnnotationLayerFactory() {
  2904. }
  2905. DefaultAnnotationLayerFactory.prototype = {
  2906. /**
  2907. * @param {HTMLDivElement} pageDiv
  2908. * @param {PDFPage} pdfPage
  2909. * @param {boolean} renderInteractiveForms
  2910. * @returns {AnnotationLayerBuilder}
  2911. */
  2912. createAnnotationLayerBuilder: function (pageDiv, pdfPage, renderInteractiveForms) {
  2913. return new AnnotationLayerBuilder({
  2914. pageDiv: pageDiv,
  2915. pdfPage: pdfPage,
  2916. renderInteractiveForms: renderInteractiveForms,
  2917. linkService: new SimpleLinkService()
  2918. });
  2919. }
  2920. };
  2921. exports.AnnotationLayerBuilder = AnnotationLayerBuilder;
  2922. exports.DefaultAnnotationLayerFactory = DefaultAnnotationLayerFactory;
  2923. }));
  2924. (function (root, factory) {
  2925. factory(root.pdfjsWebPDFViewer = {}, root.pdfjsWebUIUtils, root.pdfjsWebPDFPageView, root.pdfjsWebPDFRenderingQueue, root.pdfjsWebTextLayerBuilder, root.pdfjsWebAnnotationLayerBuilder, root.pdfjsWebPDFLinkService, root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS);
  2926. }(this, function (exports, uiUtils, pdfPageView, pdfRenderingQueue, textLayerBuilder, annotationLayerBuilder, pdfLinkService, domEvents, pdfjsLib) {
  2927. var UNKNOWN_SCALE = uiUtils.UNKNOWN_SCALE;
  2928. var SCROLLBAR_PADDING = uiUtils.SCROLLBAR_PADDING;
  2929. var VERTICAL_PADDING = uiUtils.VERTICAL_PADDING;
  2930. var MAX_AUTO_SCALE = uiUtils.MAX_AUTO_SCALE;
  2931. var CSS_UNITS = uiUtils.CSS_UNITS;
  2932. var DEFAULT_SCALE = uiUtils.DEFAULT_SCALE;
  2933. var DEFAULT_SCALE_VALUE = uiUtils.DEFAULT_SCALE_VALUE;
  2934. var scrollIntoView = uiUtils.scrollIntoView;
  2935. var watchScroll = uiUtils.watchScroll;
  2936. var getVisibleElements = uiUtils.getVisibleElements;
  2937. var PDFPageView = pdfPageView.PDFPageView;
  2938. var RenderingStates = pdfRenderingQueue.RenderingStates;
  2939. var PDFRenderingQueue = pdfRenderingQueue.PDFRenderingQueue;
  2940. var TextLayerBuilder = textLayerBuilder.TextLayerBuilder;
  2941. var AnnotationLayerBuilder = annotationLayerBuilder.AnnotationLayerBuilder;
  2942. var SimpleLinkService = pdfLinkService.SimpleLinkService;
  2943. var PresentationModeState = {
  2944. UNKNOWN: 0,
  2945. NORMAL: 1,
  2946. CHANGING: 2,
  2947. FULLSCREEN: 3
  2948. };
  2949. var DEFAULT_CACHE_SIZE = 10;
  2950. /**
  2951. * @typedef {Object} PDFViewerOptions
  2952. * @property {HTMLDivElement} container - The container for the viewer element.
  2953. * @property {HTMLDivElement} viewer - (optional) The viewer element.
  2954. * @property {EventBus} eventBus - The application event bus.
  2955. * @property {IPDFLinkService} linkService - The navigation/linking service.
  2956. * @property {DownloadManager} downloadManager - (optional) The download
  2957. * manager component.
  2958. * @property {PDFRenderingQueue} renderingQueue - (optional) The rendering
  2959. * queue object.
  2960. * @property {boolean} removePageBorders - (optional) Removes the border shadow
  2961. * around the pages. The default is false.
  2962. * @property {boolean} enhanceTextSelection - (optional) Enables the improved
  2963. * text selection behaviour. The default is `false`.
  2964. * @property {boolean} renderInteractiveForms - (optional) Enables rendering of
  2965. * interactive form elements. The default is `false`.
  2966. */
  2967. /**
  2968. * Simple viewer control to display PDF content/pages.
  2969. * @class
  2970. * @implements {IRenderableView}
  2971. */
  2972. var PDFViewer = function pdfViewer() {
  2973. function PDFPageViewBuffer(size) {
  2974. var data = [];
  2975. this.push = function cachePush(view) {
  2976. var i = data.indexOf(view);
  2977. if (i >= 0) {
  2978. data.splice(i, 1);
  2979. }
  2980. data.push(view);
  2981. if (data.length > size) {
  2982. data.shift().destroy();
  2983. }
  2984. };
  2985. this.resize = function (newSize) {
  2986. size = newSize;
  2987. while (data.length > size) {
  2988. data.shift().destroy();
  2989. }
  2990. };
  2991. }
  2992. function isSameScale(oldScale, newScale) {
  2993. if (newScale === oldScale) {
  2994. return true;
  2995. }
  2996. if (Math.abs(newScale - oldScale) < 1e-15) {
  2997. // Prevent unnecessary re-rendering of all pages when the scale
  2998. // changes only because of limited numerical precision.
  2999. return true;
  3000. }
  3001. return false;
  3002. }
  3003. /**
  3004. * @constructs PDFViewer
  3005. * @param {PDFViewerOptions} options
  3006. */
  3007. function PDFViewer(options) {
  3008. this.container = options.container;
  3009. this.viewer = options.viewer || options.container.firstElementChild;
  3010. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  3011. this.linkService = options.linkService || new SimpleLinkService();
  3012. this.downloadManager = options.downloadManager || null;
  3013. this.removePageBorders = options.removePageBorders || false;
  3014. this.enhanceTextSelection = options.enhanceTextSelection || false;
  3015. this.renderInteractiveForms = options.renderInteractiveForms || false;
  3016. this.defaultRenderingQueue = !options.renderingQueue;
  3017. if (this.defaultRenderingQueue) {
  3018. // Custom rendering queue is not specified, using default one
  3019. this.renderingQueue = new PDFRenderingQueue();
  3020. this.renderingQueue.setViewer(this);
  3021. } else {
  3022. this.renderingQueue = options.renderingQueue;
  3023. }
  3024. this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this));
  3025. this.presentationModeState = PresentationModeState.UNKNOWN;
  3026. this._resetView();
  3027. if (this.removePageBorders) {
  3028. this.viewer.classList.add('removePageBorders');
  3029. }
  3030. }
  3031. PDFViewer.prototype = /** @lends PDFViewer.prototype */
  3032. {
  3033. get pagesCount() {
  3034. return this._pages.length;
  3035. },
  3036. getPageView: function (index) {
  3037. return this._pages[index];
  3038. },
  3039. /**
  3040. * @returns {boolean} true if all {PDFPageView} objects are initialized.
  3041. */
  3042. get pageViewsReady() {
  3043. return this._pageViewsReady;
  3044. },
  3045. /**
  3046. * @returns {number}
  3047. */
  3048. get currentPageNumber() {
  3049. return this._currentPageNumber;
  3050. },
  3051. /**
  3052. * @param {number} val - The page number.
  3053. */
  3054. set currentPageNumber(val) {
  3055. if ((val | 0) !== val) {
  3056. // Ensure that `val` is an integer.
  3057. throw new Error('Invalid page number.');
  3058. }
  3059. if (!this.pdfDocument) {
  3060. this._currentPageNumber = val;
  3061. return;
  3062. }
  3063. // The intent can be to just reset a scroll position and/or scale.
  3064. this._setCurrentPageNumber(val, /* resetCurrentPageView = */
  3065. true);
  3066. },
  3067. /**
  3068. * @private
  3069. */
  3070. _setCurrentPageNumber: function PDFViewer_setCurrentPageNumber(val, resetCurrentPageView) {
  3071. if (this._currentPageNumber === val) {
  3072. if (resetCurrentPageView) {
  3073. this._resetCurrentPageView();
  3074. }
  3075. return;
  3076. }
  3077. if (!(0 < val && val <= this.pagesCount)) {
  3078. console.error('PDFViewer_setCurrentPageNumber: "' + val + '" is out of bounds.');
  3079. return;
  3080. }
  3081. var arg = {
  3082. source: this,
  3083. pageNumber: val
  3084. };
  3085. this._currentPageNumber = val;
  3086. this.eventBus.dispatch('pagechanging', arg);
  3087. this.eventBus.dispatch('pagechange', arg);
  3088. if (resetCurrentPageView) {
  3089. this._resetCurrentPageView();
  3090. }
  3091. },
  3092. /**
  3093. * @returns {number}
  3094. */
  3095. get currentScale() {
  3096. return this._currentScale !== UNKNOWN_SCALE ? this._currentScale : DEFAULT_SCALE;
  3097. },
  3098. /**
  3099. * @param {number} val - Scale of the pages in percents.
  3100. */
  3101. set currentScale(val) {
  3102. if (isNaN(val)) {
  3103. throw new Error('Invalid numeric scale');
  3104. }
  3105. if (!this.pdfDocument) {
  3106. this._currentScale = val;
  3107. this._currentScaleValue = val !== UNKNOWN_SCALE ? val.toString() : null;
  3108. return;
  3109. }
  3110. this._setScale(val, false);
  3111. },
  3112. /**
  3113. * @returns {string}
  3114. */
  3115. get currentScaleValue() {
  3116. return this._currentScaleValue;
  3117. },
  3118. /**
  3119. * @param val - The scale of the pages (in percent or predefined value).
  3120. */
  3121. set currentScaleValue(val) {
  3122. if (!this.pdfDocument) {
  3123. this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val;
  3124. this._currentScaleValue = val.toString();
  3125. return;
  3126. }
  3127. this._setScale(val, false);
  3128. },
  3129. /**
  3130. * @returns {number}
  3131. */
  3132. get pagesRotation() {
  3133. return this._pagesRotation;
  3134. },
  3135. /**
  3136. * @param {number} rotation - The rotation of the pages (0, 90, 180, 270).
  3137. */
  3138. set pagesRotation(rotation) {
  3139. if (!(typeof rotation === 'number' && rotation % 90 === 0)) {
  3140. throw new Error('Invalid pages rotation angle.');
  3141. }
  3142. this._pagesRotation = rotation;
  3143. if (!this.pdfDocument) {
  3144. return;
  3145. }
  3146. for (var i = 0, l = this._pages.length; i < l; i++) {
  3147. var pageView = this._pages[i];
  3148. pageView.update(pageView.scale, rotation);
  3149. }
  3150. this._setScale(this._currentScaleValue, true);
  3151. if (this.defaultRenderingQueue) {
  3152. this.update();
  3153. }
  3154. },
  3155. /**
  3156. * @param pdfDocument {PDFDocument}
  3157. */
  3158. setDocument: function (pdfDocument) {
  3159. if (this.pdfDocument) {
  3160. this._cancelRendering();
  3161. this._resetView();
  3162. }
  3163. this.pdfDocument = pdfDocument;
  3164. if (!pdfDocument) {
  3165. return;
  3166. }
  3167. var pagesCount = pdfDocument.numPages;
  3168. var self = this;
  3169. var resolvePagesPromise;
  3170. var pagesPromise = new Promise(function (resolve) {
  3171. resolvePagesPromise = resolve;
  3172. });
  3173. this.pagesPromise = pagesPromise;
  3174. pagesPromise.then(function () {
  3175. self._pageViewsReady = true;
  3176. self.eventBus.dispatch('pagesloaded', {
  3177. source: self,
  3178. pagesCount: pagesCount
  3179. });
  3180. });
  3181. var isOnePageRenderedResolved = false;
  3182. var resolveOnePageRendered = null;
  3183. var onePageRendered = new Promise(function (resolve) {
  3184. resolveOnePageRendered = resolve;
  3185. });
  3186. this.onePageRendered = onePageRendered;
  3187. var bindOnAfterAndBeforeDraw = function (pageView) {
  3188. pageView.onBeforeDraw = function pdfViewLoadOnBeforeDraw() {
  3189. // Add the page to the buffer at the start of drawing. That way it can
  3190. // be evicted from the buffer and destroyed even if we pause its
  3191. // rendering.
  3192. self._buffer.push(this);
  3193. };
  3194. pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {
  3195. if (!isOnePageRenderedResolved) {
  3196. isOnePageRenderedResolved = true;
  3197. resolveOnePageRendered();
  3198. }
  3199. };
  3200. };
  3201. var firstPagePromise = pdfDocument.getPage(1);
  3202. this.firstPagePromise = firstPagePromise;
  3203. // Fetch a single page so we can get a viewport that will be the default
  3204. // viewport for all pages
  3205. return firstPagePromise.then(function (pdfPage) {
  3206. var scale = this.currentScale;
  3207. var viewport = pdfPage.getViewport(scale * CSS_UNITS);
  3208. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  3209. var textLayerFactory = null;
  3210. if (!pdfjsLib.PDFJS.disableTextLayer) {
  3211. textLayerFactory = this;
  3212. }
  3213. var pageView = new PDFPageView({
  3214. container: this.viewer,
  3215. eventBus: this.eventBus,
  3216. id: pageNum,
  3217. scale: scale,
  3218. defaultViewport: viewport.clone(),
  3219. renderingQueue: this.renderingQueue,
  3220. textLayerFactory: textLayerFactory,
  3221. annotationLayerFactory: this,
  3222. enhanceTextSelection: this.enhanceTextSelection,
  3223. renderInteractiveForms: this.renderInteractiveForms
  3224. });
  3225. bindOnAfterAndBeforeDraw(pageView);
  3226. this._pages.push(pageView);
  3227. }
  3228. var linkService = this.linkService;
  3229. // Fetch all the pages since the viewport is needed before printing
  3230. // starts to create the correct size canvas. Wait until one page is
  3231. // rendered so we don't tie up too many resources early on.
  3232. onePageRendered.then(function () {
  3233. if (!pdfjsLib.PDFJS.disableAutoFetch) {
  3234. var getPagesLeft = pagesCount;
  3235. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  3236. pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) {
  3237. var pageView = self._pages[pageNum - 1];
  3238. if (!pageView.pdfPage) {
  3239. pageView.setPdfPage(pdfPage);
  3240. }
  3241. linkService.cachePageRef(pageNum, pdfPage.ref);
  3242. getPagesLeft--;
  3243. if (!getPagesLeft) {
  3244. resolvePagesPromise();
  3245. }
  3246. }.bind(null, pageNum));
  3247. }
  3248. } else {
  3249. // XXX: Printing is semi-broken with auto fetch disabled.
  3250. resolvePagesPromise();
  3251. }
  3252. });
  3253. self.eventBus.dispatch('pagesinit', { source: self });
  3254. if (this.defaultRenderingQueue) {
  3255. this.update();
  3256. }
  3257. if (this.findController) {
  3258. this.findController.resolveFirstPage();
  3259. }
  3260. }.bind(this));
  3261. },
  3262. _resetView: function () {
  3263. this._pages = [];
  3264. this._currentPageNumber = 1;
  3265. this._currentScale = UNKNOWN_SCALE;
  3266. this._currentScaleValue = null;
  3267. this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
  3268. this._location = null;
  3269. this._pagesRotation = 0;
  3270. this._pagesRequests = [];
  3271. this._pageViewsReady = false;
  3272. // Remove the pages from the DOM.
  3273. this.viewer.textContent = '';
  3274. },
  3275. _scrollUpdate: function PDFViewer_scrollUpdate() {
  3276. if (this.pagesCount === 0) {
  3277. return;
  3278. }
  3279. this.update();
  3280. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  3281. this._pages[i].updatePosition();
  3282. }
  3283. },
  3284. _setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent(newScale, newValue, preset) {
  3285. var arg = {
  3286. source: this,
  3287. scale: newScale,
  3288. presetValue: preset ? newValue : undefined
  3289. };
  3290. this.eventBus.dispatch('scalechanging', arg);
  3291. this.eventBus.dispatch('scalechange', arg);
  3292. },
  3293. _setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(newScale, newValue, noScroll, preset) {
  3294. this._currentScaleValue = newValue.toString();
  3295. if (isSameScale(this._currentScale, newScale)) {
  3296. if (preset) {
  3297. this._setScaleDispatchEvent(newScale, newValue, true);
  3298. }
  3299. return;
  3300. }
  3301. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  3302. this._pages[i].update(newScale);
  3303. }
  3304. this._currentScale = newScale;
  3305. if (!noScroll) {
  3306. var page = this._currentPageNumber, dest;
  3307. if (this._location && !pdfjsLib.PDFJS.ignoreCurrentPositionOnZoom && !(this.isInPresentationMode || this.isChangingPresentationMode)) {
  3308. page = this._location.pageNumber;
  3309. dest = [
  3310. null,
  3311. { name: 'XYZ' },
  3312. this._location.left,
  3313. this._location.top,
  3314. null
  3315. ];
  3316. }
  3317. this.scrollPageIntoView({
  3318. pageNumber: page,
  3319. destArray: dest,
  3320. allowNegativeOffset: true
  3321. });
  3322. }
  3323. this._setScaleDispatchEvent(newScale, newValue, preset);
  3324. if (this.defaultRenderingQueue) {
  3325. this.update();
  3326. }
  3327. },
  3328. _setScale: function PDFViewer_setScale(value, noScroll) {
  3329. var scale = parseFloat(value);
  3330. if (scale > 0) {
  3331. this._setScaleUpdatePages(scale, value, noScroll, false);
  3332. } else {
  3333. var currentPage = this._pages[this._currentPageNumber - 1];
  3334. if (!currentPage) {
  3335. return;
  3336. }
  3337. var hPadding = this.isInPresentationMode || this.removePageBorders ? 0 : SCROLLBAR_PADDING;
  3338. var vPadding = this.isInPresentationMode || this.removePageBorders ? 0 : VERTICAL_PADDING;
  3339. var pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale;
  3340. var pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale;
  3341. switch (value) {
  3342. case 'page-actual':
  3343. scale = 1;
  3344. break;
  3345. case 'page-width':
  3346. scale = pageWidthScale;
  3347. break;
  3348. case 'page-height':
  3349. scale = pageHeightScale;
  3350. break;
  3351. case 'page-fit':
  3352. scale = Math.min(pageWidthScale, pageHeightScale);
  3353. break;
  3354. case 'auto':
  3355. var isLandscape = currentPage.width > currentPage.height;
  3356. // For pages in landscape mode, fit the page height to the viewer
  3357. // *unless* the page would thus become too wide to fit horizontally.
  3358. var horizontalScale = isLandscape ? Math.min(pageHeightScale, pageWidthScale) : pageWidthScale;
  3359. scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
  3360. break;
  3361. default:
  3362. console.error('PDFViewer_setScale: "' + value + '" is an unknown zoom value.');
  3363. return;
  3364. }
  3365. this._setScaleUpdatePages(scale, value, noScroll, true);
  3366. }
  3367. },
  3368. /**
  3369. * Refreshes page view: scrolls to the current page and updates the scale.
  3370. * @private
  3371. */
  3372. _resetCurrentPageView: function () {
  3373. if (this.isInPresentationMode) {
  3374. // Fixes the case when PDF has different page sizes.
  3375. this._setScale(this._currentScaleValue, true);
  3376. }
  3377. var pageView = this._pages[this._currentPageNumber - 1];
  3378. scrollIntoView(pageView.div);
  3379. },
  3380. /**
  3381. * @typedef ScrollPageIntoViewParameters
  3382. * @property {number} pageNumber - The page number.
  3383. * @property {Array} destArray - (optional) The original PDF destination
  3384. * array, in the format: <page-ref> </XYZ|/FitXXX> <args..>
  3385. * @property {boolean} allowNegativeOffset - (optional) Allow negative page
  3386. * offsets. The default value is `false`.
  3387. */
  3388. /**
  3389. * Scrolls page into view.
  3390. * @param {ScrollPageIntoViewParameters} params
  3391. */
  3392. scrollPageIntoView: function PDFViewer_scrollPageIntoView(params) {
  3393. if (!this.pdfDocument) {
  3394. return;
  3395. }
  3396. if (arguments.length > 1 || typeof params === 'number') {
  3397. console.warn('Call of scrollPageIntoView() with obsolete signature.');
  3398. var paramObj = {};
  3399. if (typeof params === 'number') {
  3400. paramObj.pageNumber = params;
  3401. }
  3402. // pageNumber argument was found.
  3403. if (arguments[1] instanceof Array) {
  3404. paramObj.destArray = arguments[1];
  3405. }
  3406. // destArray argument was found.
  3407. params = paramObj;
  3408. }
  3409. var pageNumber = params.pageNumber || 0;
  3410. var dest = params.destArray || null;
  3411. var allowNegativeOffset = params.allowNegativeOffset || false;
  3412. if (this.isInPresentationMode || !dest) {
  3413. this._setCurrentPageNumber(pageNumber, /* resetCurrentPageView */
  3414. true);
  3415. return;
  3416. }
  3417. var pageView = this._pages[pageNumber - 1];
  3418. if (!pageView) {
  3419. console.error('PDFViewer_scrollPageIntoView: ' + 'Invalid "pageNumber" parameter.');
  3420. return;
  3421. }
  3422. var x = 0, y = 0;
  3423. var width = 0, height = 0, widthScale, heightScale;
  3424. var changeOrientation = pageView.rotation % 180 === 0 ? false : true;
  3425. var pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / CSS_UNITS;
  3426. var pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / CSS_UNITS;
  3427. var scale = 0;
  3428. switch (dest[1].name) {
  3429. case 'XYZ':
  3430. x = dest[2];
  3431. y = dest[3];
  3432. scale = dest[4];
  3433. // If x and/or y coordinates are not supplied, default to
  3434. // _top_ left of the page (not the obvious bottom left,
  3435. // since aligning the bottom of the intended page with the
  3436. // top of the window is rarely helpful).
  3437. x = x !== null ? x : 0;
  3438. y = y !== null ? y : pageHeight;
  3439. break;
  3440. case 'Fit':
  3441. case 'FitB':
  3442. scale = 'page-fit';
  3443. break;
  3444. case 'FitH':
  3445. case 'FitBH':
  3446. y = dest[2];
  3447. scale = 'page-width';
  3448. // According to the PDF spec, section 12.3.2.2, a `null` value in the
  3449. // parameter should maintain the position relative to the new page.
  3450. if (y === null && this._location) {
  3451. x = this._location.left;
  3452. y = this._location.top;
  3453. }
  3454. break;
  3455. case 'FitV':
  3456. case 'FitBV':
  3457. x = dest[2];
  3458. width = pageWidth;
  3459. height = pageHeight;
  3460. scale = 'page-height';
  3461. break;
  3462. case 'FitR':
  3463. x = dest[2];
  3464. y = dest[3];
  3465. width = dest[4] - x;
  3466. height = dest[5] - y;
  3467. var hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING;
  3468. var vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING;
  3469. widthScale = (this.container.clientWidth - hPadding) / width / CSS_UNITS;
  3470. heightScale = (this.container.clientHeight - vPadding) / height / CSS_UNITS;
  3471. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  3472. break;
  3473. default:
  3474. console.error('PDFViewer_scrollPageIntoView: \'' + dest[1].name + '\' is not a valid destination type.');
  3475. return;
  3476. }
  3477. if (scale && scale !== this._currentScale) {
  3478. this.currentScaleValue = scale;
  3479. } else if (this._currentScale === UNKNOWN_SCALE) {
  3480. this.currentScaleValue = DEFAULT_SCALE_VALUE;
  3481. }
  3482. if (scale === 'page-fit' && !dest[4]) {
  3483. scrollIntoView(pageView.div);
  3484. return;
  3485. }
  3486. var boundingRect = [
  3487. pageView.viewport.convertToViewportPoint(x, y),
  3488. pageView.viewport.convertToViewportPoint(x + width, y + height)
  3489. ];
  3490. var left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  3491. var top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  3492. if (!allowNegativeOffset) {
  3493. // Some bad PDF generators will create destinations with e.g. top values
  3494. // that exceeds the page height. Ensure that offsets are not negative,
  3495. // to prevent a previous page from becoming visible (fixes bug 874482).
  3496. left = Math.max(left, 0);
  3497. top = Math.max(top, 0);
  3498. }
  3499. scrollIntoView(pageView.div, {
  3500. left: left,
  3501. top: top
  3502. });
  3503. },
  3504. _updateLocation: function (firstPage) {
  3505. var currentScale = this._currentScale;
  3506. var currentScaleValue = this._currentScaleValue;
  3507. var normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue;
  3508. var pageNumber = firstPage.id;
  3509. var pdfOpenParams = '#page=' + pageNumber;
  3510. pdfOpenParams += '&zoom=' + normalizedScaleValue;
  3511. var currentPageView = this._pages[pageNumber - 1];
  3512. var container = this.container;
  3513. var topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y);
  3514. var intLeft = Math.round(topLeft[0]);
  3515. var intTop = Math.round(topLeft[1]);
  3516. pdfOpenParams += ',' + intLeft + ',' + intTop;
  3517. this._location = {
  3518. pageNumber: pageNumber,
  3519. scale: normalizedScaleValue,
  3520. top: intTop,
  3521. left: intLeft,
  3522. pdfOpenParams: pdfOpenParams
  3523. };
  3524. },
  3525. update: function PDFViewer_update() {
  3526. var visible = this._getVisiblePages();
  3527. var visiblePages = visible.views;
  3528. if (visiblePages.length === 0) {
  3529. return;
  3530. }
  3531. var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * visiblePages.length + 1);
  3532. this._buffer.resize(suggestedCacheSize);
  3533. this.renderingQueue.renderHighestPriority(visible);
  3534. var currentId = this._currentPageNumber;
  3535. var firstPage = visible.first;
  3536. for (var i = 0, ii = visiblePages.length, stillFullyVisible = false; i < ii; ++i) {
  3537. var page = visiblePages[i];
  3538. if (page.percent < 100) {
  3539. break;
  3540. }
  3541. if (page.id === currentId) {
  3542. stillFullyVisible = true;
  3543. break;
  3544. }
  3545. }
  3546. if (!stillFullyVisible) {
  3547. currentId = visiblePages[0].id;
  3548. }
  3549. if (!this.isInPresentationMode) {
  3550. this._setCurrentPageNumber(currentId);
  3551. }
  3552. this._updateLocation(firstPage);
  3553. this.eventBus.dispatch('updateviewarea', {
  3554. source: this,
  3555. location: this._location
  3556. });
  3557. },
  3558. containsElement: function (element) {
  3559. return this.container.contains(element);
  3560. },
  3561. focus: function () {
  3562. this.container.focus();
  3563. },
  3564. get isInPresentationMode() {
  3565. return this.presentationModeState === PresentationModeState.FULLSCREEN;
  3566. },
  3567. get isChangingPresentationMode() {
  3568. return this.presentationModeState === PresentationModeState.CHANGING;
  3569. },
  3570. get isHorizontalScrollbarEnabled() {
  3571. return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth;
  3572. },
  3573. _getVisiblePages: function () {
  3574. if (!this.isInPresentationMode) {
  3575. return getVisibleElements(this.container, this._pages, true);
  3576. } else {
  3577. // The algorithm in getVisibleElements doesn't work in all browsers and
  3578. // configurations when presentation mode is active.
  3579. var visible = [];
  3580. var currentPage = this._pages[this._currentPageNumber - 1];
  3581. visible.push({
  3582. id: currentPage.id,
  3583. view: currentPage
  3584. });
  3585. return {
  3586. first: currentPage,
  3587. last: currentPage,
  3588. views: visible
  3589. };
  3590. }
  3591. },
  3592. cleanup: function () {
  3593. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  3594. if (this._pages[i] && this._pages[i].renderingState !== RenderingStates.FINISHED) {
  3595. this._pages[i].reset();
  3596. }
  3597. }
  3598. },
  3599. /**
  3600. * @private
  3601. */
  3602. _cancelRendering: function PDFViewer_cancelRendering() {
  3603. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  3604. if (this._pages[i]) {
  3605. this._pages[i].cancelRendering();
  3606. }
  3607. }
  3608. },
  3609. /**
  3610. * @param {PDFPageView} pageView
  3611. * @returns {PDFPage}
  3612. * @private
  3613. */
  3614. _ensurePdfPageLoaded: function (pageView) {
  3615. if (pageView.pdfPage) {
  3616. return Promise.resolve(pageView.pdfPage);
  3617. }
  3618. var pageNumber = pageView.id;
  3619. if (this._pagesRequests[pageNumber]) {
  3620. return this._pagesRequests[pageNumber];
  3621. }
  3622. var promise = this.pdfDocument.getPage(pageNumber).then(function (pdfPage) {
  3623. pageView.setPdfPage(pdfPage);
  3624. this._pagesRequests[pageNumber] = null;
  3625. return pdfPage;
  3626. }.bind(this));
  3627. this._pagesRequests[pageNumber] = promise;
  3628. return promise;
  3629. },
  3630. forceRendering: function (currentlyVisiblePages) {
  3631. var visiblePages = currentlyVisiblePages || this._getVisiblePages();
  3632. var pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, this.scroll.down);
  3633. if (pageView) {
  3634. this._ensurePdfPageLoaded(pageView).then(function () {
  3635. this.renderingQueue.renderView(pageView);
  3636. }.bind(this));
  3637. return true;
  3638. }
  3639. return false;
  3640. },
  3641. getPageTextContent: function (pageIndex) {
  3642. return this.pdfDocument.getPage(pageIndex + 1).then(function (page) {
  3643. return page.getTextContent({ normalizeWhitespace: true });
  3644. });
  3645. },
  3646. /**
  3647. * @param {HTMLDivElement} textLayerDiv
  3648. * @param {number} pageIndex
  3649. * @param {PageViewport} viewport
  3650. * @returns {TextLayerBuilder}
  3651. */
  3652. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport, enhanceTextSelection) {
  3653. return new TextLayerBuilder({
  3654. textLayerDiv: textLayerDiv,
  3655. eventBus: this.eventBus,
  3656. pageIndex: pageIndex,
  3657. viewport: viewport,
  3658. findController: this.isInPresentationMode ? null : this.findController,
  3659. enhanceTextSelection: this.isInPresentationMode ? false : enhanceTextSelection
  3660. });
  3661. },
  3662. /**
  3663. * @param {HTMLDivElement} pageDiv
  3664. * @param {PDFPage} pdfPage
  3665. * @param {boolean} renderInteractiveForms
  3666. * @returns {AnnotationLayerBuilder}
  3667. */
  3668. createAnnotationLayerBuilder: function (pageDiv, pdfPage, renderInteractiveForms) {
  3669. return new AnnotationLayerBuilder({
  3670. pageDiv: pageDiv,
  3671. pdfPage: pdfPage,
  3672. renderInteractiveForms: renderInteractiveForms,
  3673. linkService: this.linkService,
  3674. downloadManager: this.downloadManager
  3675. });
  3676. },
  3677. setFindController: function (findController) {
  3678. this.findController = findController;
  3679. },
  3680. /**
  3681. * Returns sizes of the pages.
  3682. * @returns {Array} Array of objects with width/height fields.
  3683. */
  3684. getPagesOverview: function () {
  3685. return this._pages.map(function (pageView) {
  3686. var viewport = pageView.pdfPage.getViewport(1);
  3687. return {
  3688. width: viewport.width,
  3689. height: viewport.height
  3690. };
  3691. });
  3692. }
  3693. };
  3694. return PDFViewer;
  3695. }();
  3696. exports.PresentationModeState = PresentationModeState;
  3697. exports.PDFViewer = PDFViewer;
  3698. }));
  3699. }.call(pdfViewerLibs));
  3700. var PDFJS = pdfjsLib.PDFJS;
  3701. PDFJS.PDFViewer = pdfViewerLibs.pdfjsWebPDFViewer.PDFViewer;
  3702. PDFJS.PDFPageView = pdfViewerLibs.pdfjsWebPDFPageView.PDFPageView;
  3703. PDFJS.PDFLinkService = pdfViewerLibs.pdfjsWebPDFLinkService.PDFLinkService;
  3704. PDFJS.TextLayerBuilder = pdfViewerLibs.pdfjsWebTextLayerBuilder.TextLayerBuilder;
  3705. PDFJS.DefaultTextLayerFactory = pdfViewerLibs.pdfjsWebTextLayerBuilder.DefaultTextLayerFactory;
  3706. PDFJS.AnnotationLayerBuilder = pdfViewerLibs.pdfjsWebAnnotationLayerBuilder.AnnotationLayerBuilder;
  3707. PDFJS.DefaultAnnotationLayerFactory = pdfViewerLibs.pdfjsWebAnnotationLayerBuilder.DefaultAnnotationLayerFactory;
  3708. PDFJS.PDFHistory = pdfViewerLibs.pdfjsWebPDFHistory.PDFHistory;
  3709. PDFJS.PDFFindController = pdfViewerLibs.pdfjsWebPDFFindController.PDFFindController;
  3710. PDFJS.EventBus = pdfViewerLibs.pdfjsWebUIUtils.EventBus;
  3711. PDFJS.DownloadManager = pdfViewerLibs.pdfjsWebDownloadManager.DownloadManager;
  3712. PDFJS.ProgressBar = pdfViewerLibs.pdfjsWebUIUtils.ProgressBar;
  3713. exports.PDFJS = PDFJS;
  3714. }));