diff --git a/.gitignore b/.gitignore
index 9b20a7778..b779eac0b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,4 +2,4 @@
local.mk
build/
tags
-
+.DS_Store
diff --git a/README.md b/README.md
index 3b8d86bb1..34b1a3f5e 100644
--- a/README.md
+++ b/README.md
@@ -61,13 +61,13 @@ You can also view all the test pdf files on the right side serving
+ http://localhost:8888/test/pdfs/?frame
-### Building pdf.js
+### Building pdf.js.
-In order to bundle all `src/` files into a final `pdf.js`, issue:
+In order to bundle all `src/` files into a final `pdf.js` and build the generic viewer, issue:
- $ node make bundle
+ $ node make generic
-This will generate the file `build/pdf.js` that can be included in your final project. (WARNING: That's a large file! Consider minifying it).
+This will generate the file `build/generic/build/pdf.js` that can be included in your final project. The pdf.js file is large and should be minified for production. Also, if you would like to support more browsers than firefox you'll also need to include `compatibility.js` from `build/generic/web/`.
# Learning
diff --git a/extensions/firefox/components/PdfStreamConverter.js b/extensions/firefox/components/PdfStreamConverter.js
index 2872da3fc..bac546c87 100644
--- a/extensions/firefox/components/PdfStreamConverter.js
+++ b/extensions/firefox/components/PdfStreamConverter.js
@@ -281,9 +281,26 @@ ChromeActions.prototype = {
var strings = getLocalizedStrings('chrome.properties');
var message = getLocalizedString(strings, 'unsupported_feature');
- var win = Services.wm.getMostRecentWindow('navigator:browser');
- var browser = win.gBrowser.getBrowserForDocument(domWindow.top.document);
- var notificationBox = win.gBrowser.getNotificationBox(browser);
+ var notificationBox = null;
+ // Multiple browser windows can be opened, finding one for notification box
+ var windowsEnum = Services.wm
+ .getZOrderDOMWindowEnumerator('navigator:browser', true);
+ while (windowsEnum.hasMoreElements()) {
+ var win = windowsEnum.getNext();
+ if (win.closed)
+ continue;
+ var browser = win.gBrowser.getBrowserForDocument(domWindow.top.document);
+ if (browser) {
+ // right window/browser is found, getting the notification box
+ notificationBox = win.gBrowser.getNotificationBox(browser);
+ break;
+ }
+ }
+ if (!notificationBox) {
+ log('Unable to get a notification box for the fallback message');
+ return;
+ }
+
// Flag so we don't call the response callback twice, since if the user
// clicks open with different viewer both the button callback and
// eventCallback will be called.
diff --git a/extensions/firefox/install.rdf b/extensions/firefox/install.rdf
index fdb78b175..eea7d45d6 100644
--- a/extensions/firefox/install.rdf
+++ b/extensions/firefox/install.rdf
@@ -13,7 +13,7 @@
{ec8030f7-c20a-464f-9b0e-13a3a9e97384}
- 6.0
+ 10.0
15.0a1
@@ -22,7 +22,7 @@
{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}
- 2.1.*
+ 2.7
2.12a1
diff --git a/external/builder/builder.js b/external/builder/builder.js
new file mode 100644
index 000000000..6eb0cd6ae
--- /dev/null
+++ b/external/builder/builder.js
@@ -0,0 +1,142 @@
+require('../shelljs/make');
+var fs = require('fs'),
+ path = require('path'),
+ vm = require('vm');
+
+/**
+ * A simple preprocessor that is based on the firefox preprocessor
+ * see (https://developer.mozilla.org/en/Build/Text_Preprocessor). The main
+ * difference is that this supports a subset of the commands and it supports
+ * preproccesor commands in html style comments.
+ * Currently Supported commands:
+ * - if
+ * - else
+ * - endif
+ * - include
+ * - expand
+ */
+function preprocess(inFilename, outFilename, defines) {
+ // TODO make this really read line by line.
+ var lines = fs.readFileSync(inFilename).toString().split('\n');
+ var totalLines = lines.length;
+ var out = '';
+ var i = 0;
+ function readLine() {
+ if (i < totalLines) {
+ return lines[i++];
+ }
+ return null;
+ }
+ var writeLine = typeof outFilename === 'function' ? outFilename : function(line) {
+ out += line + '\n';
+ }
+ function include(file) {
+ var realPath = fs.realpathSync(inFilename);
+ var dir = path.dirname(realPath);
+ preprocess(path.join(dir, file), writeLine, defines);
+ }
+ function expand(line) {
+ line = line.replace(/__[\w]+__/g, function(variable) {
+ variable = variable.substring(2, variable.length - 2);
+ if (variable in defines) {
+ return defines[variable];
+ }
+ return '';
+ });
+ writeLine(line);
+ }
+
+ var s, state = 0, stack = [];
+ var control = /^(?:\/\/|)?$)?/;
+ var lineNumber = 0;
+ while ((s = readLine()) !== null) {
+ ++lineNumber;
+ var m = control.exec(s);
+ if (m) {
+ switch (m[1]) {
+ case 'if':
+ stack.push(state);
+ try {
+ state = vm.runInNewContext(m[2], defines) ? 3 : 1;
+ } catch (e) {
+ console.error('Could not evalute line \'' + m[2] + '\' at ' +
+ fs.realpathSync(inFilename) + ':' + lineNumber);
+ throw e;
+ }
+ break;
+ case 'else':
+ state = state === 1 ? 3 : 2;
+ break;
+ case 'endif':
+ state = stack.pop();
+ break;
+ case 'expand':
+ if (state === 0 || state === 3)
+ expand(m[2]);
+ break;
+ case 'include':
+ if (state === 0 || state === 3)
+ include(m[2]);
+ break;
+ }
+ } else {
+ if (state === 0) {
+ writeLine(s);
+ } else if(state === 3) {
+ writeLine(s.replace(/^\/\/|^/g, " "));
+ }
+ }
+ }
+ if (state !== 0 || stack.length !== 0)
+ throw new Error('Missing endif in preprocessor.');
+ if (typeof outFilename !== 'function')
+ fs.writeFileSync(outFilename, out);
+}
+exports.preprocess = preprocess;
+
+/**
+ * Simplifies common build steps.
+ * @param setup
+ * .defines defines for preprocessors
+ * .copy array of arrays of source and destination pairs of files to copy
+ * .preprocess array of arrays of source and destination pairs of files
+ * run through preprocessor
+ */
+function build(setup) {
+ var defines = setup.defines;
+
+ setup.copy.forEach(function(option) {
+ var source = option[0];
+ var destination = option[1];
+ cp('-R', source, destination);
+ });
+
+ setup.preprocess.forEach(function(option) {
+ var sources = option[0];
+ var destination = option[1];
+
+ sources = ls('-R', sources);
+ sources.forEach(function(source) {
+ // ??? Warn if the source is wildcard and dest is file?
+ var destWithFolder = destination;
+ if (test('-d', destination))
+ destWithFolder += '/' + path.basename(source);
+ preprocess(source, destWithFolder, defines);
+ });
+ });
+}
+exports.build = build;
+
+/**
+ * Merge two defines arrays. Values in the second param will override values in
+ * the first.
+ */
+function merge(defaults, defines) {
+ var ret = {};
+ for (var key in defaults)
+ ret[key] = defaults[key];
+ for (key in defines)
+ ret[key] = defines[key];
+ return ret;
+}
+exports.merge = merge;
diff --git a/l10n/es/viewer.properties b/l10n/es/viewer.properties
index 8e7080d03..8485cbf17 100644
--- a/l10n/es/viewer.properties
+++ b/l10n/es/viewer.properties
@@ -18,11 +18,13 @@ zoom_in_label=Ampliar
zoom.title=Ampliación
print.title=Imprimir
print_label=Imprimir
+fullscreen.title=Pantalla completa
+fullscreen_label=Pantalla completa
open_file.title=Abrir archivo
open_file_label=Abrir
download.title=Descargar
download_label=Descargar
-bookmark.title=Vista actual (copiar o abrir en una ventana nueva)
+bookmark.title=Vista actual (copie o abra en una ventana nueva)
bookmark_label=Vista actual
# Tooltips and alt text for side panel toolbar buttons
@@ -69,7 +71,7 @@ error_stack=Pila: {{stack}}
error_file=Archivo: {{file}}
# LOCALIZATION NOTE (error_line): "{{line}}" will be replaced with a line number
error_line=Línea: {{line}}
-rendering_error=Ocurrió un error al renderizar la página.
+rendering_error=Ocurrió un error mientras se renderizaba la página.
# Predefined zoom values
page_scale_width=Anchura de página
@@ -79,7 +81,7 @@ page_scale_actual=Tamaño real
# Loading indicator messages
loading_error_indicator=Error
-loading_error=Ocurrió un error al cargar el PDF.
+loading_error=Ocurrió un error mientras se cargaba el PDF.
# LOCALIZATION NOTE (text_annotation_type): This is used as a tooltip.
# "{{type}}" will be replaced with an annotation type from a list defined in
@@ -87,3 +89,5 @@ loading_error=Ocurrió un error al cargar el PDF.
# Some common types are e.g.: "Check", "Text", "Comment", "Note"
text_annotation_type=[Anotación {{type}}]
request_password=El PDF está protegido con una contraseña:
+
+printing_not_supported=Aviso: La impresión no es compatible totalmente con este navegador.
diff --git a/l10n/ja/viewer.properties b/l10n/ja/viewer.properties
index b7981ecf0..c8bfde461 100644
--- a/l10n/ja/viewer.properties
+++ b/l10n/ja/viewer.properties
@@ -18,6 +18,8 @@ zoom_in_label=拡大
zoom.title=ズーム
print.title=印刷
print_label=印刷
+fullscreen.title=全画面表示
+fullscreen_label=全画面表示
open_file.title=ファイルを開く
open_file_label=開く
download.title=ダウンロード
diff --git a/make.js b/make.js
index 727e740ca..1d2e5cfcf 100755
--- a/make.js
+++ b/make.js
@@ -1,5 +1,6 @@
#!/usr/bin/env node
require('./external/shelljs/make');
+var builder = require('./external/builder/builder.js');
var ROOT_DIR = __dirname + '/', // absolute path to project's root
BUILD_DIR = 'build/',
@@ -8,6 +9,7 @@ var ROOT_DIR = __dirname + '/', // absolute path to project's root
EXTENSION_SRC_DIR = 'extensions/',
LOCALE_SRC_DIR = 'l10n/',
GH_PAGES_DIR = BUILD_DIR + 'gh-pages/',
+ GENERIC_DIR = BUILD_DIR + 'generic/',
REPO = 'git@github.com:mozilla/pdf.js.git',
PYTHON_BIN = 'python2.7',
MOZCENTRAL_PREF_PREFIX = 'pdfjs',
@@ -15,6 +17,16 @@ var ROOT_DIR = __dirname + '/', // absolute path to project's root
MOZCENTRAL_STREAM_CONVERTER_ID = 'd0c5195d-e798-49d4-b1d3-9324328b2291',
FIREFOX_STREAM_CONVERTER_ID = '6457a96b-2d68-439a-bcfa-44465fbcdbb1';
+var DEFINES = {
+ PRODUCTION: true,
+ // The main build targets:
+ GENERIC: false,
+ FIREFOX: false,
+ MOZCENTRAL: false,
+ B2G: false,
+ CHROME: false
+};
+
//
// make all
//
@@ -31,14 +43,59 @@ target.all = function() {
// Production stuff
//
+// Files that need to be included in every build.
+var COMMON_WEB_FILES =
+ ['web/viewer.css',
+ 'web/images',
+ 'web/debugger.js'],
+ COMMON_WEB_FILES_PREPROCESS =
+ ['web/viewer.js',
+ 'web/viewer.html'];
+
+//
+// make generic
+// Builds the generic production viewer that should be compatible with most
+// modern HTML5 browsers.
+//
+target.generic = function() {
+ target.bundle();
+ target.locale();
+
+ cd(ROOT_DIR);
+ echo();
+ echo('### Creating generic viewer');
+
+ rm('-rf', GENERIC_DIR);
+ mkdir('-p', GENERIC_DIR);
+ mkdir('-p', GENERIC_DIR + BUILD_DIR);
+ mkdir('-p', GENERIC_DIR + '/web');
+
+ var defines = builder.merge(DEFINES, {GENERIC: true});
+
+ var setup = {
+ defines: defines,
+ copy: [
+ [COMMON_WEB_FILES, GENERIC_DIR + '/web'],
+ ['external/webL10n/l10n.js', GENERIC_DIR + '/web'],
+ ['web/compatibility.js', GENERIC_DIR + '/web'],
+ ['web/compressed.tracemonkey-pldi-09.pdf', GENERIC_DIR + '/web'],
+ ['web/locale.properties', GENERIC_DIR + '/web']
+ ],
+ preprocess: [
+ [BUILD_TARGET, GENERIC_DIR + BUILD_TARGET],
+ [COMMON_WEB_FILES_PREPROCESS, GENERIC_DIR + '/web']
+ ]
+ };
+ builder.build(setup);
+};
+
//
// make web
// Generates the website for the project, by checking out the gh-pages branch underneath
// the build directory, and then moving the various viewer files into place.
//
target.web = function() {
- target.production();
- target.locale();
+ target.generic();
target.extension();
target.pagesrepo();
@@ -46,25 +103,18 @@ target.web = function() {
echo();
echo('### Creating web site');
- var GH_PAGES_SRC_FILES = [
- 'web/*',
- 'external/webL10n/l10n.js'
- ];
-
- cp(BUILD_TARGET, GH_PAGES_DIR + BUILD_TARGET);
- cp('-R', GH_PAGES_SRC_FILES, GH_PAGES_DIR + '/web');
+ cp('-R', GENERIC_DIR + '/*', GH_PAGES_DIR);
cp(FIREFOX_BUILD_DIR + '/*.xpi', FIREFOX_BUILD_DIR + '/*.rdf',
- GH_PAGES_DIR + EXTENSION_SRC_DIR + 'firefox/');
- cp(GH_PAGES_DIR + '/web/index.html.template', GH_PAGES_DIR + '/index.html');
- mv('-f', GH_PAGES_DIR + '/web/viewer-production.html',
- GH_PAGES_DIR + '/web/viewer.html');
+ GH_PAGES_DIR + EXTENSION_SRC_DIR + 'firefox/');
+ cp('web/index.html.template', GH_PAGES_DIR + '/index.html');
+
cd(GH_PAGES_DIR);
exec('git add -A');
echo();
echo("Website built in " + GH_PAGES_DIR);
echo("Don't forget to cd into " + GH_PAGES_DIR +
- " and issue 'git commit' to push changes.");
+ " and issue 'git commit' to push changes.");
};
//
@@ -124,20 +174,10 @@ target.locale = function() {
chromeManifestContent.to(CHROME_MANIFEST_OUTPUT);
};
-//
-// make production
-// Creates production output (pdf.js, and corresponding changes to web/ files)
-//
-target.production = function() {
- target.bundle();
- target.viewer();
-};
-
//
// make bundle
// Bundles all source files into one wrapper 'pdf.js' file, in the given order.
//
-
target.bundle = function() {
cd(ROOT_DIR);
echo();
@@ -178,29 +218,12 @@ target.bundle = function() {
bundleVersion = exec('git log --format="%h" -n 1',
{silent: true}).output.replace('\n', '');
- sed(/.*PDFJSSCRIPT_INCLUDE_ALL.*\n/, bundle, 'pdf.js')
- .to(ROOT_DIR + BUILD_TARGET);
- sed('-i', 'PDFJSSCRIPT_BUNDLE_VER', bundleVersion, ROOT_DIR + BUILD_TARGET);
+ // This just preprocesses the empty pdf.js file, we don't actually want to
+ // preprocess everything yet since other build targets use this file.
+ builder.preprocess('pdf.js', ROOT_DIR + BUILD_TARGET,
+ {BUNDLE: bundle, BUNDLE_VERSION: bundleVersion});
};
-//
-// make viewer
-// Changes development
+
+
diff --git a/web/viewer-snippet-firefox-extension.html b/web/viewer-snippet-firefox-extension.html
index 57d7875eb..5b8cc9eaf 100644
--- a/web/viewer-snippet-firefox-extension.html
+++ b/web/viewer-snippet-firefox-extension.html
@@ -1,14 +1,11 @@
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/web/viewer.js b/web/viewer.js
index 13b260a64..ad327924f 100644
--- a/web/viewer.js
+++ b/web/viewer.js
@@ -90,66 +90,9 @@ var ProgressBar = (function ProgressBarClosure() {
return ProgressBar;
})();
-var FirefoxCom = (function FirefoxComClosure() {
- return {
- /**
- * Creates an event that the extension is listening for and will
- * synchronously respond to.
- * NOTE: It is reccomended to use request() instead since one day we may not
- * be able to synchronously reply.
- * @param {String} action The action to trigger.
- * @param {String} data Optional data to send.
- * @return {*} The response.
- */
- requestSync: function(action, data) {
- var request = document.createTextNode('');
- request.setUserData('action', action, null);
- request.setUserData('data', data, null);
- request.setUserData('sync', true, null);
- document.documentElement.appendChild(request);
-
- var sender = document.createEvent('Events');
- sender.initEvent('pdf.js.message', true, false);
- request.dispatchEvent(sender);
- var response = request.getUserData('response');
- document.documentElement.removeChild(request);
- return response;
- },
- /**
- * Creates an event that the extension is listening for and will
- * asynchronously respond by calling the callback.
- * @param {String} action The action to trigger.
- * @param {String} data Optional data to send.
- * @param {Function} callback Optional response callback that will be called
- * with one data argument.
- */
- request: function(action, data, callback) {
- var request = document.createTextNode('');
- request.setUserData('action', action, null);
- request.setUserData('data', data, null);
- request.setUserData('sync', false, null);
- if (callback) {
- request.setUserData('callback', callback, null);
-
- document.addEventListener('pdf.js.response', function listener(event) {
- var node = event.target,
- callback = node.getUserData('callback'),
- response = node.getUserData('response');
-
- document.documentElement.removeChild(node);
-
- document.removeEventListener('pdf.js.response', listener, false);
- return callback(response);
- }, false);
- }
- document.documentElement.appendChild(request);
-
- var sender = document.createEvent('HTMLEvents');
- sender.initEvent('pdf.js.message', true, false);
- return request.dispatchEvent(sender);
- }
- };
-})();
+//#if FIREFOX || MOZCENTRAL
+//#include firefoxcom.js
+//#endif
// Settings Manager - This is a utility for saving settings
// First we see if localStorage is available
@@ -167,17 +110,17 @@ var Settings = (function SettingsClosure() {
}
})();
- var isFirefoxExtension = PDFJS.isFirefoxExtension;
-
function Settings(fingerprint) {
var database = null;
var index;
- if (isFirefoxExtension)
- database = FirefoxCom.requestSync('getDatabase', null) || '{}';
- else if (isLocalStorageEnabled)
+//#if !(FIREFOX || MOZCENTRAL)
+ if (isLocalStorageEnabled)
database = localStorage.getItem('database') || '{}';
else
- return false;
+ return;
+//#else
+// database = FirefoxCom.requestSync('getDatabase', null) || '{}';
+//#endif
database = JSON.parse(database);
if (!('files' in database))
@@ -205,10 +148,12 @@ var Settings = (function SettingsClosure() {
var file = this.file;
file[name] = val;
var database = JSON.stringify(this.database);
- if (isFirefoxExtension)
- FirefoxCom.requestSync('setDatabase', database);
- else if (isLocalStorageEnabled)
+//#if !(FIREFOX || MOZCENTRAL)
+ if (isLocalStorageEnabled)
localStorage.setItem('database', database);
+//#else
+// FirefoxCom.requestSync('setDatabase', database);
+//#endif
},
get: function settingsGet(name, defaultValue) {
@@ -351,9 +296,10 @@ var PDFView = {
set page(val) {
var pages = this.pages;
var input = document.getElementById('pageNumber');
+ var event = document.createEvent('UIEvents');
+ event.initUIEvent('pagechange', false, false, window, 0);
+
if (!(0 < val && val <= pages.length)) {
- var event = document.createEvent('UIEvents');
- event.initUIEvent('pagechange', false, false, window, 0);
event.pageNumber = this.page;
window.dispatchEvent(event);
return;
@@ -361,8 +307,6 @@ var PDFView = {
pages[val - 1].updateStats();
currentPageNumber = val;
- var event = document.createEvent('UIEvents');
- event.initUIEvent('pagechange', false, false, window, 0);
event.pageNumber = val;
window.dispatchEvent(event);
@@ -486,52 +430,54 @@ var PDFView = {
}
var url = this.url.split('#')[0];
- if (PDFJS.isFirefoxExtension) {
- // Document isn't ready just try to download with the url.
- if (!this.pdfDocument) {
- noData();
- return;
- }
- this.pdfDocument.getData().then(
- function getDataSuccess(data) {
- var bb = new MozBlobBuilder();
- bb.append(data.buffer);
- var blobUrl = window.URL.createObjectURL(
- bb.getBlob('application/pdf'));
-
- FirefoxCom.request('download', { blobUrl: blobUrl, originalUrl: url },
- function response(err) {
- if (err) {
- // This error won't really be helpful because it's likely the
- // fallback won't work either (or is already open).
- PDFView.error('PDF failed to download.');
- }
- window.URL.revokeObjectURL(blobUrl);
- }
- );
- },
- noData // Error ocurred try downloading with just the url.
- );
- } else {
- url += '#pdfjs.action=download', '_parent';
- window.open(url, '_parent');
- }
+//#if !(FIREFOX || MOZCENTRAL)
+ url += '#pdfjs.action=download';
+ window.open(url, '_parent');
+//#else
+// // Document isn't ready just try to download with the url.
+// if (!this.pdfDocument) {
+// noData();
+// return;
+// }
+// this.pdfDocument.getData().then(
+// function getDataSuccess(data) {
+// var bb = new MozBlobBuilder();
+// bb.append(data.buffer);
+// var blobUrl = window.URL.createObjectURL(
+// bb.getBlob('application/pdf'));
+//
+// FirefoxCom.request('download', { blobUrl: blobUrl, originalUrl: url },
+// function response(err) {
+// if (err) {
+// // This error won't really be helpful because it's likely the
+// // fallback won't work either (or is already open).
+// PDFView.error('PDF failed to download.');
+// }
+// window.URL.revokeObjectURL(blobUrl);
+// }
+// );
+// },
+// noData // Error occurred try downloading with just the url.
+// );
+//#endif
},
fallback: function pdfViewFallback() {
- if (!PDFJS.isFirefoxExtension)
- return;
- // Only trigger the fallback once so we don't spam the user with messages
- // for one PDF.
- if (this.fellback)
- return;
- this.fellback = true;
- var url = this.url.split('#')[0];
- FirefoxCom.request('fallback', url, function response(download) {
- if (!download)
- return;
- PDFView.download();
- });
+//#if !(FIREFOX || MOZCENTRAL)
+// return;
+//#else
+// // Only trigger the fallback once so we don't spam the user with messages
+// // for one PDF.
+// if (this.fellback)
+// return;
+// this.fellback = true;
+// var url = this.url.split('#')[0];
+// FirefoxCom.request('fallback', url, function response(download) {
+// if (!download)
+// return;
+// PDFView.download();
+// });
+//#endif
},
navigateTo: function pdfViewNavigateTo(dest) {
@@ -583,9 +529,11 @@ var PDFView = {
* @param {String} anchor The anchor hash include the #.
*/
getAnchorUrl: function getAnchorUrl(anchor) {
- if (PDFJS.isFirefoxExtension)
- return this.url.split('#')[0] + anchor;
+//#if !(FIREFOX || MOZCENTRAL)
return anchor;
+//#else
+// return this.url.split('#')[0] + anchor;
+//#endif
},
/**
@@ -619,11 +567,7 @@ var PDFView = {
}
}
}
- if (PDFJS.isFirefoxExtension) {
- console.error(message + '\n' + moreInfoText);
- this.fallback();
- return;
- }
+//#if !(FIREFOX || MOZCENTRAL)
var errorWrapper = document.getElementById('errorWrapper');
errorWrapper.removeAttribute('hidden');
@@ -653,6 +597,10 @@ var PDFView = {
errorMoreInfo.value = moreInfoText;
errorMoreInfo.rows = moreInfoText.split('\n').length - 1;
+//#else
+// console.error(message + '\n' + moreInfoText);
+// this.fallback();
+//#endif
},
progress: function pdfViewProgress(level) {
@@ -811,7 +759,7 @@ var PDFView = {
}
},
- getHighestPriority: function pdfViewGetHighestPriority(visibleViews, views,
+ getHighestPriority: function pdfViewGetHighestPriority(visible, views,
scrolledDown) {
// The state has changed figure out which page has the highest priority to
// render next (if any).
@@ -819,9 +767,10 @@ var PDFView = {
// 1 visible pages
// 2 if last scrolled down page after the visible pages
// 2 if last scrolled up page before the visible pages
+ var visibleViews = visible.views;
+
var numVisible = visibleViews.length;
if (numVisible === 0) {
- info('No visible views.');
return false;
}
for (var i = 0; i < numVisible; ++i) {
@@ -832,13 +781,12 @@ var PDFView = {
// All the visible views have rendered, try to render next/previous pages.
if (scrolledDown) {
- var lastVisible = visibleViews[visibleViews.length - 1];
- var nextPageIndex = lastVisible.id;
+ var nextPageIndex = visible.last.id;
// ID's start at 1 so no need to add 1.
if (views[nextPageIndex] && !this.isViewFinished(views[nextPageIndex]))
return views[nextPageIndex];
} else {
- var previousPageIndex = visibleViews[0].id - 2;
+ var previousPageIndex = visible.first.id - 2;
if (views[previousPageIndex] &&
!this.isViewFinished(views[previousPageIndex]))
return views[previousPageIndex];
@@ -876,14 +824,14 @@ var PDFView = {
search: function pdfViewStartSearch() {
// Limit this function to run every ms.
var SEARCH_TIMEOUT = 250;
- var lastSeach = this.lastSearch;
+ var lastSearch = this.lastSearch;
var now = Date.now();
- if (lastSeach && (now - lastSeach) < SEARCH_TIMEOUT) {
+ if (lastSearch && (now - lastSearch) < SEARCH_TIMEOUT) {
if (!this.searchTimer) {
this.searchTimer = setTimeout(function resumeSearch() {
PDFView.search();
},
- SEARCH_TIMEOUT - (now - lastSeach)
+ SEARCH_TIMEOUT - (now - lastSearch)
);
}
return;
@@ -952,7 +900,6 @@ var PDFView = {
}
if ('page' in params) {
var pageNumber = (params.page | 0) || 1;
- this.page = pageNumber;
if ('zoom' in params) {
var zoomArgs = params.zoom.split(','); // scale,left,top
// building destination array
@@ -968,9 +915,9 @@ var PDFView = {
(zoomArgs[2] | 0), zoomArg];
var currentPage = this.pages[pageNumber - 1];
currentPage.scrollIntoView(dest);
- } else
- this.page = params.page; // simple page
- return;
+ } else {
+ this.page = pageNumber; // simple page
+ }
}
} else if (/^\d+$/.test(hash)) // page number
this.page = hash;
@@ -1041,13 +988,13 @@ var PDFView = {
extractPageText(pageIndex + 1);
}
);
- };
+ }
extractPageText(0);
},
getVisiblePages: function pdfViewGetVisiblePages() {
return this.getVisibleElements(this.container,
- this.pages);
+ this.pages, true);
},
getVisibleThumbs: function pdfViewGetVisibleThumbs() {
@@ -1056,11 +1003,12 @@ var PDFView = {
},
// Generic helper to find out what elements are visible within a scroll pane.
- getVisibleElements: function pdfViewGetVisibleElements(scrollEl, views) {
+ getVisibleElements: function pdfViewGetVisibleElements(
+ scrollEl, views, sortByVisibility) {
var currentHeight = 0, view;
var top = scrollEl.scrollTop;
- for (var i = 1; i <= views.length; ++i) {
+ for (var i = 1, ii = views.length; i <= ii; ++i) {
view = views[i - 1];
currentHeight = view.el.offsetTop;
if (currentHeight + view.el.clientHeight > top)
@@ -1078,19 +1026,38 @@ var PDFView = {
view: currentPage
});
- return visible;
+ return { first: currentPage, last: currentPage, views: visible};
}
var bottom = top + scrollEl.clientHeight;
- for (; i <= views.length && currentHeight < bottom; ++i) {
+ var nextHeight, hidden, percent, viewHeight;
+ for (; i <= ii && currentHeight < bottom; ++i) {
view = views[i - 1];
+ viewHeight = view.el.clientHeight;
currentHeight = view.el.offsetTop;
+ nextHeight = currentHeight + viewHeight;
+ hidden = Math.max(0, top - currentHeight) +
+ Math.max(0, nextHeight - bottom);
+ percent = Math.floor((viewHeight - hidden) * 100.0 / viewHeight);
visible.push({ id: view.id, y: currentHeight,
- view: view });
- currentHeight += view.el.clientHeight;
+ view: view, percent: percent });
+ currentHeight = nextHeight;
}
- return visible;
+ var first = visible[0];
+ var last = visible[visible.length - 1];
+
+ if (sortByVisibility) {
+ visible.sort(function(a, b) {
+ var pc = a.percent - b.percent;
+ if (Math.abs(pc) > 0.001)
+ return -pc;
+
+ return a.id - b.id; // ensure stability
+ });
+ }
+
+ return {first: first, last: last, views: visible};
},
// Helper function to parse query string (e.g. ?param1=value&parm2=...).
@@ -1727,13 +1694,13 @@ var CustomStyle = (function CustomStyleClosure() {
//if all fails then set to undefined
return (_cache[propName] = 'undefined');
- }
+ };
CustomStyle.setProp = function set(propName, element, str) {
var prop = this.getProp(propName);
if (prop != 'undefined')
element.style[prop] = str;
- }
+ };
return CustomStyle;
})();
@@ -1763,6 +1730,7 @@ var TextLayerBuilder = function textLayerBuilder(textLayerDiv) {
if (textDivs.length === 0) {
clearInterval(renderTimer);
renderingDone = true;
+ self.textLayerDiv = textLayerDiv = canvas = ctx = null;
return;
}
var textDiv = textDivs.shift();
@@ -1802,7 +1770,7 @@ var TextLayerBuilder = function textLayerBuilder(textLayerDiv) {
// Resume rendering
renderTimer = setInterval(renderTextLayer, renderInterval);
}, resumeInterval);
- }; // textLayerOnScroll
+ } // textLayerOnScroll
window.addEventListener('scroll', textLayerOnScroll, false);
}; // endLayout
@@ -1830,15 +1798,21 @@ document.addEventListener('DOMContentLoaded', function webViewerLoad(evt) {
PDFView.initialize();
var params = PDFView.parseQueryString(document.location.search.substring(1));
- var file = PDFJS.isFirefoxExtension ?
- window.location.toString() : params.file || kDefaultURL;
+//#if !(FIREFOX || MOZCENTRAL)
+ var file = params.file || kDefaultURL;
+//#else
+//var file = window.location.toString()
+//#endif
- if (PDFJS.isFirefoxExtension || !window.File || !window.FileReader ||
- !window.FileList || !window.Blob) {
+//#if !(FIREFOX || MOZCENTRAL)
+ if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
document.getElementById('openFile').setAttribute('hidden', 'true');
} else {
document.getElementById('fileInput').value = null;
}
+//#else
+//document.getElementById('openFile').setAttribute('hidden', 'true');
+//#endif
// Special debugging flags in the hash section of the URL.
var hash = document.location.hash.substring(1);
@@ -1847,18 +1821,21 @@ document.addEventListener('DOMContentLoaded', function webViewerLoad(evt) {
if ('disableWorker' in hashParams)
PDFJS.disableWorker = (hashParams['disableWorker'] === 'true');
- if (!PDFJS.isFirefoxExtension) {
- var locale = navigator.language;
- if ('locale' in hashParams)
- locale = hashParams['locale'];
- mozL10n.language.code = locale;
- }
+//#if !(FIREFOX || MOZCENTRAL)
+ var locale = navigator.language;
+ if ('locale' in hashParams)
+ locale = hashParams['locale'];
+ mozL10n.language.code = locale;
+//#endif
if ('disableTextLayer' in hashParams)
PDFJS.disableTextLayer = (hashParams['disableTextLayer'] === 'true');
- if ('pdfBug' in hashParams &&
- (!PDFJS.isFirefoxExtension || FirefoxCom.requestSync('pdfBugEnabled'))) {
+//#if !(FIREFOX || MOZCENTRAL)
+ if ('pdfBug' in hashParams) {
+//#else
+//if ('pdfBug' in hashParams && FirefoxCom.requestSync('pdfBugEnabled')) {
+//#endif
PDFJS.pdfBug = true;
var pdfBug = hashParams['pdfBug'];
var enabled = pdfBug.split(',');
@@ -1866,10 +1843,12 @@ document.addEventListener('DOMContentLoaded', function webViewerLoad(evt) {
PDFBug.init();
}
- if (!PDFJS.isFirefoxExtension ||
- (PDFJS.isFirefoxExtension && FirefoxCom.requestSync('searchEnabled'))) {
- document.querySelector('#viewSearch').classList.remove('hidden');
- }
+//#if !(FIREFOX || MOZCENTRAL)
+//#else
+//if (FirefoxCom.requestSync('searchEnabled')) {
+// document.querySelector('#viewSearch').classList.remove('hidden');
+//}
+//#endif
if (!PDFView.supportsPrinting) {
document.getElementById('print').classList.add('hidden');
@@ -1907,27 +1886,50 @@ document.addEventListener('DOMContentLoaded', function webViewerLoad(evt) {
PDFView.renderHighestPriority();
});
- if (PDFJS.isFirefoxExtension &&
- FirefoxCom.requestSync('getLoadingType') == 'passive') {
- PDFView.setTitleUsingUrl(file);
- PDFView.initPassiveLoading();
- } else
- PDFView.open(file, 0);
+//#if (FIREFOX || MOZCENTRAL)
+//if (FirefoxCom.requestSync('getLoadingType') == 'passive') {
+// PDFView.setTitleUsingUrl(file);
+// PDFView.initPassiveLoading();
+//}
+//#endif
+
+//#if !B2G
+ PDFView.open(file, 0);
+//#endif
}, true);
function updateViewarea() {
+
if (!PDFView.initialized)
return;
- var visiblePages = PDFView.getVisiblePages();
+ var visible = PDFView.getVisiblePages();
+ var visiblePages = visible.views;
PDFView.renderHighestPriority();
var currentId = PDFView.page;
- var firstPage = visiblePages[0];
+ var firstPage = visible.first;
+
+ for (var i = 0, ii = visiblePages.length, stillFullyVisible = false;
+ i < ii; ++i) {
+ var page = visiblePages[i];
+
+ if (page.percent < 100)
+ break;
+
+ if (page.id === PDFView.page) {
+ stillFullyVisible = true;
+ break;
+ }
+ }
+
+ if (!stillFullyVisible) {
+ currentId = visiblePages[0].id;
+ }
if (!PDFView.isFullscreen) {
updateViewarea.inProgress = true; // used in "set page"
- PDFView.page = firstPage.id;
+ PDFView.page = currentId;
updateViewarea.inProgress = false;
}
@@ -1975,20 +1977,13 @@ window.addEventListener('change', function webViewerChange(evt) {
// Read the local file into a Uint8Array.
var fileReader = new FileReader();
fileReader.onload = function webViewerChangeFileReaderOnload(evt) {
- var data = evt.target.result;
- var buffer = new ArrayBuffer(data.length);
+ var buffer = evt.target.result;
var uint8Array = new Uint8Array(buffer);
-
- for (var i = 0; i < data.length; i++)
- uint8Array[i] = data.charCodeAt(i);
-
PDFView.open(uint8Array, 0);
};
- // Read as a binary string since "readAsArrayBuffer" is not yet
- // implemented in Firefox.
var file = files[0];
- fileReader.readAsBinaryString(file);
+ fileReader.readAsArrayBuffer(file);
PDFView.setTitleUsingUrl(file.name);
// URL does not reflect proper document location - hiding some icons.
@@ -2046,13 +2041,13 @@ window.addEventListener('pagechange', function pagechange(evt) {
var thumbnail = document.getElementById('thumbnailContainer' + page);
thumbnail.classList.add('selected');
var visibleThumbs = PDFView.getVisibleThumbs();
- var numVisibleThumbs = visibleThumbs.length;
+ var numVisibleThumbs = visibleThumbs.views.length;
// If the thumbnail isn't currently visible scroll it into view.
if (numVisibleThumbs > 0) {
- var first = visibleThumbs[0].id;
+ var first = visibleThumbs.first.id;
// Account for only one thumbnail being visible.
var last = numVisibleThumbs > 1 ?
- visibleThumbs[numVisibleThumbs - 1].id : first;
+ visibleThumbs.last.id : first;
if (page <= first || page >= last)
thumbnail.scrollIntoView();
}
@@ -2171,3 +2166,21 @@ window.addEventListener('afterprint', function afterPrint(evt) {
window.addEventListener('mozfullscreenchange', fullscreenChange, false);
window.addEventListener('webkitfullscreenchange', fullscreenChange, false);
})();
+
+//#if B2G
+//window.navigator.mozSetMessageHandler('activity', function(activity) {
+// var url = activity.source.data.url;
+// // Temporarily get the data here since the cross domain xhr is broken in
+// // the worker currently, see bug 761227.
+// var params = {
+// url: url,
+// error: function(e) {
+// PDFView.error(mozL10n.get('loading_error', null,
+// 'An error occurred while loading the PDF.'), e);
+// }
+// };
+// PDFJS.getPdf(params, function successCallback(data) {
+// PDFView.open(data, 0);
+// });
+//});
+//#endif