pdf_viewer.js 152 KB

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