ui_utils.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* Copyright 2012 Mozilla Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. 'use strict';
  17. var CSS_UNITS = 96.0 / 72.0;
  18. var DEFAULT_SCALE = 'auto';
  19. var UNKNOWN_SCALE = 0;
  20. var MAX_AUTO_SCALE = 1.25;
  21. var SCROLLBAR_PADDING = 40;
  22. var VERTICAL_PADDING = 5;
  23. // optimised CSS custom property getter/setter
  24. var CustomStyle = (function CustomStyleClosure() {
  25. // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
  26. // animate-css-transforms-firefox-webkit.html
  27. // in some versions of IE9 it is critical that ms appear in this list
  28. // before Moz
  29. var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
  30. var _cache = {};
  31. function CustomStyle() {}
  32. CustomStyle.getProp = function get(propName, element) {
  33. // check cache only when no element is given
  34. if (arguments.length === 1 && typeof _cache[propName] === 'string') {
  35. return _cache[propName];
  36. }
  37. element = element || document.documentElement;
  38. var style = element.style, prefixed, uPropName;
  39. // test standard property first
  40. if (typeof style[propName] === 'string') {
  41. return (_cache[propName] = propName);
  42. }
  43. // capitalize
  44. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  45. // test vendor specific properties
  46. for (var i = 0, l = prefixes.length; i < l; i++) {
  47. prefixed = prefixes[i] + uPropName;
  48. if (typeof style[prefixed] === 'string') {
  49. return (_cache[propName] = prefixed);
  50. }
  51. }
  52. //if all fails then set to undefined
  53. return (_cache[propName] = 'undefined');
  54. };
  55. CustomStyle.setProp = function set(propName, element, str) {
  56. var prop = this.getProp(propName);
  57. if (prop !== 'undefined') {
  58. element.style[prop] = str;
  59. }
  60. };
  61. return CustomStyle;
  62. })();
  63. function getFileName(url) {
  64. var anchor = url.indexOf('#');
  65. var query = url.indexOf('?');
  66. var end = Math.min(
  67. anchor > 0 ? anchor : url.length,
  68. query > 0 ? query : url.length);
  69. return url.substring(url.lastIndexOf('/', end) + 1, end);
  70. }
  71. /**
  72. * Returns scale factor for the canvas. It makes sense for the HiDPI displays.
  73. * @return {Object} The object with horizontal (sx) and vertical (sy)
  74. scales. The scaled property is set to false if scaling is
  75. not required, true otherwise.
  76. */
  77. function getOutputScale(ctx) {
  78. var devicePixelRatio = window.devicePixelRatio || 1;
  79. var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
  80. ctx.mozBackingStorePixelRatio ||
  81. ctx.msBackingStorePixelRatio ||
  82. ctx.oBackingStorePixelRatio ||
  83. ctx.backingStorePixelRatio || 1;
  84. var pixelRatio = devicePixelRatio / backingStoreRatio;
  85. return {
  86. sx: pixelRatio,
  87. sy: pixelRatio,
  88. scaled: pixelRatio !== 1
  89. };
  90. }
  91. /**
  92. * Scrolls specified element into view of its parent.
  93. * element {Object} The element to be visible.
  94. * spot {Object} An object with optional top and left properties,
  95. * specifying the offset from the top left edge.
  96. */
  97. function scrollIntoView(element, spot) {
  98. // Assuming offsetParent is available (it's not available when viewer is in
  99. // hidden iframe or object). We have to scroll: if the offsetParent is not set
  100. // producing the error. See also animationStartedClosure.
  101. var parent = element.offsetParent;
  102. var offsetY = element.offsetTop + element.clientTop;
  103. var offsetX = element.offsetLeft + element.clientLeft;
  104. if (!parent) {
  105. console.error('offsetParent is not set -- cannot scroll');
  106. return;
  107. }
  108. while (parent.clientHeight === parent.scrollHeight) {
  109. if (parent.dataset._scaleY) {
  110. offsetY /= parent.dataset._scaleY;
  111. offsetX /= parent.dataset._scaleX;
  112. }
  113. offsetY += parent.offsetTop;
  114. offsetX += parent.offsetLeft;
  115. parent = parent.offsetParent;
  116. if (!parent) {
  117. return; // no need to scroll
  118. }
  119. }
  120. if (spot) {
  121. if (spot.top !== undefined) {
  122. offsetY += spot.top;
  123. }
  124. if (spot.left !== undefined) {
  125. offsetX += spot.left;
  126. parent.scrollLeft = offsetX;
  127. }
  128. }
  129. parent.scrollTop = offsetY;
  130. }
  131. /**
  132. * Helper function to start monitoring the scroll event and converting them into
  133. * PDF.js friendly one: with scroll debounce and scroll direction.
  134. */
  135. function watchScroll(viewAreaElement, callback) {
  136. var debounceScroll = function debounceScroll(evt) {
  137. if (rAF) {
  138. return;
  139. }
  140. // schedule an invocation of scroll for next animation frame.
  141. rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
  142. rAF = null;
  143. var currentY = viewAreaElement.scrollTop;
  144. var lastY = state.lastY;
  145. if (currentY !== lastY) {
  146. state.down = currentY > lastY;
  147. }
  148. state.lastY = currentY;
  149. callback(state);
  150. });
  151. };
  152. var state = {
  153. down: true,
  154. lastY: viewAreaElement.scrollTop,
  155. _eventHandler: debounceScroll
  156. };
  157. var rAF = null;
  158. viewAreaElement.addEventListener('scroll', debounceScroll, true);
  159. return state;
  160. }
  161. /**
  162. * Use binary search to find the index of the first item in a given array which
  163. * passes a given condition. The items are expected to be sorted in the sense
  164. * that if the condition is true for one item in the array, then it is also true
  165. * for all following items.
  166. *
  167. * @returns {Number} Index of the first array element to pass the test,
  168. * or |items.length| if no such element exists.
  169. */
  170. function binarySearchFirstItem(items, condition) {
  171. var minIndex = 0;
  172. var maxIndex = items.length - 1;
  173. if (items.length === 0 || !condition(items[maxIndex])) {
  174. return items.length;
  175. }
  176. if (condition(items[minIndex])) {
  177. return minIndex;
  178. }
  179. while (minIndex < maxIndex) {
  180. var currentIndex = (minIndex + maxIndex) >> 1;
  181. var currentItem = items[currentIndex];
  182. if (condition(currentItem)) {
  183. maxIndex = currentIndex;
  184. } else {
  185. minIndex = currentIndex + 1;
  186. }
  187. }
  188. return minIndex; /* === maxIndex */
  189. }
  190. /**
  191. * Generic helper to find out what elements are visible within a scroll pane.
  192. */
  193. function getVisibleElements(scrollEl, views, sortByVisibility) {
  194. var top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight;
  195. var left = scrollEl.scrollLeft, right = left + scrollEl.clientWidth;
  196. function isElementBottomBelowViewTop(view) {
  197. var element = view.div;
  198. var elementBottom =
  199. element.offsetTop + element.clientTop + element.clientHeight;
  200. return elementBottom > top;
  201. }
  202. var visible = [], view, element;
  203. var currentHeight, viewHeight, hiddenHeight, percentHeight;
  204. var currentWidth, viewWidth;
  205. var firstVisibleElementInd = (views.length === 0) ? 0 :
  206. binarySearchFirstItem(views, isElementBottomBelowViewTop);
  207. for (var i = firstVisibleElementInd, ii = views.length; i < ii; i++) {
  208. view = views[i];
  209. element = view.div;
  210. currentHeight = element.offsetTop + element.clientTop;
  211. viewHeight = element.clientHeight;
  212. if (currentHeight > bottom) {
  213. break;
  214. }
  215. currentWidth = element.offsetLeft + element.clientLeft;
  216. viewWidth = element.clientWidth;
  217. if (currentWidth + viewWidth < left || currentWidth > right) {
  218. continue;
  219. }
  220. hiddenHeight = Math.max(0, top - currentHeight) +
  221. Math.max(0, currentHeight + viewHeight - bottom);
  222. percentHeight = ((viewHeight - hiddenHeight) * 100 / viewHeight) | 0;
  223. visible.push({
  224. id: view.id,
  225. x: currentWidth,
  226. y: currentHeight,
  227. view: view,
  228. percent: percentHeight
  229. });
  230. }
  231. var first = visible[0];
  232. var last = visible[visible.length - 1];
  233. if (sortByVisibility) {
  234. visible.sort(function(a, b) {
  235. var pc = a.percent - b.percent;
  236. if (Math.abs(pc) > 0.001) {
  237. return -pc;
  238. }
  239. return a.id - b.id; // ensure stability
  240. });
  241. }
  242. return {first: first, last: last, views: visible};
  243. }
  244. /**
  245. * Event handler to suppress context menu.
  246. */
  247. function noContextMenuHandler(e) {
  248. e.preventDefault();
  249. }
  250. /**
  251. * Returns the filename or guessed filename from the url (see issue 3455).
  252. * url {String} The original PDF location.
  253. * @return {String} Guessed PDF file name.
  254. */
  255. function getPDFFileNameFromURL(url) {
  256. var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  257. // SCHEME HOST 1.PATH 2.QUERY 3.REF
  258. // Pattern to get last matching NAME.pdf
  259. var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  260. var splitURI = reURI.exec(url);
  261. var suggestedFilename = reFilename.exec(splitURI[1]) ||
  262. reFilename.exec(splitURI[2]) ||
  263. reFilename.exec(splitURI[3]);
  264. if (suggestedFilename) {
  265. suggestedFilename = suggestedFilename[0];
  266. if (suggestedFilename.indexOf('%') !== -1) {
  267. // URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
  268. try {
  269. suggestedFilename =
  270. reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  271. } catch(e) { // Possible (extremely rare) errors:
  272. // URIError "Malformed URI", e.g. for "%AA.pdf"
  273. // TypeError "null has no properties", e.g. for "%2F.pdf"
  274. }
  275. }
  276. }
  277. return suggestedFilename || 'document.pdf';
  278. }
  279. var ProgressBar = (function ProgressBarClosure() {
  280. function clamp(v, min, max) {
  281. return Math.min(Math.max(v, min), max);
  282. }
  283. function ProgressBar(id, opts) {
  284. this.visible = true;
  285. // Fetch the sub-elements for later.
  286. this.div = document.querySelector(id + ' .progress');
  287. // Get the loading bar element, so it can be resized to fit the viewer.
  288. this.bar = this.div.parentNode;
  289. // Get options, with sensible defaults.
  290. this.height = opts.height || 100;
  291. this.width = opts.width || 100;
  292. this.units = opts.units || '%';
  293. // Initialize heights.
  294. this.div.style.height = this.height + this.units;
  295. this.percent = 0;
  296. }
  297. ProgressBar.prototype = {
  298. updateBar: function ProgressBar_updateBar() {
  299. if (this._indeterminate) {
  300. this.div.classList.add('indeterminate');
  301. this.div.style.width = this.width + this.units;
  302. return;
  303. }
  304. this.div.classList.remove('indeterminate');
  305. var progressSize = this.width * this._percent / 100;
  306. this.div.style.width = progressSize + this.units;
  307. },
  308. get percent() {
  309. return this._percent;
  310. },
  311. set percent(val) {
  312. this._indeterminate = isNaN(val);
  313. this._percent = clamp(val, 0, 100);
  314. this.updateBar();
  315. },
  316. setWidth: function ProgressBar_setWidth(viewer) {
  317. if (viewer) {
  318. var container = viewer.parentNode;
  319. var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
  320. if (scrollbarWidth > 0) {
  321. this.bar.setAttribute('style', 'width: calc(100% - ' +
  322. scrollbarWidth + 'px);');
  323. }
  324. }
  325. },
  326. hide: function ProgressBar_hide() {
  327. if (!this.visible) {
  328. return;
  329. }
  330. this.visible = false;
  331. this.bar.classList.add('hidden');
  332. document.body.classList.remove('loadingInProgress');
  333. },
  334. show: function ProgressBar_show() {
  335. if (this.visible) {
  336. return;
  337. }
  338. this.visible = true;
  339. document.body.classList.add('loadingInProgress');
  340. this.bar.classList.remove('hidden');
  341. }
  342. };
  343. return ProgressBar;
  344. })();