pdf_viewer.js 153 KB

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