ui_utils.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. // optimised CSS custom property getter/setter
  18. var CustomStyle = (function CustomStyleClosure() {
  19. // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
  20. // animate-css-transforms-firefox-webkit.html
  21. // in some versions of IE9 it is critical that ms appear in this list
  22. // before Moz
  23. var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
  24. var _cache = { };
  25. function CustomStyle() {
  26. }
  27. CustomStyle.getProp = function get(propName, element) {
  28. // check cache only when no element is given
  29. if (arguments.length == 1 && typeof _cache[propName] == 'string') {
  30. return _cache[propName];
  31. }
  32. element = element || document.documentElement;
  33. var style = element.style, prefixed, uPropName;
  34. // test standard property first
  35. if (typeof style[propName] == 'string') {
  36. return (_cache[propName] = propName);
  37. }
  38. // capitalize
  39. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  40. // test vendor specific properties
  41. for (var i = 0, l = prefixes.length; i < l; i++) {
  42. prefixed = prefixes[i] + uPropName;
  43. if (typeof style[prefixed] == 'string') {
  44. return (_cache[propName] = prefixed);
  45. }
  46. }
  47. //if all fails then set to undefined
  48. return (_cache[propName] = 'undefined');
  49. };
  50. CustomStyle.setProp = function set(propName, element, str) {
  51. var prop = this.getProp(propName);
  52. if (prop != 'undefined')
  53. element.style[prop] = str;
  54. };
  55. return CustomStyle;
  56. })();
  57. function getFileName(url) {
  58. var anchor = url.indexOf('#');
  59. var query = url.indexOf('?');
  60. var end = Math.min(
  61. anchor > 0 ? anchor : url.length,
  62. query > 0 ? query : url.length);
  63. return url.substring(url.lastIndexOf('/', end) + 1, end);
  64. }
  65. /**
  66. * Returns scale factor for the canvas. It makes sense for the HiDPI displays.
  67. * @return {Object} The object with horizontal (sx) and vertical (sy)
  68. scales. The scaled property is set to false if scaling is
  69. not required, true otherwise.
  70. */
  71. function getOutputScale(ctx) {
  72. var devicePixelRatio = window.devicePixelRatio || 1;
  73. var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
  74. ctx.mozBackingStorePixelRatio ||
  75. ctx.msBackingStorePixelRatio ||
  76. ctx.oBackingStorePixelRatio ||
  77. ctx.backingStorePixelRatio || 1;
  78. var pixelRatio = devicePixelRatio / backingStoreRatio;
  79. return {
  80. sx: pixelRatio,
  81. sy: pixelRatio,
  82. scaled: pixelRatio != 1
  83. };
  84. }
  85. /**
  86. * Scrolls specified element into view of its parent.
  87. * element {Object} The element to be visible.
  88. * spot {Object} An object with optional top and left properties,
  89. * specifying the offset from the top left edge.
  90. */
  91. function scrollIntoView(element, spot) {
  92. // Assuming offsetParent is available (it's not available when viewer is in
  93. // hidden iframe or object). We have to scroll: if the offsetParent is not set
  94. // producing the error. See also animationStartedClosure.
  95. var parent = element.offsetParent;
  96. var offsetY = element.offsetTop + element.clientTop;
  97. var offsetX = element.offsetLeft + element.clientLeft;
  98. if (!parent) {
  99. console.error('offsetParent is not set -- cannot scroll');
  100. return;
  101. }
  102. while (parent.clientHeight === parent.scrollHeight) {
  103. if (parent.dataset._scaleY) {
  104. offsetY /= parent.dataset._scaleY;
  105. offsetX /= parent.dataset._scaleX;
  106. }
  107. offsetY += parent.offsetTop;
  108. offsetX += parent.offsetLeft;
  109. parent = parent.offsetParent;
  110. if (!parent) {
  111. return; // no need to scroll
  112. }
  113. }
  114. if (spot) {
  115. if (spot.top !== undefined) {
  116. offsetY += spot.top;
  117. }
  118. if (spot.left !== undefined) {
  119. offsetX += spot.left;
  120. parent.scrollLeft = offsetX;
  121. }
  122. }
  123. parent.scrollTop = offsetY;
  124. }
  125. /**
  126. * Event handler to suppress context menu.
  127. */
  128. function noContextMenuHandler(e) {
  129. e.preventDefault();
  130. }
  131. /**
  132. * Returns the filename or guessed filename from the url (see issue 3455).
  133. * url {String} The original PDF location.
  134. * @return {String} Guessed PDF file name.
  135. */
  136. function getPDFFileNameFromURL(url) {
  137. var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  138. // SCHEME HOST 1.PATH 2.QUERY 3.REF
  139. // Pattern to get last matching NAME.pdf
  140. var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  141. var splitURI = reURI.exec(url);
  142. var suggestedFilename = reFilename.exec(splitURI[1]) ||
  143. reFilename.exec(splitURI[2]) ||
  144. reFilename.exec(splitURI[3]);
  145. if (suggestedFilename) {
  146. suggestedFilename = suggestedFilename[0];
  147. if (suggestedFilename.indexOf('%') != -1) {
  148. // URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
  149. try {
  150. suggestedFilename =
  151. reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  152. } catch(e) { // Possible (extremely rare) errors:
  153. // URIError "Malformed URI", e.g. for "%AA.pdf"
  154. // TypeError "null has no properties", e.g. for "%2F.pdf"
  155. }
  156. }
  157. }
  158. return suggestedFilename || 'document.pdf';
  159. }
  160. var ProgressBar = (function ProgressBarClosure() {
  161. function clamp(v, min, max) {
  162. return Math.min(Math.max(v, min), max);
  163. }
  164. function ProgressBar(id, opts) {
  165. // Fetch the sub-elements for later.
  166. this.div = document.querySelector(id + ' .progress');
  167. // Get the loading bar element, so it can be resized to fit the viewer.
  168. this.bar = this.div.parentNode;
  169. // Get options, with sensible defaults.
  170. this.height = opts.height || 100;
  171. this.width = opts.width || 100;
  172. this.units = opts.units || '%';
  173. // Initialize heights.
  174. this.div.style.height = this.height + this.units;
  175. this.percent = 0;
  176. }
  177. ProgressBar.prototype = {
  178. updateBar: function ProgressBar_updateBar() {
  179. if (this._indeterminate) {
  180. this.div.classList.add('indeterminate');
  181. this.div.style.width = this.width + this.units;
  182. return;
  183. }
  184. this.div.classList.remove('indeterminate');
  185. var progressSize = this.width * this._percent / 100;
  186. this.div.style.width = progressSize + this.units;
  187. },
  188. get percent() {
  189. return this._percent;
  190. },
  191. set percent(val) {
  192. this._indeterminate = isNaN(val);
  193. this._percent = clamp(val, 0, 100);
  194. this.updateBar();
  195. },
  196. setWidth: function ProgressBar_setWidth(viewer) {
  197. if (viewer) {
  198. var container = viewer.parentNode;
  199. var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
  200. if (scrollbarWidth > 0) {
  201. this.bar.setAttribute('style', 'width: calc(100% - ' +
  202. scrollbarWidth + 'px);');
  203. }
  204. }
  205. },
  206. hide: function ProgressBar_hide() {
  207. this.bar.classList.add('hidden');
  208. this.bar.removeAttribute('style');
  209. }
  210. };
  211. return ProgressBar;
  212. })();
  213. var Cache = function cacheCache(size) {
  214. var data = [];
  215. this.push = function cachePush(view) {
  216. var i = data.indexOf(view);
  217. if (i >= 0)
  218. data.splice(i);
  219. data.push(view);
  220. if (data.length > size)
  221. data.shift().destroy();
  222. };
  223. };
  224. //#if !(FIREFOX || MOZCENTRAL || B2G)
  225. var isLocalStorageEnabled = (function isLocalStorageEnabledClosure() {
  226. // Feature test as per http://diveintohtml5.info/storage.html
  227. // The additional localStorage call is to get around a FF quirk, see
  228. // bug #495747 in bugzilla
  229. try {
  230. return ('localStorage' in window && window['localStorage'] !== null &&
  231. localStorage);
  232. } catch (e) {
  233. return false;
  234. }
  235. })();
  236. //#endif