Merge remote-tracking branch 'mozilla/master' into textsearch-1

Conflicts:
	src/core.js
	src/fonts.js
This commit is contained in:
notmasteryet 2012-01-22 13:56:56 -06:00
commit 1ac24dbc01
53 changed files with 6051 additions and 1127 deletions

4
.gitignore vendored
View File

@ -1,7 +1,5 @@
*~
pdf.pdf
intelisa.pdf
openweb_tm-PRINT.pdf
local.mk
build/
tags

View File

@ -3,9 +3,12 @@ BUILD_DIR := build
BUILD_TARGET := $(BUILD_DIR)/pdf.js
DEFAULT_BROWSERS := resources/browser_manifests/browser_manifest.json
DEFAULT_TESTS := test_manifest.json
DEFAULT_PYTHON := python2.7
EXTENSION_SRC := ./extensions/
EXTENSION_BASE_VERSION := 4bb289ec499013de66eb421737a4dbb4a9273eda
FIREFOX_EXTENSION_NAME := pdf.js.xpi
FIREFOX_AMO_EXTENSION_NAME := pdf.js.amo.xpi
CHROME_EXTENSION_NAME := pdf.js.crx
all: bundle
@ -34,6 +37,7 @@ PDF_JS_FILES = \
stream.js \
worker.js \
../external/jpgjs/jpg.js \
jpx.js \
$(NULL)
# make server
@ -41,8 +45,12 @@ PDF_JS_FILES = \
# This target starts a local web server at localhost:8888. This can be
# used for testing all browsers.
server:
@cd test; python test.py --port=8888;
@cd test; $(DEFAULT_PYTHON) test.py --port=8888;
# make test
#
# This target runs all the tests excluding the unit-test. This can be used for
# testing all browsers.
test: shell-test browser-test
#
@ -65,10 +73,17 @@ bundle: | $(BUILD_DIR)
cat $(PDF_JS_FILES) > all_files.tmp; \
sed '/PDFJSSCRIPT_INCLUDE_ALL/ r all_files.tmp' pdf.js > ../$(BUILD_TARGET); \
sed -i.bak "s/PDFJSSCRIPT_BUNDLE_VER/`git log --format="%h" -n 1`/" ../$(BUILD_TARGET); \
rm -f ../$(BUILD_TARGET).bak
rm -f ../$(BUILD_TARGET).bak; \
rm -f *.tmp; \
cd ..
# make unit-test
#
# This target runs in-browser unit tests with js-test-driver and jasmine unit
# test framework.
unit-test:
@cd test/unit/ ; make ;
# make browser-test
#
# This target runs in-browser tests using two primary arguments: a
@ -93,7 +108,7 @@ browser-test:
fi;
cd test; \
python test.py --reftest \
$(DEFAULT_PYTHON) test.py --reftest \
--browserManifestFile=$(PDF_BROWSERS) \
--manifestFile=$(PDF_TESTS)
@ -147,7 +162,10 @@ web: | production extension compiler pages-repo
@cp $(BUILD_TARGET) $(GH_PAGES)/$(BUILD_TARGET)
@cp -R web/* $(GH_PAGES)/web
@cp web/images/* $(GH_PAGES)/web/images
@cp $(EXTENSION_SRC)/firefox/*.xpi $(GH_PAGES)/$(EXTENSION_SRC)/firefox/
@cp $(FIREFOX_BUILD_DIR)/$(FIREFOX_EXTENSION_NAME) \
$(FIREFOX_BUILD_DIR)/$(FIREFOX_AMO_EXTENSION_NAME) \
$(FIREFOX_BUILD_DIR)/update.rdf \
$(GH_PAGES)/$(EXTENSION_SRC)/firefox/
@cp $(GH_PAGES)/web/index.html.template $(GH_PAGES)/index.html;
@mv -f $(GH_PAGES)/web/viewer-production.html $(GH_PAGES)/web/viewer.html;
@cd $(GH_PAGES); git add -A;
@ -190,8 +208,7 @@ pages-repo: | $(BUILD_DIR)
# This target produce a restartless firefox extension containing a
# copy of the pdf.js source.
CONTENT_DIR := content
FIREFOX_CONTENT_DIR := $(EXTENSION_SRC)/firefox/$(CONTENT_DIR)/
CHROME_CONTENT_DIR := $(EXTENSION_SRC)/chrome/$(CONTENT_DIR)/
BUILD_NUMBER := `git log --format=oneline $(EXTENSION_BASE_VERSION).. | wc -l | awk '{print $$1}'`
PDF_WEB_FILES = \
web/images \
web/compatibility.js \
@ -199,26 +216,66 @@ PDF_WEB_FILES = \
web/viewer.js \
web/viewer-production.html \
$(NULL)
FIREFOX_BUILD_DIR := $(BUILD_DIR)/firefox
FIREFOX_BUILD_CONTENT := $(FIREFOX_BUILD_DIR)/$(CONTENT_DIR)/
FIREFOX_CONTENT_DIR := $(EXTENSION_SRC)/firefox/$(CONTENT_DIR)/
FIREFOX_EXTENSION_FILES_TO_COPY = \
*.js \
*.rdf \
chrome.manifest \
components \
$(NULL)
FIREFOX_EXTENSION_FILES = \
content \
*.js \
install.rdf \
chrome.manifest \
components \
content \
$(NULL)
CHROME_BUILD_DIR := $(BUILD_DIR)/chrome
CHROME_CONTENT_DIR := $(EXTENSION_SRC)/chrome/$(CONTENT_DIR)/
CHROME_BUILD_CONTENT := $(CHROME_BUILD_DIR)/$(CONTENT_DIR)/
CHROME_EXTENSION_FILES = \
extensions/chrome/*.json \
extensions/chrome/*.html \
$(NULL)
extension: | production
# Clear out everything in the firefox extension build directory
@rm -Rf $(FIREFOX_BUILD_DIR)
@mkdir -p $(FIREFOX_BUILD_CONTENT)
@mkdir -p $(FIREFOX_BUILD_CONTENT)/$(BUILD_DIR)
@mkdir -p $(FIREFOX_BUILD_CONTENT)/web
@cd extensions/firefox; cp -r $(FIREFOX_EXTENSION_FILES_TO_COPY) ../../$(FIREFOX_BUILD_DIR)/
# Copy a standalone version of pdf.js inside the content directory
@rm -Rf $(FIREFOX_CONTENT_DIR)
@mkdir -p $(FIREFOX_CONTENT_DIR)/$(BUILD_DIR)
@mkdir -p $(FIREFOX_CONTENT_DIR)/web
@cp $(BUILD_TARGET) $(FIREFOX_CONTENT_DIR)/$(BUILD_DIR)
@cp -r $(PDF_WEB_FILES) $(FIREFOX_CONTENT_DIR)/web/
@mv -f $(FIREFOX_CONTENT_DIR)/web/viewer-production.html $(FIREFOX_CONTENT_DIR)/web/viewer.html
@cp $(BUILD_TARGET) $(FIREFOX_BUILD_CONTENT)/$(BUILD_DIR)/
@cp -r $(PDF_WEB_FILES) $(FIREFOX_BUILD_CONTENT)/web/
@mv -f $(FIREFOX_BUILD_CONTENT)/web/viewer-production.html $(FIREFOX_BUILD_CONTENT)/web/viewer.html
# Update the build version number
@sed -i.bak "s/PDFJSSCRIPT_BUILD/$(BUILD_NUMBER)/" $(FIREFOX_BUILD_DIR)/install.rdf
@sed -i.bak "s/PDFJSSCRIPT_BUILD/$(BUILD_NUMBER)/" $(FIREFOX_BUILD_DIR)/update.rdf
@rm -f $(FIREFOX_BUILD_DIR)/*.bak
# Create the xpi
@cd $(EXTENSION_SRC)/firefox; zip -r $(FIREFOX_EXTENSION_NAME) *
@cd $(FIREFOX_BUILD_DIR); zip -r $(FIREFOX_EXTENSION_NAME) $(FIREFOX_EXTENSION_FILES)
@echo "extension created: " $(FIREFOX_EXTENSION_NAME)
# Build the amo extension too (remove the updateUrl)
@sed -i.bak "/updateURL/d" $(FIREFOX_BUILD_DIR)/install.rdf
@rm -f $(FIREFOX_BUILD_DIR)/*.bak
@cd $(FIREFOX_BUILD_DIR); zip -r $(FIREFOX_AMO_EXTENSION_NAME) $(FIREFOX_EXTENSION_FILES)
@echo "AMO extension created: " $(FIREFOX_AMO_EXTENSION_NAME)
# Copy a standalone version of pdf.js inside the extension directory
@rm -Rf $(CHROME_CONTENT_DIR)
@mkdir -p $(CHROME_CONTENT_DIR)/$(BUILD_DIR)
@mkdir -p $(CHROME_CONTENT_DIR)/web
@cp $(BUILD_TARGET) $(CHROME_CONTENT_DIR)/$(BUILD_DIR)
@cp -r $(PDF_WEB_FILES) $(CHROME_CONTENT_DIR)/web/
@mv -f $(CHROME_CONTENT_DIR)/web/viewer-production.html $(CHROME_CONTENT_DIR)/web/viewer.html
# Clear out everything in the chrome extension build directory
@rm -Rf $(CHROME_BUILD_DIR)
@mkdir -p $(CHROME_BUILD_CONTENT)
@mkdir -p $(CHROME_BUILD_CONTENT)/$(BUILD_DIR)
@mkdir -p $(CHROME_BUILD_CONTENT)/web
@cp -R $(CHROME_EXTENSION_FILES) $(CHROME_BUILD_DIR)/
# Copy a standalone version of pdf.js inside the content directory
@cp $(BUILD_TARGET) $(CHROME_BUILD_CONTENT)/$(BUILD_DIR)/
@cp -r $(PDF_WEB_FILES) $(CHROME_BUILD_CONTENT)/web/
@mv -f $(CHROME_BUILD_CONTENT)/web/viewer-production.html $(CHROME_BUILD_CONTENT)/web/viewer.html
# Create the crx
#TODO

View File

@ -1,8 +1,5 @@
# pdf.js
# PDF.JS
## Overview
pdf.js is an HTML5 technology experiment that explores building a faithful
and efficient Portable Document Format (PDF) renderer without native code
@ -16,7 +13,7 @@ successful.
## Getting started
# Getting started
### Online demo
@ -29,11 +26,12 @@ using the pdf.js API.
### Extension
An up-to-date Firefox extension is also available:
A Firefox extension is also available:
+ http://mozilla.github.com/pdf.js/extensions/firefox/pdf.js.xpi
(The above link is updated upon every merge to our master branch).
Note that this extension is self-updating, and by default Firefox will auto-update extensions on a
daily basis (you can change this through the `extensions.update.interval` option in `about:config`).
For an experimental Chrome extension, get the code as explained below and issue `make extension`.
Then open Chrome with the flag `--enable-experimental-extension-apis`, go to `Tools > Extension`
@ -68,12 +66,12 @@ In order to bundle all `src/` files into a final `pdf.js`, issue:
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).
## Learning
# Learning
Here are some initial pointers to help contributors get off the ground.
Additional resources are available in a separate section below.
#### Hello world
### Hello world
For a "hello world" example, take a look at:
@ -82,7 +80,7 @@ For a "hello world" example, take a look at:
This example illustrates the bare minimum ingredients for integrating pdf.js
in a custom project.
#### Introductory video
### Introductory video
Check out the presentation by our contributor Julian Viereck on the inner
workings of PDF and pdf.js:
@ -92,7 +90,7 @@ workings of PDF and pdf.js:
## Contributing
# Contributing
pdf.js is a community-driven project, so contributors are always welcome.
Simply fork our repo and contribute away. Good starting places for picking
@ -122,7 +120,7 @@ You can add your name to it! :)
## Running the tests
# Running the tests
pdf.js comes with browser-level regression tests that allow one to probe
whether it's able to successfully parse PDFs, as well as compare its output
@ -148,7 +146,7 @@ images. The test type `load` simply tests whether the file loads without
raising any errors.
## Running tests through our bot
### Running tests through our bot
If you are a reviewer, you can use our remote bot to issue comprehensive tests
against reference images before merging pull requests.
@ -158,7 +156,7 @@ See the bot repo for details:
+ https://github.com/mozilla/pdf.js-bot
## Additional resources
# Additional resources
Gallery of user projects and modifications:
@ -188,7 +186,7 @@ Follow us on twitter: @pdfjs
## PDF-related resources
### PDF-related resources
A really basic overview of PDF is described here:
@ -205,4 +203,3 @@ a "PDF Reference" from Adobe:
Recommended chapters to read: "2. Overview", "3.4 File Structure",
"4.1 Graphics Objects" that lists the PDF commands.

View File

@ -23,6 +23,7 @@
<script type="text/javascript" src="../../src/stream.js"></script>
<script type="text/javascript" src="../../src/worker.js"></script>
<script type="text/javascript" src="../../external/jpgjs/jpg.js"></script>
<script type="text/javascript" src="../../src/jpx.js"></script>
<script type="text/javascript">
// Specify the main script used to create a new PDF.JS web worker.

View File

@ -23,6 +23,7 @@
<script type="text/javascript" src="../../src/stream.js"></script>
<script type="text/javascript" src="../../src/worker.js"></script>
<script type="text/javascript" src="../../external/jpgjs/jpg.js"></script>
<script type="text/javascript" src="../../src/jpx.js"></script>
<script type="text/javascript">
// Specify the main script used to create a new PDF.JS web worker.

View File

@ -6,7 +6,7 @@
<Description about="urn:mozilla:install-manifest">
<em:id>uriloader@pdf.js</em:id>
<em:name>pdf.js</em:name>
<em:version>0.1.0</em:version>
<em:version>0.2.PDFJSSCRIPT_BUILD</em:version>
<em:iconURL>chrome://pdf.js/skin/logo.png</em:iconURL>
<em:targetApplication>
<Description>
@ -17,9 +17,11 @@
</em:targetApplication>
<em:bootstrap>true</em:bootstrap>
<em:unpack>true</em:unpack>
<em:creator>Vivien Nicolas</em:creator>
<em:creator>Mozilla Labs</em:creator>
<em:description>pdf.js uri loader</em:description>
<em:homepageURL>https://github.com/mozilla/pdf.js/</em:homepageURL>
<em:type>2</em:type>
<!-- Use the raw link for updates so we we can use SSL. -->
<em:updateURL>https://github.com/mozilla/pdf.js/raw/gh-pages/extensions/firefox/update.rdf</em:updateURL>
</Description>
</RDF>

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<RDF:RDF xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:em="http://www.mozilla.org/2004/em-rdf#">
<RDF:Description about="urn:mozilla:extension:uriloader@pdf.js">
<em:updates>
<RDF:Seq>
<RDF:li>
<RDF:Description>
<em:version>0.2.PDFJSSCRIPT_BUILD</em:version>
<em:targetApplication>
<RDF:Description>
<em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
<em:minVersion>6.0</em:minVersion>
<em:maxVersion>11.*</em:maxVersion>
<!-- Use the raw link for updates so we we can use SSL. -->
<em:updateLink>https://github.com/mozilla/pdf.js/raw/gh-pages/extensions/firefox/pdf.js.xpi</em:updateLink>
</RDF:Description>
</em:targetApplication>
</RDF:Description>
</RDF:li>
</RDF:Seq>
</em:updates>
</RDF:Description>
</RDF:RDF>

View File

@ -1,676 +0,0 @@
jasmine.HtmlReporterHelpers = {};
jasmine.HtmlReporterHelpers.createDom = function(type, attrs, childrenVarArgs) {
var el = document.createElement(type);
for (var i = 2; i < arguments.length; i++) {
var child = arguments[i];
if (typeof child === 'string') {
el.appendChild(document.createTextNode(child));
} else {
if (child) {
el.appendChild(child);
}
}
}
for (var attr in attrs) {
if (attr == "className") {
el[attr] = attrs[attr];
} else {
el.setAttribute(attr, attrs[attr]);
}
}
return el;
};
jasmine.HtmlReporterHelpers.getSpecStatus = function(child) {
var results = child.results();
var status = results.passed() ? 'passed' : 'failed';
if (results.skipped) {
status = 'skipped';
}
return status;
};
jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) {
var parentDiv = this.dom.summary;
var parentSuite = (typeof child.parentSuite == 'undefined') ? 'suite' : 'parentSuite';
var parent = child[parentSuite];
if (parent) {
if (typeof this.views.suites[parent.id] == 'undefined') {
this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views);
}
parentDiv = this.views.suites[parent.id].element;
}
parentDiv.appendChild(childElement);
};
jasmine.HtmlReporterHelpers.addHelpers = function(ctor) {
for(var fn in jasmine.HtmlReporterHelpers) {
ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn];
}
};
jasmine.HtmlReporter = function(_doc) {
var self = this;
var doc = _doc || window.document;
var reporterView;
var dom = {};
// Jasmine Reporter Public Interface
self.logRunningSpecs = false;
self.reportRunnerStarting = function(runner) {
var specs = runner.specs() || [];
if (specs.length == 0) {
return;
}
createReporterDom(runner.env.versionString());
doc.body.appendChild(dom.reporter);
reporterView = new jasmine.HtmlReporter.ReporterView(dom);
reporterView.addSpecs(specs, self.specFilter);
};
self.reportRunnerResults = function(runner) {
reporterView.complete();
};
self.reportSuiteResults = function(suite) {
reporterView.suiteComplete(suite);
};
self.reportSpecStarting = function(spec) {
if (self.logRunningSpecs) {
self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...');
}
};
self.reportSpecResults = function(spec) {
reporterView.specComplete(spec);
};
self.log = function() {
var console = jasmine.getGlobal().console;
if (console && console.log) {
if (console.log.apply) {
console.log.apply(console, arguments);
} else {
console.log(arguments); // ie fix: console.log.apply doesn't exist on ie
}
}
};
self.specFilter = function(spec) {
if (!focusedSpecName()) {
return true;
}
return spec.getFullName().indexOf(focusedSpecName()) === 0;
};
return self;
function focusedSpecName() {
var specName;
(function memoizeFocusedSpec() {
if (specName) {
return;
}
var paramMap = [];
var params = doc.location.search.substring(1).split('&');
for (var i = 0; i < params.length; i++) {
var p = params[i].split('=');
paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
}
specName = paramMap.spec;
})();
return specName;
}
function createReporterDom(version) {
dom.reporter = self.createDom('div', { id: 'HTMLReporter', className: 'jasmine_reporter' },
dom.banner = self.createDom('div', { className: 'banner' },
self.createDom('span', { className: 'title' }, "Jasmine "),
self.createDom('span', { className: 'version' }, version)),
dom.symbolSummary = self.createDom('ul', {className: 'symbolSummary'}),
dom.alert = self.createDom('div', {className: 'alert'}),
dom.results = self.createDom('div', {className: 'results'},
dom.summary = self.createDom('div', { className: 'summary' }),
dom.details = self.createDom('div', { id: 'details' }))
);
}
};
jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter);jasmine.HtmlReporterHelpers = {};
jasmine.HtmlReporterHelpers.createDom = function(type, attrs, childrenVarArgs) {
var el = document.createElement(type);
for (var i = 2; i < arguments.length; i++) {
var child = arguments[i];
if (typeof child === 'string') {
el.appendChild(document.createTextNode(child));
} else {
if (child) {
el.appendChild(child);
}
}
}
for (var attr in attrs) {
if (attr == "className") {
el[attr] = attrs[attr];
} else {
el.setAttribute(attr, attrs[attr]);
}
}
return el;
};
jasmine.HtmlReporterHelpers.getSpecStatus = function(child) {
var results = child.results();
var status = results.passed() ? 'passed' : 'failed';
if (results.skipped) {
status = 'skipped';
}
return status;
};
jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) {
var parentDiv = this.dom.summary;
var parentSuite = (typeof child.parentSuite == 'undefined') ? 'suite' : 'parentSuite';
var parent = child[parentSuite];
if (parent) {
if (typeof this.views.suites[parent.id] == 'undefined') {
this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views);
}
parentDiv = this.views.suites[parent.id].element;
}
parentDiv.appendChild(childElement);
};
jasmine.HtmlReporterHelpers.addHelpers = function(ctor) {
for(var fn in jasmine.HtmlReporterHelpers) {
ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn];
}
};
jasmine.HtmlReporter.ReporterView = function(dom) {
this.startedAt = new Date();
this.runningSpecCount = 0;
this.completeSpecCount = 0;
this.passedCount = 0;
this.failedCount = 0;
this.skippedCount = 0;
this.createResultsMenu = function() {
this.resultsMenu = this.createDom('span', {className: 'resultsMenu bar'},
this.summaryMenuItem = this.createDom('a', {className: 'summaryMenuItem', href: "#"}, '0 specs'),
' | ',
this.detailsMenuItem = this.createDom('a', {className: 'detailsMenuItem', href: "#"}, '0 failing'));
this.summaryMenuItem.onclick = function() {
dom.reporter.className = dom.reporter.className.replace(/ showDetails/g, '');
};
this.detailsMenuItem.onclick = function() {
showDetails();
};
};
this.addSpecs = function(specs, specFilter) {
this.totalSpecCount = specs.length;
this.views = {
specs: {},
suites: {}
};
for (var i = 0; i < specs.length; i++) {
var spec = specs[i];
this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom, this.views);
if (specFilter(spec)) {
this.runningSpecCount++;
}
}
};
this.specComplete = function(spec) {
this.completeSpecCount++;
if (isUndefined(this.views.specs[spec.id])) {
this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom);
}
var specView = this.views.specs[spec.id];
switch (specView.status()) {
case 'passed':
this.passedCount++;
break;
case 'failed':
this.failedCount++;
break;
case 'skipped':
this.skippedCount++;
break;
}
specView.refresh();
this.refresh();
};
this.suiteComplete = function(suite) {
var suiteView = this.views.suites[suite.id];
if (isUndefined(suiteView)) {
return;
}
suiteView.refresh();
};
this.refresh = function() {
if (isUndefined(this.resultsMenu)) {
this.createResultsMenu();
}
// currently running UI
if (isUndefined(this.runningAlert)) {
this.runningAlert = this.createDom('a', {href: "?", className: "runningAlert bar"});
dom.alert.appendChild(this.runningAlert);
}
this.runningAlert.innerHTML = "Running " + this.completeSpecCount + " of " + specPluralizedFor(this.totalSpecCount);
// skipped specs UI
if (isUndefined(this.skippedAlert)) {
this.skippedAlert = this.createDom('a', {href: "?", className: "skippedAlert bar"});
}
this.skippedAlert.innerHTML = "Skipping " + this.skippedCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all";
if (this.skippedCount === 1 && isDefined(dom.alert)) {
dom.alert.appendChild(this.skippedAlert);
}
// passing specs UI
if (isUndefined(this.passedAlert)) {
this.passedAlert = this.createDom('span', {href: "?", className: "passingAlert bar"});
}
this.passedAlert.innerHTML = "Passing " + specPluralizedFor(this.passedCount);
// failing specs UI
if (isUndefined(this.failedAlert)) {
this.failedAlert = this.createDom('span', {href: "?", className: "failingAlert bar"});
}
this.failedAlert.innerHTML = "Failing " + specPluralizedFor(this.failedCount);
if (this.failedCount === 1 && isDefined(dom.alert)) {
dom.alert.appendChild(this.failedAlert);
dom.alert.appendChild(this.resultsMenu);
}
// summary info
this.summaryMenuItem.innerHTML = "" + specPluralizedFor(this.runningSpecCount);
this.detailsMenuItem.innerHTML = "" + this.failedCount + " failing";
};
this.complete = function() {
dom.alert.removeChild(this.runningAlert);
this.skippedAlert.innerHTML = "Ran " + this.runningSpecCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all";
if (this.failedCount === 0) {
dom.alert.appendChild(this.createDom('span', {className: 'passingAlert bar'}, "Passing " + specPluralizedFor(this.passedCount)));
} else {
showDetails();
}
dom.banner.appendChild(this.createDom('span', {className: 'duration'}, "finished in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"));
};
return this;
function showDetails() {
if (dom.reporter.className.search(/showDetails/) === -1) {
dom.reporter.className += " showDetails";
}
}
function isUndefined(obj) {
return typeof obj === 'undefined';
}
function isDefined(obj) {
return !isUndefined(obj);
}
function specPluralizedFor(count) {
var str = count + " spec";
if (count > 1) {
str += "s"
}
return str;
}
};
jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.ReporterView);
jasmine.HtmlReporter.SpecView = function(spec, dom, views) {
this.spec = spec;
this.dom = dom;
this.views = views;
this.symbol = this.createDom('li', { className: 'pending' });
this.dom.symbolSummary.appendChild(this.symbol);
this.summary = this.createDom('div', { className: 'specSummary' },
this.createDom('a', {
className: 'description',
href: '?spec=' + encodeURIComponent(this.spec.getFullName()),
title: this.spec.getFullName()
}, this.spec.description)
);
this.detail = this.createDom('div', { className: 'specDetail' },
this.createDom('a', {
className: 'description',
href: '?spec=' + encodeURIComponent(this.spec.getFullName()),
title: this.spec.getFullName()
}, this.spec.getFullName())
);
};
jasmine.HtmlReporter.SpecView.prototype.status = function() {
return this.getSpecStatus(this.spec);
};
jasmine.HtmlReporter.SpecView.prototype.refresh = function() {
this.symbol.className = this.status();
switch (this.status()) {
case 'skipped':
break;
case 'passed':
this.appendSummaryToSuiteDiv();
break;
case 'failed':
this.appendSummaryToSuiteDiv();
this.appendFailureDetail();
break;
}
};
jasmine.HtmlReporter.SpecView.prototype.appendSummaryToSuiteDiv = function() {
this.summary.className += ' ' + this.status();
this.appendToSummary(this.spec, this.summary);
};
jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function() {
this.detail.className += ' ' + this.status();
var resultItems = this.spec.results().getItems();
var messagesDiv = this.createDom('div', { className: 'messages' });
for (var i = 0; i < resultItems.length; i++) {
var result = resultItems[i];
if (result.type == 'log') {
messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString()));
} else if (result.type == 'expect' && result.passed && !result.passed()) {
messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message));
if (result.trace.stack) {
messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack));
}
}
}
if (messagesDiv.childNodes.length > 0) {
this.detail.appendChild(messagesDiv);
this.dom.details.appendChild(this.detail);
}
};
jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SpecView);jasmine.HtmlReporter.SuiteView = function(suite, dom, views) {
this.suite = suite;
this.dom = dom;
this.views = views;
this.element = this.createDom('div', { className: 'suite' },
this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(this.suite.getFullName()) }, this.suite.description)
);
this.appendToSummary(this.suite, this.element);
};
jasmine.HtmlReporter.SuiteView.prototype.status = function() {
return this.getSpecStatus(this.suite);
};
jasmine.HtmlReporter.SuiteView.prototype.refresh = function() {
this.element.className += " " + this.status();
};
jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SuiteView);
/* @deprecated Use jasmine.HtmlReporter instead
*/
jasmine.TrivialReporter = function(doc) {
this.document = doc || document;
this.suiteDivs = {};
this.logRunningSpecs = false;
};
jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) {
var el = document.createElement(type);
for (var i = 2; i < arguments.length; i++) {
var child = arguments[i];
if (typeof child === 'string') {
el.appendChild(document.createTextNode(child));
} else {
if (child) { el.appendChild(child); }
}
}
for (var attr in attrs) {
if (attr == "className") {
el[attr] = attrs[attr];
} else {
el.setAttribute(attr, attrs[attr]);
}
}
return el;
};
jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) {
var showPassed, showSkipped;
this.outerDiv = this.createDom('div', { id: 'TrivialReporter', className: 'jasmine_reporter' },
this.createDom('div', { className: 'banner' },
this.createDom('div', { className: 'logo' },
this.createDom('span', { className: 'title' }, "Jasmine"),
this.createDom('span', { className: 'version' }, runner.env.versionString())),
this.createDom('div', { className: 'options' },
"Show ",
showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }),
this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "),
showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }),
this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped")
)
),
this.runnerDiv = this.createDom('div', { className: 'runner running' },
this.createDom('a', { className: 'run_spec', href: '?' }, "run all"),
this.runnerMessageSpan = this.createDom('span', {}, "Running..."),
this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, ""))
);
this.document.body.appendChild(this.outerDiv);
var suites = runner.suites();
for (var i = 0; i < suites.length; i++) {
var suite = suites[i];
var suiteDiv = this.createDom('div', { className: 'suite' },
this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"),
this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description));
this.suiteDivs[suite.id] = suiteDiv;
var parentDiv = this.outerDiv;
if (suite.parentSuite) {
parentDiv = this.suiteDivs[suite.parentSuite.id];
}
parentDiv.appendChild(suiteDiv);
}
this.startedAt = new Date();
var self = this;
showPassed.onclick = function(evt) {
if (showPassed.checked) {
self.outerDiv.className += ' show-passed';
} else {
self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, '');
}
};
showSkipped.onclick = function(evt) {
if (showSkipped.checked) {
self.outerDiv.className += ' show-skipped';
} else {
self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, '');
}
};
};
jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) {
var results = runner.results();
var className = (results.failedCount > 0) ? "runner failed" : "runner passed";
this.runnerDiv.setAttribute("class", className);
//do it twice for IE
this.runnerDiv.setAttribute("className", className);
var specs = runner.specs();
var specCount = 0;
for (var i = 0; i < specs.length; i++) {
if (this.specFilter(specs[i])) {
specCount++;
}
}
var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s");
message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s";
this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild);
this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString()));
};
jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) {
var results = suite.results();
var status = results.passed() ? 'passed' : 'failed';
if (results.totalCount === 0) { // todo: change this to check results.skipped
status = 'skipped';
}
this.suiteDivs[suite.id].className += " " + status;
};
jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) {
if (this.logRunningSpecs) {
this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...');
}
};
jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) {
var results = spec.results();
var status = results.passed() ? 'passed' : 'failed';
if (results.skipped) {
status = 'skipped';
}
var specDiv = this.createDom('div', { className: 'spec ' + status },
this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"),
this.createDom('a', {
className: 'description',
href: '?spec=' + encodeURIComponent(spec.getFullName()),
title: spec.getFullName()
}, spec.description));
var resultItems = results.getItems();
var messagesDiv = this.createDom('div', { className: 'messages' });
for (var i = 0; i < resultItems.length; i++) {
var result = resultItems[i];
if (result.type == 'log') {
messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString()));
} else if (result.type == 'expect' && result.passed && !result.passed()) {
messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message));
if (result.trace.stack) {
messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack));
}
}
}
if (messagesDiv.childNodes.length > 0) {
specDiv.appendChild(messagesDiv);
}
this.suiteDivs[spec.suite.id].appendChild(specDiv);
};
jasmine.TrivialReporter.prototype.log = function() {
var console = jasmine.getGlobal().console;
if (console && console.log) {
if (console.log.apply) {
console.log.apply(console, arguments);
} else {
console.log(arguments); // ie fix: console.log.apply doesn't exist on ie
}
}
};
jasmine.TrivialReporter.prototype.getLocation = function() {
return this.document.location;
};
jasmine.TrivialReporter.prototype.specFilter = function(spec) {
var paramMap = {};
var params = this.getLocation().search.substring(1).split('&');
for (var i = 0; i < params.length; i++) {
var p = params[i].split('=');
paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
}
if (!paramMap.spec) {
return true;
}
return spec.getFullName().indexOf(paramMap.spec) === 0;
};

View File

@ -1,81 +0,0 @@
body { background-color: #eeeeee; padding: 0; margin: 5px; overflow-y: scroll; }
#HTMLReporter { font-size: 11px; font-family: Monaco, "Lucida Console", monospace; line-height: 14px; color: #333333; }
#HTMLReporter a { text-decoration: none; }
#HTMLReporter a:hover { text-decoration: underline; }
#HTMLReporter p, #HTMLReporter h1, #HTMLReporter h2, #HTMLReporter h3, #HTMLReporter h4, #HTMLReporter h5, #HTMLReporter h6 { margin: 0; line-height: 14px; }
#HTMLReporter .banner, #HTMLReporter .symbolSummary, #HTMLReporter .summary, #HTMLReporter .resultMessage, #HTMLReporter .specDetail .description, #HTMLReporter .alert .bar, #HTMLReporter .stackTrace { padding-left: 9px; padding-right: 9px; }
#HTMLReporter #jasmine_content { position: fixed; right: 100%; }
#HTMLReporter .version { color: #aaaaaa; }
#HTMLReporter .banner { margin-top: 14px; }
#HTMLReporter .duration { color: #aaaaaa; float: right; }
#HTMLReporter .symbolSummary { overflow: hidden; *zoom: 1; margin: 14px 0; }
#HTMLReporter .symbolSummary li { display: block; float: left; height: 7px; width: 14px; margin-bottom: 7px; font-size: 16px; }
#HTMLReporter .symbolSummary li.passed { font-size: 14px; }
#HTMLReporter .symbolSummary li.passed:before { color: #5e7d00; content: "\02022"; }
#HTMLReporter .symbolSummary li.failed { line-height: 9px; }
#HTMLReporter .symbolSummary li.failed:before { color: #b03911; content: "x"; font-weight: bold; margin-left: -1px; }
#HTMLReporter .symbolSummary li.skipped { font-size: 14px; }
#HTMLReporter .symbolSummary li.skipped:before { color: #bababa; content: "\02022"; }
#HTMLReporter .symbolSummary li.pending { line-height: 11px; }
#HTMLReporter .symbolSummary li.pending:before { color: #aaaaaa; content: "-"; }
#HTMLReporter .bar { line-height: 28px; font-size: 14px; display: block; color: #eee; }
#HTMLReporter .runningAlert { background-color: #666666; }
#HTMLReporter .skippedAlert { background-color: #aaaaaa; }
#HTMLReporter .skippedAlert:first-child { background-color: #333333; }
#HTMLReporter .skippedAlert:hover { text-decoration: none; color: white; text-decoration: underline; }
#HTMLReporter .passingAlert { background-color: #a6b779; }
#HTMLReporter .passingAlert:first-child { background-color: #5e7d00; }
#HTMLReporter .failingAlert { background-color: #cf867e; }
#HTMLReporter .failingAlert:first-child { background-color: #b03911; }
#HTMLReporter .results { margin-top: 14px; }
#HTMLReporter #details { display: none; }
#HTMLReporter .resultsMenu, #HTMLReporter .resultsMenu a { background-color: #fff; color: #333333; }
#HTMLReporter.showDetails .summaryMenuItem { font-weight: normal; text-decoration: inherit; }
#HTMLReporter.showDetails .summaryMenuItem:hover { text-decoration: underline; }
#HTMLReporter.showDetails .detailsMenuItem { font-weight: bold; text-decoration: underline; }
#HTMLReporter.showDetails .summary { display: none; }
#HTMLReporter.showDetails #details { display: block; }
#HTMLReporter .summaryMenuItem { font-weight: bold; text-decoration: underline; }
#HTMLReporter .summary { margin-top: 14px; }
#HTMLReporter .summary .suite .suite, #HTMLReporter .summary .specSummary { margin-left: 14px; }
#HTMLReporter .summary .specSummary.passed a { color: #5e7d00; }
#HTMLReporter .summary .specSummary.failed a { color: #b03911; }
#HTMLReporter .description + .suite { margin-top: 0; }
#HTMLReporter .suite { margin-top: 14px; }
#HTMLReporter .suite a { color: #333333; }
#HTMLReporter #details .specDetail { margin-bottom: 28px; }
#HTMLReporter #details .specDetail .description { display: block; color: white; background-color: #b03911; }
#HTMLReporter .resultMessage { padding-top: 14px; color: #333333; }
#HTMLReporter .resultMessage span.result { display: block; }
#HTMLReporter .stackTrace { margin: 5px 0 0 0; max-height: 224px; overflow: auto; line-height: 18px; color: #666666; border: 1px solid #ddd; background: white; white-space: pre; }
#TrivialReporter { padding: 8px 13px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; overflow-y: scroll; background-color: white; font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif; /*.resultMessage {*/ /*white-space: pre;*/ /*}*/ }
#TrivialReporter a:visited, #TrivialReporter a { color: #303; }
#TrivialReporter a:hover, #TrivialReporter a:active { color: blue; }
#TrivialReporter .run_spec { float: right; padding-right: 5px; font-size: .8em; text-decoration: none; }
#TrivialReporter .banner { color: #303; background-color: #fef; padding: 5px; }
#TrivialReporter .logo { float: left; font-size: 1.1em; padding-left: 5px; }
#TrivialReporter .logo .version { font-size: .6em; padding-left: 1em; }
#TrivialReporter .runner.running { background-color: yellow; }
#TrivialReporter .options { text-align: right; font-size: .8em; }
#TrivialReporter .suite { border: 1px outset gray; margin: 5px 0; padding-left: 1em; }
#TrivialReporter .suite .suite { margin: 5px; }
#TrivialReporter .suite.passed { background-color: #dfd; }
#TrivialReporter .suite.failed { background-color: #fdd; }
#TrivialReporter .spec { margin: 5px; padding-left: 1em; clear: both; }
#TrivialReporter .spec.failed, #TrivialReporter .spec.passed, #TrivialReporter .spec.skipped { padding-bottom: 5px; border: 1px solid gray; }
#TrivialReporter .spec.failed { background-color: #fbb; border-color: red; }
#TrivialReporter .spec.passed { background-color: #bfb; border-color: green; }
#TrivialReporter .spec.skipped { background-color: #bbb; }
#TrivialReporter .messages { border-left: 1px dashed gray; padding-left: 1em; padding-right: 1em; }
#TrivialReporter .passed { background-color: #cfc; display: none; }
#TrivialReporter .failed { background-color: #fbb; }
#TrivialReporter .skipped { color: #777; background-color: #eee; display: none; }
#TrivialReporter .resultMessage span.result { display: block; line-height: 2em; color: black; }
#TrivialReporter .resultMessage .mismatch { color: black; }
#TrivialReporter .stackTrace { white-space: pre; font-size: .8em; margin-left: 10px; max-height: 5em; overflow: auto; border: 1px inset red; padding: 1em; background: #eef; }
#TrivialReporter .finished-at { padding-left: 1em; font-size: .6em; }
#TrivialReporter.show-passed .passed, #TrivialReporter.show-skipped .skipped { display: block; }
#TrivialReporter #jasmine_content { position: fixed; right: 100%; }
#TrivialReporter .runner { border: 1px solid gray; display: block; margin: 5px 0; padding: 2px 0 2px 10px; }

Binary file not shown.

Before

Width:  |  Height:  |  Size: 905 B

View File

@ -0,0 +1,198 @@
/**
* @fileoverview Jasmine JsTestDriver Adapter.
* @author misko@hevery.com (Misko Hevery)
*/
(function(window) {
var rootDescribes = new Describes(window);
var describePath = [];
rootDescribes.collectMode();
var JASMINE_TYPE = 'jasmine test case';
TestCase('Jasmine Adapter Tests', null, JASMINE_TYPE);
var jasminePlugin = {
name:'jasmine',
getTestRunsConfigurationFor: function(testCaseInfos, expressions, testRunsConfiguration) {
for (var i = 0; i < testCaseInfos.length; i++) {
if (testCaseInfos[i].getType() == JASMINE_TYPE) {
testRunsConfiguration.push(new jstestdriver.TestRunConfiguration(testCaseInfos[i], []));
}
}
return false;
},
runTestConfiguration: function(testRunConfiguration, onTestDone, onTestRunConfigurationComplete){
if (testRunConfiguration.getTestCaseInfo().getType() != JASMINE_TYPE) return false;
var jasmineEnv = jasmine.currentEnv_ = new jasmine.Env();
rootDescribes.playback();
var specLog = jstestdriver.console.log_ = [];
var start;
jasmineEnv.specFilter = function(spec) {
return rootDescribes.isExclusive(spec);
};
jasmineEnv.reporter = {
log: function(str){
specLog.push(str);
},
reportRunnerStarting: function(runner) { },
reportSpecStarting: function(spec) {
specLog = jstestdriver.console.log_ = [];
start = new Date().getTime();
},
reportSpecResults: function(spec) {
var suite = spec.suite;
var results = spec.results();
if (results.skipped) return;
var end = new Date().getTime();
var messages = [];
var resultItems = results.getItems();
var state = 'passed';
for ( var i = 0; i < resultItems.length; i++) {
if (!resultItems[i].passed()) {
state = resultItems[i].message.match(/AssertionError:/) ? 'error' : 'failed';
messages.push({
message: resultItems[i].toString(),
name: resultItems[i].trace.name,
stack: formatStack(resultItems[i].trace.stack)
});
}
}
onTestDone(
new jstestdriver.TestResult(
suite.getFullName(),
spec.description,
state,
jstestdriver.angular.toJson(messages),
specLog.join('\n'),
end - start));
},
reportSuiteResults: function(suite) {},
reportRunnerResults: function(runner) {
onTestRunConfigurationComplete();
}
};
jasmineEnv.execute();
return true;
},
onTestsFinish: function(){
jasmine.currentEnv_ = null;
rootDescribes.collectMode();
}
};
jstestdriver.pluginRegistrar.register(jasminePlugin);
function formatStack(stack) {
var lines = (stack||'').split(/\r?\n/);
var frames = [];
for (i = 0; i < lines.length; i++) {
if (!lines[i].match(/\/jasmine[\.-]/)) {
frames.push(lines[i].replace(/https?:\/\/\w+(:\d+)?\/test\//, '').replace(/^\s*/, ' '));
}
}
return frames.join('\n');
}
function noop(){}
function Describes(window){
var describes = {};
var beforeEachs = {};
var afterEachs = {};
// Here we store:
// 0: everyone runs
// 1: run everything under ddescribe
// 2: run only iits (ignore ddescribe)
var exclusive = 0;
var collectMode = true;
intercept('describe', describes);
intercept('xdescribe', describes);
intercept('beforeEach', beforeEachs);
intercept('afterEach', afterEachs);
function intercept(functionName, collection){
window[functionName] = function(desc, fn){
if (collectMode) {
collection[desc] = function(){
jasmine.getEnv()[functionName](desc, fn);
};
} else {
jasmine.getEnv()[functionName](desc, fn);
}
};
}
window.ddescribe = function(name, fn){
if (exclusive < 1) {
exclusive = 1; // run ddescribe only
}
window.describe(name, function(){
var oldIt = window.it;
window.it = function(name, fn){
fn.exclusive = 1; // run anything under ddescribe
jasmine.getEnv().it(name, fn);
};
try {
fn.call(this);
} finally {
window.it = oldIt;
};
});
};
window.iit = function(name, fn){
exclusive = fn.exclusive = 2; // run only iits
jasmine.getEnv().it(name, fn);
};
this.collectMode = function() {
collectMode = true;
exclusive = 0; // run everything
};
this.playback = function(){
collectMode = false;
playback(beforeEachs);
playback(afterEachs);
playback(describes);
function playback(set) {
for ( var name in set) {
set[name]();
}
}
};
this.isExclusive = function(spec) {
if (exclusive) {
var blocks = spec.queue.blocks;
for ( var i = 0; i < blocks.length; i++) {
if (blocks[i].func.exclusive >= exclusive) {
return true;
}
}
return false;
}
return true;
};
}
})(window);
// Patch Jasmine for proper stack traces
jasmine.Spec.prototype.fail = function (e) {
var expectationResult = new jasmine.ExpectationResult({
passed: false,
message: e ? jasmine.util.formatException(e) : 'Exception'
});
// PATCH
if (e) {
expectationResult.trace = e;
}
this.results_.addResult(expectationResult);
};

23
external/jasmineAdapter/MIT.LICENSE vendored Normal file
View File

@ -0,0 +1,23 @@
Copyright (c) 2010
Misko Hevery <misko@hevery.com>
Olmo Maldonado <me@ibolmo.com>
Christoph Pojer <christoph.pojer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Binary file not shown.

202
external/jsTestDriver/LICENSE-2.0.txt vendored Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -48,6 +48,7 @@ var CanvasExtraState = (function CanvasExtraStateClosure() {
// Note: fill alpha applies to all non-stroking operations
this.fillAlpha = 1;
this.strokeAlpha = 1;
this.lineWidth = 1;
this.old = old;
}
@ -257,8 +258,9 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
this.ctx.scale(cw / mediaBox.width, ch / mediaBox.height);
// Move the media left-top corner to the (0,0) canvas position
this.ctx.translate(-mediaBox.x, -mediaBox.y);
this.textDivs = [];
this.textLayerQueue = [];
if (this.textLayer)
this.textLayer.beginLayout();
},
executeIRQueue: function canvasGraphicsExecuteIRQueue(codeIR,
@ -322,31 +324,13 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
endDrawing: function canvasGraphicsEndDrawing() {
this.ctx.restore();
var textLayer = this.textLayer;
if (!textLayer)
return;
var self = this;
var textDivs = this.textDivs;
this.textLayerTimer = setInterval(function renderTextLayer() {
if (textDivs.length === 0) {
clearInterval(self.textLayerTimer);
return;
}
var textDiv = textDivs.shift();
if (textDiv.dataset.textLength > 1) { // avoid div by zero
textLayer.appendChild(textDiv);
// Adjust div width (via letterSpacing) to match canvas text
// Due to the .offsetWidth calls, this is slow
textDiv.style.letterSpacing =
((textDiv.dataset.canvasWidth - textDiv.offsetWidth) /
(textDiv.dataset.textLength - 1)) + 'px';
}
}, 0);
if (this.textLayer)
this.textLayer.endLayout();
},
// Graphics state
setLineWidth: function canvasGraphicsSetLineWidth(width) {
this.current.lineWidth = width;
this.ctx.lineWidth = width;
},
setLineCap: function canvasGraphicsSetLineCap(style) {
@ -361,6 +345,8 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
setDash: function canvasGraphicsSetDash(dashArray, dashPhase) {
this.ctx.mozDash = dashArray;
this.ctx.mozDashOffset = dashPhase;
this.ctx.webkitLineDash = dashArray;
this.ctx.webkitLineDashOffset = dashPhase;
},
setRenderingIntent: function canvasGraphicsSetRenderingIntent(intent) {
TODO('set rendering intent: ' + intent);
@ -458,6 +444,8 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
var ctx = this.ctx;
var strokeColor = this.current.strokeColor;
if (this.current.lineWidth === 0)
ctx.lineWidth = this.getSinglePixelWidth();
// For stroke we want to temporarily change the global alpha to the
// stroking alpha.
ctx.globalAlpha = this.current.strokeAlpha;
@ -573,7 +561,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
(fontObj.bold ? 'bold' : 'normal');
var italic = fontObj.italic ? 'italic' : 'normal';
var serif = fontObj.serif ? 'serif' : 'sans-serif';
var serif = fontObj.isSerifFont ? 'serif' : 'sans-serif';
var typeface = '"' + name + '", ' + serif;
var rule = italic + ' ' + bold + ' ' + size + 'px ' + typeface;
this.ctx.font = rule;
@ -632,24 +620,6 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
return geometry;
},
pushTextDivs: function canvasGraphicsPushTextDivs(text) {
var div = document.createElement('div');
var fontSize = this.current.fontSize;
// vScale and hScale already contain the scaling to pixel units
// as mozCurrentTransform reflects ctx.scale() changes
// (see beginDrawing())
var fontHeight = fontSize * text.geom.vScale;
div.dataset.canvasWidth = text.canvasWidth * text.geom.hScale;
div.style.fontSize = fontHeight + 'px';
div.style.fontFamily = this.current.font.loadedName || 'sans-serif';
div.style.left = text.geom.x + 'px';
div.style.top = (text.geom.y - fontHeight) + 'px';
div.innerHTML = text.str;
div.dataset.textLength = text.length;
this.textDivs.push(div);
},
showText: function canvasGraphicsShowText(str, skipTextSelection) {
var ctx = this.ctx;
var current = this.current;
@ -674,7 +644,6 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
ctx.translate(current.x, current.y);
ctx.scale(textHScale, 1);
ctx.lineWidth /= current.textMatrix[0];
if (textSelection) {
this.save();
@ -711,7 +680,15 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
} else {
ctx.save();
this.applyTextTransforms();
ctx.lineWidth /= current.textMatrix[0] * fontMatrix[0];
var lineWidth = current.lineWidth;
var scale = Math.abs(current.textMatrix[0] * fontMatrix[0]);
if (scale == 0 || lineWidth == 0)
lineWidth = this.getSinglePixelWidth();
else
lineWidth /= scale;
ctx.lineWidth = lineWidth;
if (textSelection)
text.geom = this.getTextGeometry();
@ -749,7 +726,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
width += charWidth;
text.str += glyph.unicode === ' ' ? '&nbsp;' : glyph.unicode;
text.str += glyph.unicode === ' ' ? '\u00A0' : glyph.unicode;
text.length++;
text.canvasWidth += charWidth;
}
@ -758,7 +735,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
}
if (textSelection)
this.pushTextDivs(text);
this.textLayer.appendText(text, font.loadedName, fontSize);
return text;
},
@ -801,7 +778,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
if (e < 0 && text.geom.spaceWidth > 0) { // avoid div by zero
var numFakeSpaces = Math.round(-e / text.geom.spaceWidth);
if (numFakeSpaces > 0) {
text.str += '&nbsp;';
text.str += '\u00A0';
text.length++;
}
}
@ -811,7 +788,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
if (textSelection) {
if (shownText.str === ' ') {
text.str += '&nbsp;';
text.str += '\u00A0';
} else {
text.str += shownText.str;
}
@ -824,7 +801,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
}
if (textSelection)
this.pushTextDivs(text);
this.textLayer.appendText(text, font.loadedName, fontSize);
},
nextLineShowText: function canvasGraphicsNextLineShowText(text) {
this.nextLine();
@ -866,8 +843,8 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
},
setStrokeColor: function canvasGraphicsSetStrokeColor(/*...*/) {
var cs = this.current.strokeColorSpace;
var color = cs.getRgb(arguments);
var color = Util.makeCssRgb.apply(null, cs.getRgb(arguments));
var rgbColor = cs.getRgb(arguments);
var color = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]);
this.ctx.strokeStyle = color;
this.current.strokeColor = color;
},
@ -904,7 +881,8 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
},
setFillColor: function canvasGraphicsSetFillColor(/*...*/) {
var cs = this.current.fillColorSpace;
var color = Util.makeCssRgb.apply(null, cs.getRgb(arguments));
var rgbColor = cs.getRgb(arguments);
var color = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]);
this.ctx.fillStyle = color;
this.current.fillColor = color;
},
@ -1175,6 +1153,10 @@ var CanvasGraphics = (function CanvasGraphicsClosure() {
},
restoreFillRule: function canvasGraphicsRestoreFillRule(rule) {
this.ctx.mozFillRule = rule;
},
getSinglePixelWidth: function getSinglePixelWidth(scale) {
var inverse = this.ctx.mozCurrentTransformInverse;
return Math.abs(inverse[0] + inverse[2]);
}
};

View File

@ -70,8 +70,7 @@ var Page = (function PageClosure() {
this.xref = xref;
this.ref = ref;
this.ctx = null;
this.callback = null;
this.displayReadyPromise = null;
}
Page.prototype = {
@ -167,20 +166,12 @@ var Page = (function PageClosure() {
IRQueue, fonts) {
var self = this;
this.IRQueue = IRQueue;
var gfx = new CanvasGraphics(this.ctx, this.objs, this.textLayer);
var displayContinuation = function pageDisplayContinuation() {
// Always defer call to display() to work around bug in
// Firefox error reporting from XHR callbacks.
setTimeout(function pageSetTimeout() {
try {
self.display(gfx, self.callback);
} catch (e) {
if (self.callback)
self.callback(e);
else
throw e;
}
self.displayReadyPromise.resolve();
});
};
@ -206,8 +197,12 @@ var Page = (function PageClosure() {
for (i = 0; i < n; ++i)
streams.push(xref.fetchIfRef(content[i]));
content = new StreamsSequenceStream(streams);
} else if (isStream(content))
} else if (isStream(content)) {
content.reset();
} else if (!content) {
// replacing non-existent page content with empty one
content = new Stream(new Uint8Array(0));
}
var pe = this.pe = new PartialEvaluator(
xref, handler, 'p' + this.pageNumber + '_');
@ -429,12 +424,35 @@ var Page = (function PageClosure() {
return items;
},
startRendering: function pageStartRendering(ctx, callback, textLayer) {
this.ctx = ctx;
this.callback = callback;
this.textLayer = textLayer;
this.startRenderingTime = Date.now();
this.pdf.startRendering(this);
// If there is no displayReadyPromise yet, then the IRQueue was never
// requested before. Make the request and create the promise.
if (!this.displayReadyPromise) {
this.pdf.startRendering(this);
this.displayReadyPromise = new Promise();
}
// Once the IRQueue and fonts are loaded, perform the actual rendering.
this.displayReadyPromise.then(
function pageDisplayReadyPromise() {
var gfx = new CanvasGraphics(ctx, this.objs, textLayer);
try {
this.display(gfx, callback);
} catch (e) {
if (callback)
callback(e);
else
throw e;
}
}.bind(this),
function pageDisplayReadPromiseError(reason) {
if (callback)
callback(reason);
else
throw reason;
}
);
}
};
@ -557,13 +575,15 @@ var PDFDocModel = (function PDFDocModelClosure() {
},
setup: function pdfDocSetup(ownerPassword, userPassword) {
this.checkHeader();
this.xref = new XRef(this.stream,
this.startXRef,
this.mainXRefEntriesOffset);
this.catalog = new Catalog(this.xref);
if (this.xref.trailer && this.xref.trailer.has('ID')) {
var xref = new XRef(this.stream,
this.startXRef,
this.mainXRefEntriesOffset);
this.xref = xref;
this.catalog = new Catalog(xref);
if (xref.trailer && xref.trailer.has('ID')) {
var fileID = '';
this.xref.trailer.get('ID')[0].split('').forEach(function(el) {
var id = xref.fetchIfRef(xref.trailer.get('ID'))[0];
id.split('').forEach(function(el) {
fileID += Number(el.charCodeAt(0)).toString(16);
});
this.fileID = fileID;
@ -642,8 +662,7 @@ var PDFDoc = (function PDFDocClosure() {
var worker = new Worker(workerSrc);
var messageHandler = new MessageHandler('main', worker);
// Tell the worker the file it was created from.
messageHandler.send('workerSrc', workerSrc);
messageHandler.on('test', function pdfDocTest(supportTypedArray) {
if (supportTypedArray) {
this.worker = worker;
@ -748,8 +767,8 @@ var PDFDoc = (function PDFDocClosure() {
messageHandler.on('page_error', function pdfDocError(data) {
var page = this.pageCache[data.pageNum];
if (page.callback)
page.callback(data.error);
if (page.displayReadyPromise)
page.displayReadyPromise.reject(data.error);
else
throw data.error;
}, this);

View File

@ -118,7 +118,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
var self = this;
var xref = this.xref;
var handler = this.handler;
var uniquePrefix = this.uniquePrefix;
var uniquePrefix = this.uniquePrefix || '';
function insertDependency(depList) {
fnArray.push('dependency');
@ -211,7 +211,8 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
args = [objId, w, h];
var softMask = dict.get('SMask', 'IM') || false;
if (!softMask && image instanceof JpegStream && image.isNative) {
if (!softMask && image instanceof JpegStream &&
image.isNativelySupported(xref, resources)) {
// These JPEGs don't need any more processing so we can just send it.
fn = 'paintJpegXObject';
handler.send('obj', [objId, 'JpegStream', image.getIR()]);
@ -234,7 +235,6 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
}, handler, xref, resources, image, inline);
}
uniquePrefix = uniquePrefix || '';
if (!queue.argsArray) {
queue.argsArray = [];
}
@ -292,8 +292,8 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
// Create an IR of the pattern code.
var depIdx = dependencyArray.length;
var queueObj = {};
var codeIR = this.getIRQueue(pattern, dict.get('Resources'),
queueObj, dependencyArray);
var codeIR = this.getIRQueue(pattern, dict.get('Resources') ||
resources, queueObj, dependencyArray);
// Add the dependencies that are required to execute the
// codeIR.
@ -336,8 +336,8 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
// This adds the IRQueue of the xObj to the current queue.
var depIdx = dependencyArray.length;
this.getIRQueue(xobj, xobj.dict.get('Resources'), queue,
dependencyArray);
this.getIRQueue(xobj, xobj.dict.get('Resources') || resources,
queue, dependencyArray);
// Add the dependencies that are required to execute the
// codeIR.
@ -823,10 +823,17 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
baseFontName = baseFontName.name.replace(/[,_]/g, '-');
var metrics = this.getBaseFontMetrics(baseFontName);
// Simulating descriptor flags attribute
var fontNameWoStyle = baseFontName.split('-')[0];
var flags = (serifFonts[fontNameWoStyle] ||
(fontNameWoStyle.search(/serif/gi) != -1) ? 2 : 0) |
(symbolsFonts[fontNameWoStyle] ? 4 : 32);
var properties = {
type: type.name,
widths: metrics.widths,
defaultWidth: metrics.defaultWidth,
flags: flags,
firstChar: 0,
lastChar: maxCharIndex
};

View File

@ -339,6 +339,21 @@ var stdFontMap = {
'TimesNewRomanPSMT-Italic': 'Times-Italic'
};
/**
* Holds the map of the non-standard fonts that might be included as a standard
* fonts without glyph data.
*/
var nonStdFontMap = {
'ComicSansMS': 'Comic Sans MS',
'ComicSansMS-Bold': 'Comic Sans MS-Bold',
'ComicSansMS-BoldItalic': 'Comic Sans MS-BoldItalic',
'ComicSansMS-Italic': 'Comic Sans MS-Italic',
'LucidaConsole': 'Courier',
'LucidaConsole-Bold': 'Courier-Bold',
'LucidaConsole-BoldItalic': 'Courier-BoldOblique',
'LucidaConsole-Italic': 'Courier-Oblique'
};
var serifFonts = {
'Adobe Jenson': true, 'Adobe Text': true, 'Albertus': true,
'Aldus': true, 'Alexandria': true, 'Algerian': true,
@ -386,6 +401,10 @@ var serifFonts = {
'Wide Latin': true, 'Windsor': true, 'XITS': true
};
var symbolsFonts = {
'Dingbats': true, 'Symbol': true, 'ZapfDingbats': true
};
var FontLoader = {
listeningForFontLoad: false,
@ -1472,7 +1491,8 @@ var Font = (function FontClosure() {
var names = name.split('+');
names = names.length > 1 ? names[1] : names[0];
names = names.split(/[-,_]/g)[0];
this.serif = serifFonts[names] || (name.search(/serif/gi) != -1);
this.isSerifFont = !!(properties.flags & 2);
this.isSymbolicFont = !!(properties.flags & 4);
var type = properties.type;
this.type = type;
@ -1480,7 +1500,7 @@ var Font = (function FontClosure() {
// If the font is to be ignored, register it like an already loaded font
// to avoid the cost of waiting for it be be loaded by the platform.
if (properties.ignore) {
this.loadedName = this.serif ? 'serif' : 'sans-serif';
this.loadedName = this.isSerifFont ? 'serif' : 'sans-serif';
this.loading = false;
return;
}
@ -1510,7 +1530,7 @@ var Font = (function FontClosure() {
// The file data is not specified. Trying to fix the font name
// to be used with the canvas.font.
var fontName = name.replace(/[,_]/g, '-');
fontName = stdFontMap[fontName] || fontName;
fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName;
this.bold = (fontName.search(/bold/gi) != -1);
this.italic = (fontName.search(/oblique/gi) != -1) ||
@ -1560,7 +1580,6 @@ var Font = (function FontClosure() {
this.widthMultiplier = !properties.fontMatrix ? 1.0 :
1.0 / properties.fontMatrix[0];
this.encoding = properties.baseEncoding;
this.hasShortCmap = properties.hasShortCmap;
this.loadedName = getUniqueName();
this.loading = true;
};
@ -2530,7 +2549,32 @@ var Font = (function FontClosure() {
this.useToUnicode = true;
}
}
properties.hasShortCmap = hasShortCmap;
if (hasShortCmap && this.hasEncoding && !this.isSymbolicFont) {
// Re-encode short map encoding to unicode -- that simplifies the
// resolution of MacRoman encoded glyphs logic for TrueType fonts:
// copying all characters to private use area, all mapping all known
// glyphs to the unicodes. The glyphs and ids arrays will grow.
var usedUnicodes = [];
for (var i = 0, ii = glyphs.length; i < ii; i++) {
var code = glyphs[i].unicode;
glyphs[i].unicode += kCmapGlyphOffset;
var glyphName = properties.baseEncoding[code];
if (glyphName in GlyphsUnicode) {
var unicode = GlyphsUnicode[glyphName];
if (unicode in usedUnicodes)
continue;
usedUnicodes[unicode] = true;
glyphs.push({
unicode: unicode,
code: glyphs[i].code
});
ids.push(ids[i]);
}
}
}
// remove glyph references outside range of avaialable glyphs
for (var i = 0, ii = ids.length; i < ii; i++) {
@ -2822,10 +2866,11 @@ var Font = (function FontClosure() {
window.btoa(data) + ');');
var rule = "@font-face { font-family:'" + fontName + "';src:" + url + '}';
document.documentElement.firstChild.appendChild(
document.createElement('style'));
var styleElement = document.createElement('style');
document.documentElement.getElementsByTagName('head')[0].appendChild(
styleElement);
var styleSheet = document.styleSheets[document.styleSheets.length - 1];
var styleSheet = styleElement.sheet;
styleSheet.insertRule(rule, styleSheet.cssRules.length);
return rule;
@ -2914,19 +2959,15 @@ var Font = (function FontClosure() {
fontChar = GlyphsUnicode[glyphName] || charcode;
break;
}
if (!this.hasEncoding) {
if (!this.hasEncoding || this.isSymbolicFont) {
fontChar = this.useToUnicode ? this.toUnicode[charcode] : charcode;
break;
}
if (this.hasShortCmap && false) {
var j = Encodings.MacRomanEncoding.indexOf(glyphName);
fontChar = j >= 0 ? j :
this.glyphNameMap[glyphName];
} else {
fontChar = glyphName in GlyphsUnicode ?
GlyphsUnicode[glyphName] :
this.glyphNameMap[glyphName];
}
// MacRoman encoding address by re-encoding the cmap table
fontChar = glyphName in GlyphsUnicode ?
GlyphsUnicode[glyphName] :
this.glyphNameMap[glyphName];
break;
default:
warn('Unsupported font type: ' + this.type);
@ -4030,15 +4071,9 @@ var Type2CFF = (function Type2CFFClosure() {
inverseEncoding[encoding[charcode]] = charcode | 0;
for (var i = 0, ii = charsets.length; i < ii; i++) {
var glyph = charsets[i];
if (glyph == '.notdef') {
charstrings.push({
unicode: 0,
code: 0,
gid: i,
glyph: glyph
});
if (glyph == '.notdef')
continue;
}
var code = inverseEncoding[i];
if (!code || isSpecialUnicode(code)) {
unassignedUnicodeItems.push(i);

View File

@ -9,7 +9,7 @@ var PDFImage = (function PDFImageClosure() {
* when the image data is ready.
*/
function handleImageData(handler, xref, res, image, promise) {
if (image instanceof JpegStream && image.isNative) {
if (image instanceof JpegStream && image.isNativelyDecodable(xref, res)) {
// For natively supported jpegs send them to the main thread for decoding.
var dict = image.dict;
var colorSpace = dict.get('ColorSpace', 'CS');

1854
src/jpx.js Normal file

File diff suppressed because it is too large Load Diff

View File

@ -120,11 +120,11 @@ var Catalog = (function CatalogClosure() {
return shadow(this, 'toplevelPagesDict', xrefObj);
},
get documentOutline() {
var obj = this.catDict.get('Outlines');
var xref = this.xref;
var obj = xref.fetchIfRef(this.catDict.get('Outlines'));
var root = { items: [] };
if (isRef(obj)) {
obj = xref.fetch(obj).get('First');
if (isDict(obj)) {
obj = obj.get('First');
var processed = new RefSet();
if (isRef(obj)) {
var queue = [{obj: obj, parent: root}];
@ -552,9 +552,7 @@ var XRef = (function XRefClosure() {
},
getEntry: function xRefGetEntry(i) {
var e = this.entries[i];
if (e.free)
error('reading an XRef stream not implemented yet');
return e;
return e.free ? null : e; // returns null is the entry is free
},
fetchIfRef: function xRefFetchIfRef(obj) {
if (!isRef(obj))
@ -563,11 +561,15 @@ var XRef = (function XRefClosure() {
},
fetch: function xRefFetch(ref, suppressEncryption) {
var num = ref.num;
var e = this.cache[num];
if (e)
return e;
if (num in this.cache)
return this.cache[num];
var e = this.getEntry(num);
// the referenced entry can be free
if (e === null)
return (this.cache[num] = e);
e = this.getEntry(num);
var gen = ref.gen;
var stream, parser;
if (e.uncompressed) {

View File

@ -240,6 +240,10 @@ var Parser = (function ParserClosure() {
var bytes = stream.getBytes(length);
return new JpegStream(bytes, stream.dict, this.xref);
}
if (name == 'JPXDecode' || name == 'JPX') {
var bytes = stream.getBytes(length);
return new JpxStream(bytes, stream.dict);
}
if (name == 'ASCII85Decode' || name == 'A85') {
return new Ascii85Stream(stream);
}
@ -249,6 +253,9 @@ var Parser = (function ParserClosure() {
if (name == 'CCITTFaxDecode' || name == 'CCF') {
return new CCITTFaxStream(stream, params);
}
if (name == 'RunLengthDecode') {
return new RunLengthStream(stream);
}
warn('filter "' + name + '" not supported yet');
return stream;
}

View File

@ -94,9 +94,9 @@ Shadings.RadialAxial = (function RadialAxialClosure() {
var colorStops = [];
for (var i = t0; i <= t1; i += step) {
var color = fn([i]);
var rgbColor = Util.makeCssRgb.apply(this, cs.getRgb(color));
colorStops.push([(i - t0) / diff, rgbColor]);
var rgbColor = cs.getRgb(fn([i]));
var cssColor = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]);
colorStops.push([(i - t0) / diff, cssColor]);
}
this.colorStops = colorStops;
@ -234,9 +234,9 @@ var TilingPattern = (function TilingPatternClosure() {
tmpCtx.strokeStyle = ctx.strokeStyle;
break;
case PaintType.UNCOLORED:
color = Util.makeCssRgb.apply(this, color);
tmpCtx.fillStyle = color;
tmpCtx.strokeStyle = color;
var cssColor = Util.makeCssRgb(this, color[0], color[1], color[2]);
tmpCtx.fillStyle = cssColor;
tmpCtx.strokeStyle = cssColor;
break;
default:
error('Unsupported paint type: ' + paintType);

View File

@ -803,29 +803,16 @@ var JpegStream = (function JpegStreamClosure() {
// need to be removed
this.dict = dict;
// Flag indicating wether the image can be natively loaded.
this.isNative = true;
this.colorTransform = -1;
this.isAdobeImage = false;
this.colorTransform = dict.get('ColorTransform') || -1;
if (isAdobeImage(bytes)) {
// when bug 674619 land, let's check if browser can do
// normal cmyk and then we won't have to the following
var cs = xref.fetchIfRef(dict.get('ColorSpace'));
// DeviceRGB and DeviceGray are the only Adobe images that work natively
if (isName(cs) && (cs.name === 'DeviceRGB' || cs.name === 'DeviceGray')) {
bytes = fixAdobeImage(bytes);
this.src = bytesToString(bytes);
} else {
this.colorTransform = dict.get('ColorTransform');
this.isNative = false;
this.bytes = bytes;
}
} else {
this.src = bytesToString(bytes);
this.isAdobeImage = true;
bytes = fixAdobeImage(bytes);
}
this.bytes = bytes;
DecodeStream.call(this);
}
@ -835,7 +822,8 @@ var JpegStream = (function JpegStreamClosure() {
if (this.bufferLength)
return;
var jpegImage = new JpegImage();
jpegImage.colorTransform = this.colorTransform;
if (this.colorTransform != -1)
jpegImage.colorTransform = this.colorTransform;
jpegImage.parse(this.bytes);
var width = jpegImage.width;
var height = jpegImage.height;
@ -844,15 +832,144 @@ var JpegStream = (function JpegStreamClosure() {
this.bufferLength = data.length;
};
JpegStream.prototype.getIR = function jpegStreamGetIR() {
return this.src;
return bytesToString(this.bytes);
};
JpegStream.prototype.getChar = function jpegStreamGetChar() {
error('internal error: getChar is not valid on JpegStream');
error('internal error: getChar is not valid on JpegStream');
};
/**
* Checks if the image can be decoded and displayed by the browser without any
* further processing such as color space conversions.
*/
JpegStream.prototype.isNativelySupported = function isNativelySupported(xref,
res) {
var cs = ColorSpace.parse(this.dict.get('ColorSpace'), xref, res);
// when bug 674619 lands, let's check if browser can do
// normal cmyk and then we won't need to decode in JS
if (cs.name === 'DeviceGray' || cs.name === 'DeviceRGB')
return true;
if (cs.name === 'DeviceCMYK' && !this.isAdobeImage &&
this.colorTransform < 1)
return true;
return false;
};
/**
* Checks if the image can be decoded by the browser.
*/
JpegStream.prototype.isNativelyDecodable = function isNativelyDecodable(xref,
res) {
var cs = ColorSpace.parse(this.dict.get('ColorSpace'), xref, res);
var numComps = cs.numComps;
if (numComps == 1 || numComps == 3)
return true;
return false;
};
return JpegStream;
})();
/**
* For JPEG 2000's we use a library to decode these images and
* the stream behaves like all the other DecodeStreams.
*/
var JpxStream = (function JpxStreamClosure() {
function JpxStream(bytes, dict) {
this.dict = dict;
this.bytes = bytes;
DecodeStream.call(this);
}
JpxStream.prototype = Object.create(DecodeStream.prototype);
JpxStream.prototype.ensureBuffer = function jpxStreamEnsureBuffer(req) {
if (this.bufferLength)
return;
var jpxImage = new JpxImage();
jpxImage.parse(this.bytes);
var width = jpxImage.width;
var height = jpxImage.height;
var componentsCount = jpxImage.componentsCount;
if (componentsCount != 1 && componentsCount != 3 && componentsCount != 4)
error('JPX with ' + componentsCount + ' components is not supported');
var data = new Uint8Array(width * height * componentsCount);
for (var k = 0, kk = jpxImage.tiles.length; k < kk; k++) {
var tileCompoments = jpxImage.tiles[k];
var tileWidth = tileCompoments[0].width;
var tileHeight = tileCompoments[0].height;
var tileLeft = tileCompoments[0].left;
var tileTop = tileCompoments[0].top;
var dataPosition, sourcePosition, data0, data1, data2, data3, rowFeed;
switch (componentsCount) {
case 1:
data0 = tileCompoments[0].items;
dataPosition = width * tileTop + tileLeft;
rowFeed = width - tileWidth;
sourcePosition = 0;
for (var j = 0; j < tileHeight; j++) {
for (var i = 0; i < tileWidth; i++)
data[dataPosition++] = data0[sourcePosition++];
dataPosition += rowFeed;
}
break;
case 3:
data0 = tileCompoments[0].items;
data1 = tileCompoments[1].items;
data2 = tileCompoments[2].items;
dataPosition = (width * tileTop + tileLeft) * 3;
rowFeed = (width - tileWidth) * 3;
sourcePosition = 0;
for (var j = 0; j < tileHeight; j++) {
for (var i = 0; i < tileWidth; i++) {
data[dataPosition++] = data0[sourcePosition];
data[dataPosition++] = data1[sourcePosition];
data[dataPosition++] = data2[sourcePosition];
sourcePosition++;
}
dataPosition += rowFeed;
}
break;
case 4:
data0 = tileCompoments[0].items;
data1 = tileCompoments[1].items;
data2 = tileCompoments[2].items;
data3 = tileCompoments[3].items;
dataPosition = (width * tileTop + tileLeft) * 4;
rowFeed = (width - tileWidth) * 4;
sourcePosition = 0;
for (var j = 0; j < tileHeight; j++) {
for (var i = 0; i < tileWidth; i++) {
data[dataPosition++] = data0[sourcePosition];
data[dataPosition++] = data1[sourcePosition];
data[dataPosition++] = data2[sourcePosition];
data[dataPosition++] = data3[sourcePosition];
sourcePosition++;
}
dataPosition += rowFeed;
}
break;
}
}
this.buffer = data;
this.bufferLength = data.length;
};
JpxStream.prototype.getChar = function jpxStreamGetChar() {
error('internal error: getChar is not valid on JpxStream');
};
return JpxStream;
})();
var DecryptStream = (function DecryptStreamClosure() {
function DecryptStream(str, decrypt) {
this.str = str;
@ -1025,6 +1142,51 @@ var AsciiHexStream = (function AsciiHexStreamClosure() {
return AsciiHexStream;
})();
var RunLengthStream = (function RunLengthStreamClosure() {
function RunLengthStream(str) {
this.str = str;
this.dict = str.dict;
DecodeStream.call(this);
}
RunLengthStream.prototype = Object.create(DecodeStream.prototype);
RunLengthStream.prototype.readBlock = function runLengthStreamReadBlock() {
// The repeatHeader has following format. The first byte defines type of run
// and amount of bytes to repeat/copy: n = 0 through 127 - copy next n bytes
// (in addition to the second byte from the header), n = 129 through 255 -
// duplicate the second byte from the header (257 - n) times, n = 128 - end.
var repeatHeader = this.str.getBytes(2);
if (!repeatHeader || repeatHeader.length < 2 || repeatHeader[0] == 128) {
this.eof = true;
return;
}
var bufferLength = this.bufferLength;
var n = repeatHeader[0];
if (n < 128) {
// copy n bytes
var buffer = this.ensureBuffer(bufferLength + n + 1);
buffer[bufferLength++] = repeatHeader[1];
if (n > 0) {
var source = this.str.getBytes(n);
buffer.set(source, bufferLength);
bufferLength += n;
}
} else {
n = 257 - n;
var b = repeatHeader[1];
var buffer = this.ensureBuffer(bufferLength + n + 1);
for (var i = 0; i < n; i++)
buffer[bufferLength++] = b;
}
this.bufferLength = bufferLength;
};
return RunLengthStream;
})();
var CCITTFaxStream = (function CCITTFaxStreamClosure() {
var ccittEOL = -2;
@ -1856,10 +2018,10 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {
// values. The first array element indicates whether a valid code is being
// returned. The second array element is the actual code. The third array
// element indicates whether EOF was reached.
var findTableCode = function ccittFaxStreamFindTableCode(start, end, table,
limit) {
var limitValue = limit || 0;
CCITTFaxStream.prototype.findTableCode =
function ccittFaxStreamFindTableCode(start, end, table, limit) {
var limitValue = limit || 0;
for (var i = start; i <= end; ++i) {
var code = this.lookBits(i);
if (code == EOF)
@ -1890,7 +2052,7 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {
return p[1];
}
} else {
var result = findTableCode(1, 7, twoDimTable);
var result = this.findTableCode(1, 7, twoDimTable);
if (result[0] && result[2])
return result[1];
}
@ -1919,11 +2081,11 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {
return p[1];
}
} else {
var result = findTableCode(1, 9, whiteTable2);
var result = this.findTableCode(1, 9, whiteTable2);
if (result[0])
return result[1];
result = findTableCode(11, 12, whiteTable1);
result = this.findTableCode(11, 12, whiteTable1);
if (result[0])
return result[1];
}
@ -1952,15 +2114,15 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {
return p[1];
}
} else {
var result = findTableCode(2, 6, blackTable3);
var result = this.findTableCode(2, 6, blackTable3);
if (result[0])
return result[1];
result = findTableCode(7, 12, blackTable2, 64);
result = this.findTableCode(7, 12, blackTable2, 64);
if (result[0])
return result[1];
result = findTableCode(10, 13, blackTable1);
result = this.findTableCode(10, 13, blackTable1);
if (result[0])
return result[1];
}

View File

@ -206,6 +206,8 @@ var Promise = (function PromiseClosure() {
*/
function Promise(name, data) {
this.name = name;
this.isRejected = false;
this.error = null;
// If you build a promise and pass in some data it's already resolved.
if (data != null) {
this.isResolved = true;
@ -216,6 +218,7 @@ var Promise = (function PromiseClosure() {
this._data = EMPTY_PROMISE;
}
this.callbacks = [];
this.errbacks = [];
};
/**
* Builds a promise that is resolved when all the passed in promises are
@ -282,9 +285,12 @@ var Promise = (function PromiseClosure() {
if (this.isResolved) {
throw 'A Promise can be resolved only once ' + this.name;
}
if (this.isRejected) {
throw 'The Promise was already rejected ' + this.name;
}
this.isResolved = true;
this.data = data;
this.data = data || null;
var callbacks = this.callbacks;
for (var i = 0, ii = callbacks.length; i < ii; i++) {
@ -292,7 +298,24 @@ var Promise = (function PromiseClosure() {
}
},
then: function promiseThen(callback) {
reject: function proimseReject(reason) {
if (this.isRejected) {
throw 'A Promise can be rejected only once ' + this.name;
}
if (this.isResolved) {
throw 'The Promise was already resolved ' + this.name;
}
this.isRejected = true;
this.error = reason || null;
var errbacks = this.errbacks;
for (var i = 0, ii = errbacks.length; i < ii; i++) {
errbacks[i].call(null, reason);
}
},
then: function promiseThen(callback, errback) {
if (!callback) {
throw 'Requiring callback' + this.name;
}
@ -301,8 +324,13 @@ var Promise = (function PromiseClosure() {
if (this.isResolved) {
var data = this.data;
callback.call(null, data);
} else if (this.isRejected && errorback) {
var error = this.error;
errback.call(null, error);
} else {
this.callbacks.push(callback);
if (errback)
this.errbacks.push(errback);
}
}
};

View File

@ -85,13 +85,6 @@ var WorkerMessageHandler = {
handler.send('test', data instanceof Uint8Array);
});
handler.on('workerSrc', function wphSetupWorkerSrc(data) {
// In development, the `workerSrc` message is handled in the
// `worker_loader.js` file. In production the workerProcessHandler is
// called for this. This servers as a dummy to prevent calling an
// undefined action `workerSrc`.
});
handler.on('doc', function wphSetupDoc(data) {
// Create only the model of the PDFDoc, which is enough for
// processing the content of the pdf.

View File

@ -3,51 +3,31 @@
'use strict';
function onMessageLoader(evt) {
// Reset the `onmessage` function as it was only set to call
// this function the first time a message is passed to the worker
// but shouldn't get called anytime afterwards.
this.onmessage = null;
// List of files to include;
var files = [
'core.js',
'util.js',
'canvas.js',
'obj.js',
'function.js',
'charsets.js',
'cidmaps.js',
'colorspace.js',
'crypto.js',
'evaluator.js',
'fonts.js',
'glyphlist.js',
'image.js',
'metrics.js',
'parser.js',
'pattern.js',
'stream.js',
'worker.js',
'../external/jpgjs/jpg.js',
'jpx.js'
];
if (evt.data.action !== 'workerSrc') {
throw 'Worker expects first message to be `workerSrc`';
}
// Content of `PDFJS.workerSrc` as defined on the main thread.
var workerSrc = evt.data.data;
// Extract the directory that contains the source files to load.
// Assuming the source files have the same relative possition as the
// `workerSrc` file.
var dir = workerSrc.substring(0, workerSrc.lastIndexOf('/') + 1);
// List of files to include;
var files = [
'core.js',
'util.js',
'canvas.js',
'obj.js',
'function.js',
'charsets.js',
'cidmaps.js',
'colorspace.js',
'crypto.js',
'evaluator.js',
'fonts.js',
'glyphlist.js',
'image.js',
'metrics.js',
'parser.js',
'pattern.js',
'stream.js',
'worker.js',
'../external/jpgjs/jpg.js'
];
// Load all the files.
for (var i = 0; i < files.length; i++) {
importScripts(dir + files[i]);
}
// Load all the files.
for (var i = 0; i < files.length; i++) {
importScripts(files[i]);
}
this.onmessage = onMessageLoader;

3
test/.gitignore vendored
View File

@ -0,0 +1,3 @@
ref/
tmp/

View File

@ -78,6 +78,14 @@ function cleanup() {
}
}
function exceptionToString(e) {
if (typeof e !== 'object')
return String(e);
if (!('message' in e))
return JSON.stringify(e);
return e.message + ('stack' in e ? ' at ' + e.stack.split('\n')[0] : '');
}
function nextTask() {
cleanup();
@ -95,7 +103,7 @@ function nextTask() {
try {
task.pdfDoc = new PDFJS.PDFDoc(data);
} catch (e) {
failure = 'load PDF doc : ' + e.toString();
failure = 'load PDF doc : ' + exceptionToString(e);
}
task.pageNum = task.firstPage || 1;
nextPage(task, failure);
@ -165,9 +173,14 @@ function nextPage(task, loadError) {
canvas.height = pageHeight * pdfToCssUnitsCoef;
clear(ctx);
// using non-attached to the document div to test
// using the text layer builder that does nothing to test
// text layer creation operations
var textLayer = document.createElement('div');
var textLayerBuilder = {
beginLayout: function nullTextLayerBuilderBeginLayout() {},
endLayout: function nullTextLayerBuilderEndLayout() {},
appendText: function nullTextLayerBuilderAppendText(text, fontName,
fontSize) {}
};
page.startRendering(
ctx,
@ -177,10 +190,10 @@ function nextPage(task, loadError) {
failureMessage = 'render : ' + error.message;
snapshotCurrentPage(task, failureMessage);
},
textLayer
textLayerBuilder
);
} catch (e) {
failure = 'page setup : ' + e.toString();
failure = 'page setup : ' + exceptionToString(e);
}
}

View File

@ -22,3 +22,5 @@
!issue918.pdf
!smaskdim.pdf
!type4psfunc.pdf
!S2.pdf
!zerowidthline.pdf

2549
test/pdfs/S2.pdf Normal file

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
http://www.intel.com/content/dam/doc/manual/64-ia-32-architectures-software-developer-vol-1-manual.pdf
http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-vol-1-manual.pdf

View File

@ -0,0 +1 @@
http://francois.laustriat.free.fr/test/caravan-d.pdf

View File

@ -0,0 +1 @@
http://faculty.washington.edu/fidelr/RayaPubs/TheCaseStudyMethod.pdf

View File

@ -0,0 +1 @@
http://mcpherrin.ca/code/mozilla/engl208b.pdf

View File

@ -0,0 +1 @@
http://blog.lassus.se/files/liveprogramming.pdf

1
test/pdfs/ocs.pdf.link Normal file
View File

@ -0,0 +1 @@
http://www.unibuc.ro/uploads_en/29535/10/Cyrillic_Alphabets-Chars.pdf

BIN
test/pdfs/zerowidthline.pdf Normal file

Binary file not shown.

View File

@ -0,0 +1 @@
user_pref("browser.shell.checkDefaultBrowser", false);

View File

@ -9,7 +9,7 @@ USAGE_EXAMPLE = "%prog"
# The local web server uses the git repo as the document root.
DOC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__),".."))
ANAL = True
GIT_CLONE_CHECK = True
DEFAULT_MANIFEST_FILE = 'test_manifest.json'
EQLOG_FILE = 'eq.log'
BROWSERLOG_FILE = 'browser.log'
@ -344,7 +344,7 @@ def verifyPDFs(manifestList):
def setUp(options):
# Only serve files from a pdf.js clone
assert not ANAL or os.path.isfile('../src/pdf.js') and os.path.isdir('../.git')
assert not GIT_CLONE_CHECK or os.path.isfile('../src/pdf.js') and os.path.isdir('../.git')
if options.masterMode and os.path.isdir(TMPDIR):
print 'Temporary snapshot dir tmp/ is still around.'

View File

@ -19,7 +19,7 @@
},
{ "id": "intelisa-eq",
"file": "pdfs/intelisa.pdf",
"md5": "f5712097d29287a97f1278839814f682",
"md5": "83032ccbfdc5a66269b1403971110abe",
"link": true,
"pageLimit": 100,
"rounds": 1,
@ -176,7 +176,6 @@
"md5": "eb7b224107205db4fea9f7df0185f77d",
"link": true,
"rounds": 1,
"skipPages": [12,31],
"type": "eq"
},
{ "id": "fips197",
@ -381,5 +380,54 @@
"md5": "7e6027a02ff78577f74dccdf84e37189",
"rounds": 1,
"type": "eq"
},
{ "id": "ocs",
"file": "pdfs/ocs.pdf",
"md5": "2ade57e954ae7632749cf328daeaa7a8",
"rounds": 1,
"link": true,
"type": "load"
},
{ "id": "issue1010",
"file": "pdfs/issue1010.pdf",
"md5": "f991ef093484a107fe9f59dff18fc155",
"rounds": 1,
"link": true,
"type": "eq"
},
{ "id": "issue1015",
"file": "pdfs/issue1015.pdf",
"md5": "b61503d1b445742b665212866afb60e2",
"rounds": 1,
"link": true,
"type": "eq"
},
{ "id": "liveprogramming",
"file": "pdfs/liveprogramming.pdf",
"md5": "7bd4dad1188232ef597d36fd72c33e52",
"rounds": 1,
"pageLimit": 3,
"link": true,
"type": "load"
},
{ "id": "S2-eq",
"file": "pdfs/S2.pdf",
"md5": "d0b6137846df6e0fe058f234a87fb588",
"rounds": 1,
"type": "eq"
},
{ "id": "issue1055",
"file": "pdfs/issue1055.pdf",
"md5": "3ba56c2e48dce81da8669b1b9cf98ff0",
"rounds": 1,
"link": true,
"type": "eq"
},
{ "id": "zerowidthline",
"file": "pdfs/zerowidthline.pdf",
"md5": "295d26e61a85635433f8e4b768953f60",
"rounds": 1,
"link": false,
"type": "eq"
}
]

View File

@ -22,6 +22,7 @@
<script type="text/javascript" src="/src/stream.js"></script>
<script type="text/javascript" src="/src/worker.js"></script>
<script type="text/javascript" src="/external/jpgjs/jpg.js"></script>
<script type="text/javascript" src="/src/jpx.js"></script>
<script type="text/javascript" src="driver.js"></script>
<script type="text/javascript">

116
test/unit/Makefile Normal file
View File

@ -0,0 +1,116 @@
# Create temporary profile directory name.
TEMP_PROFILE:=$(shell echo `pwd`)/test_reports/temp_profile
# These are the Firefox command line arguments.
FIREFOX_ARGS:=-no-remote -profile $(TEMP_PROFILE)
# These are the Chrome command line arguments.
CHROME_ARGS:=--user-data-dir=$(TEMP_PROFILE) --no-first-run --disable-sync
# Unit test uses the manifest from ref test to determine which browsers will
# be used for running the unit tests.
MANIFEST:=../resources/browser_manifests/browser_manifest.json
# This is a helper command to separate multiple browsers to their own lines
# for an easier sed operation.
SPLIT_LINES:=sed 's|,|,@|g' | tr '@' '\n'
# This is a helper command to join multiple lines together.
JOIN_LINES:=tr -d '\n'
# Fetch the paths to browsers that are going to be used in testing.
# For OS X the path to the binary needs to be added.
# Add the browser arguments for each browser.
# Create random profile directory for each browser.
BROWSERS_PATHS:=$(shell echo `\
sed -n 's|.*"path":\(.*\)|\1,|p' $(MANIFEST) | \
$(JOIN_LINES) \
`)
# The browser_manifest.json file has only the app directory for mac browsers.
# The absolute path to the browser binary needs to be used.
BROWSERS_PATHS_WITH_MAC_CORRECTION:=$(shell echo '$(BROWSERS_PATHS)' | \
$(SPLIT_LINES) | \
sed 's|\(Aurora\.app\)|\1/Contents/MacOS/firefox-bin|' | \
sed 's|\(Firefox.*\.app\)|\1/Contents/MacOS/firefox-bin|' | \
sed 's|\(Google Chrome\.app\)|\1/Contents/MacOS/Google Chrome|' | \
$(JOIN_LINES) \
)
# Replace " with @@@@ so that echoing do not destroy the quotation marks.
QUOTATION_MARK:=\"
SUBSTITUTE_FOR_QUOTATION_MARK:=@@@@
# Each of the browser can have their own separate arguments.
BROWSERS_WITH_ARGUMENTS:=$(shell echo '$(BROWSERS_PATHS_WITH_MAC_CORRECTION)' | \
$(SPLIT_LINES) | \
sed "s|\(irefox.*\)\($(QUOTATION_MARK)\),|\1;$(FIREFOX_ARGS)\2,|" | \
sed "s|\(hrome.*\)\($(QUOTATION_MARK)\),|\1;$(CHROME_ARGS)\2,|" | \
$(JOIN_LINES) \
)
# A temporary profile directory is needed for each of the browser. In this way
# a unit test run will not disturb the main browsing session of the user. The
# $RANDOM shell variable is used to generate non-conflicting temporary
# directories.
BROWSERS_WITH_UKNOWN_RANDOM_PROFILE_PATHS:=$(shell echo '$(BROWSERS_WITH_ARGUMENTS)' | \
$(SPLIT_LINES) | \
sed 's|\(temp_profile\)|\1_$$RANDOM$$RANDOM|' | \
sed "s|$(QUOTATION_MARK)|$(SUBSTITUTE_FOR_QUOTATION_MARK)|g" | \
$(JOIN_LINES) \
)
# Echo the variable so that the unknown random directories become known.
# Replace @@@@ with " so that jsTestDriver will work properly.
BROWSERS:=$(shell echo "$(BROWSERS_WITH_UKNOWN_RANDOM_PROFILE_PATHS)" | \
sed "s|$(SUBSTITUTE_FOR_QUOTATION_MARK)|$(QUOTATION_MARK)|g" \
)
# Get the known random directories for browsers. This information will be used
# to create the profile directories beforehand. Create also the dummy temp
# profile directory so that the mkdir command would not fail for browsers that
# do not need it.
PROFILES:=$(TEMP_PROFILE) $(shell echo '$(BROWSERS)' | \
$(SPLIT_LINES) | \
sed -n "s|.*\( $(TEMP_PROFILE)_[0-9]\+\).*|\1|p" | \
$(JOIN_LINES) \
)
# This is the command to invoke the unit test.
PROG:=java \
-Xms512m \
-Xmx1024m \
-jar ../../external/jsTestDriver/JsTestDriver-1.3.3d.jar \
--config ./jsTestDriver.conf \
--reset \
--port 4224 \
--browser $(BROWSERS) \
--tests all \
--testOutput ./test_reports/
# This default rule runs the unit tests with the constructed command.
test:
@mkdir -p $(PROFILES)
$(PROG)
@rm -rf $(PROFILES)
# In case this Makefile needs to be debugged then this rule will provide all
# the information from intermediate steps.
debug:
@echo 'Debug browsers paths: $(BROWSERS_PATHS)'
@echo
@echo 'Debug browsers paths with mac correction: $(BROWSERS_PATHS_WITH_MAC_CORRECTION)'
@echo
@echo 'Debug browsers with arguments: $(BROWSERS_WITH_ARGUMENTS)'
@echo
@echo 'Debug browsers random profile paths: $(BROWSERS_WITH_UKNOWN_RANDOM_PROFILE_PATHS)'
@echo
@echo 'Debug browsers: $(BROWSERS)'
@echo
@echo 'Debug profiles: $(PROFILES)'
@echo
@echo 'Command to be run: $(PROG)'
@echo
.phony:: test

187
test/unit/crypto_spec.js Normal file
View File

@ -0,0 +1,187 @@
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
'use strict';
describe('crypto', function() {
function string2binary(s) {
var n = s.length, i;
var result = new Uint8Array(n);
for (i = 0; i < n; ++i)
result[i] = s.charCodeAt(i) % 0xFF;
return result;
}
function hex2binary(s) {
var digits = '0123456789ABCDEF';
s = s.toUpperCase();
var n = s.length >> 1, i, j;
var result = new Uint8Array(n);
for (i = 0, j = 0; i < n; ++i) {
var d1 = s.charAt(j++);
var d2 = s.charAt(j++);
var value = (digits.indexOf(d1) << 4) | (digits.indexOf(d2));
result[i] = value;
}
return result;
}
// RFC 1321, A.5 Test suite
describe('calculateMD5', function() {
it('should pass RFC 1321 test #1', function() {
var input, result, expected;
input = string2binary('');
result = calculateMD5(input, 0, input.length);
expected = hex2binary('d41d8cd98f00b204e9800998ecf8427e');
expect(result).toEqual(expected);
});
it('should pass RFC 1321 test #2', function() {
var input, result, expected;
input = string2binary('a');
result = calculateMD5(input, 0, input.length);
expected = hex2binary('0cc175b9c0f1b6a831c399e269772661');
expect(result).toEqual(expected);
});
it('should pass RFC 1321 test #3', function() {
var input, result, expected;
input = string2binary('abc');
result = calculateMD5(input, 0, input.length);
expected = hex2binary('900150983cd24fb0d6963f7d28e17f72');
expect(result).toEqual(expected);
});
it('should pass RFC 1321 test #4', function() {
var input, result, expected;
input = string2binary('message digest');
result = calculateMD5(input, 0, input.length);
expected = hex2binary('f96b697d7cb7938d525a2f31aaf161d0');
expect(result).toEqual(expected);
});
it('should pass RFC 1321 test #5', function() {
var input, result, expected;
input = string2binary('abcdefghijklmnopqrstuvwxyz');
result = calculateMD5(input, 0, input.length);
expected = hex2binary('c3fcd3d76192e4007dfb496cca67e13b');
expect(result).toEqual(expected);
});
it('should pass RFC 1321 test #6', function() {
var input, result, expected;
input = string2binary('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv' +
'wxyz0123456789');
result = calculateMD5(input, 0, input.length);
expected = hex2binary('d174ab98d277d9f5a5611c2c9f419d9f');
expect(result).toEqual(expected);
});
it('should pass RFC 1321 test #7', function() {
var input, result, expected;
input = string2binary('123456789012345678901234567890123456789012345678' +
'90123456789012345678901234567890');
result = calculateMD5(input, 0, input.length);
expected = hex2binary('57edf4a22be3c955ac49da2e2107b67a');
expect(result).toEqual(expected);
});
});
// http://www.freemedialibrary.com/index.php/RC4_test_vectors are used
describe('ARCFourCipher', function() {
it('should pass test #1', function() {
var key, input, result, expected, cipher;
key = hex2binary('0123456789abcdef');
input = hex2binary('0123456789abcdef');
cipher = new ARCFourCipher(key);
result = cipher.encryptBlock(input);
expected = hex2binary('75b7878099e0c596');
expect(result).toEqual(expected);
});
it('should pass test #2', function() {
var key, input, result, expected, cipher;
key = hex2binary('0123456789abcdef');
input = hex2binary('0000000000000000');
cipher = new ARCFourCipher(key);
result = cipher.encryptBlock(input);
expected = hex2binary('7494c2e7104b0879');
expect(result).toEqual(expected);
});
it('should pass test #3', function() {
var key, input, result, expected, cipher;
key = hex2binary('0000000000000000');
input = hex2binary('0000000000000000');
cipher = new ARCFourCipher(key);
result = cipher.encryptBlock(input);
expected = hex2binary('de188941a3375d3a');
expect(result).toEqual(expected);
});
it('should pass test #4', function() {
var key, input, result, expected, cipher;
key = hex2binary('ef012345');
input = hex2binary('00000000000000000000');
cipher = new ARCFourCipher(key);
result = cipher.encryptBlock(input);
expected = hex2binary('d6a141a7ec3c38dfbd61');
expect(result).toEqual(expected);
});
it('should pass test #5', function() {
var key, input, result, expected, cipher;
key = hex2binary('0123456789abcdef');
input = hex2binary('010101010101010101010101010101010101010101010101010' +
'10101010101010101010101010101010101010101010101010101010101010101010' +
'10101010101010101010101010101010101010101010101010101010101010101010' +
'10101010101010101010101010101010101010101010101010101010101010101010' +
'10101010101010101010101010101010101010101010101010101010101010101010' +
'10101010101010101010101010101010101010101010101010101010101010101010' +
'10101010101010101010101010101010101010101010101010101010101010101010' +
'10101010101010101010101010101010101010101010101010101010101010101010' +
'10101010101010101010101010101010101010101010101010101010101010101010' +
'10101010101010101010101010101010101010101010101010101010101010101010' +
'10101010101010101010101010101010101010101010101010101010101010101010' +
'10101010101010101010101010101010101010101010101010101010101010101010' +
'10101010101010101010101010101010101010101010101010101010101010101010' +
'10101010101010101010101010101010101010101010101010101010101010101010' +
'10101010101010101010101010101010101010101010101010101010101010101010' +
'101010101010101010101');
cipher = new ARCFourCipher(key);
result = cipher.encryptBlock(input);
expected = hex2binary('7595c3e6114a09780c4ad452338e1ffd9a1be9498f813d76' +
'533449b6778dcad8c78a8d2ba9ac66085d0e53d59c26c2d1c490c1ebbe0ce66d1b6b' +
'1b13b6b919b847c25a91447a95e75e4ef16779cde8bf0a95850e32af9689444fd377' +
'108f98fdcbd4e726567500990bcc7e0ca3c4aaa304a387d20f3b8fbbcd42a1bd311d' +
'7a4303dda5ab078896ae80c18b0af66dff319616eb784e495ad2ce90d7f772a81747' +
'b65f62093b1e0db9e5ba532fafec47508323e671327df9444432cb7367cec82f5d44' +
'c0d00b67d650a075cd4b70dedd77eb9b10231b6b5b741347396d62897421d43df9b4' +
'2e446e358e9c11a9b2184ecbef0cd8e7a877ef968f1390ec9b3d35a5585cb009290e' +
'2fcde7b5ec66d9084be44055a619d9dd7fc3166f9487f7cb272912426445998514c1' +
'5d53a18c864ce3a2b7555793988126520eacf2e3066e230c91bee4dd5304f5fd0405' +
'b35bd99c73135d3d9bc335ee049ef69b3867bf2d7bd1eaa595d8bfc0066ff8d31509' +
'eb0c6caa006c807a623ef84c3d33c195d23ee320c40de0558157c822d4b8c569d849' +
'aed59d4e0fd7f379586b4b7ff684ed6a189f7486d49b9c4bad9ba24b96abf924372c' +
'8a8fffb10d55354900a77a3db5f205e1b99fcd8660863a159ad4abe40fa48934163d' +
'dde542a6585540fd683cbfd8c00f12129a284deacc4cdefe58be7137541c047126c8' +
'd49e2755ab181ab7e940b0c0');
expect(result).toEqual(expected);
});
it('should pass test #6', function() {
var key, input, result, expected, cipher;
key = hex2binary('fb029e3031323334');
input = hex2binary('aaaa0300000008004500004e661a00008011be640a0001220af' +
'fffff00890089003a000080a601100001000000000000204543454a4548454346434' +
'550464545494546464343414341434143414341414100002000011bd0b604');
cipher = new ARCFourCipher(key);
result = cipher.encryptBlock(input);
expected = hex2binary('f69c5806bd6ce84626bcbefb9474650aad1f7909b0f64d5f' +
'58a503a258b7ed22eb0ea64930d3a056a55742fcce141d485f8aa836dea18df42c53' +
'80805ad0c61a5d6f58f41040b24b7d1a693856ed0d4398e7aee3bf0e2a2ca8f7');
expect(result).toEqual(expected);
});
it('should pass test #7', function() {
var key, input, result, expected, cipher;
key = hex2binary('0123456789abcdef');
input = hex2binary('123456789abcdef0123456789abcdef0123456789abcdef0123' +
'45678');
cipher = new ARCFourCipher(key);
result = cipher.encryptBlock(input);
expected = hex2binary('66a0949f8af7d6891f7f832ba833c00c892ebe30143ce287' +
'40011ecf');
expect(result).toEqual(expected);
});
});
});

View File

@ -0,0 +1,30 @@
server: http://localhost:4224
load:
- ../../external/jasmine/jasmine.js
- ../../external/jasmineAdapter/JasmineAdapter.js
- ../../src/obj.js
- ../../src/core.js
- ../../src/util.js
- ../../src/canvas.js
- ../../src/obj.js
- ../../src/function.js
- ../../src/charsets.js
- ../../src/cidmaps.js
- ../../src/colorspace.js
- ../../src/crypto.js
- ../../src/evaluator.js
- ../../src/fonts.js
- ../../src/glyphlist.js
- ../../src/image.js
- ../../src/metrics.js
- ../../src/parser.js
- ../../src/pattern.js
- ../../src/stream.js
- ../../src/worker.js
- ../../external/jpgjs/jpg.js
- ../unit/obj_spec.js
- ../unit/function_spec.js
- ../unit/crypto_spec.js
- ../unit/stream_spec.js

View File

@ -127,5 +127,23 @@ describe('obj', function() {
expect(ref.gen).toEqual(storedGen);
});
});
describe('RefSet', function() {
it('should have a stored value', function() {
var ref = new Ref(4, 2);
var refset = new RefSet();
refset.put(ref);
expect(refset.has(ref)).toBeTruthy();
});
it('should not have an unknown value', function() {
var ref = new Ref(4, 2);
var refset = new RefSet();
expect(refset.has(ref)).toBeFalsy();
refset.put(ref);
var anotherRef = new Ref(2, 4);
expect(refset.has(anotherRef)).toBeFalsy();
});
});
});

25
test/unit/stream_spec.js Normal file
View File

@ -0,0 +1,25 @@
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
'use strict';
describe('stream', function() {
describe('PredictorStream', function() {
it('should decode simple predictor data', function() {
var dict = new Dict();
dict.set('Predictor', 12);
dict.set('Colors', 1);
dict.set('BitsPerComponent', 8);
dict.set('Columns', 2);
var input = new Stream(new Uint8Array([2, 100, 3, 2, 1, 255, 2, 1, 255]),
0, 9, dict);
var predictor = new PredictorStream(input, dict);
var result = predictor.getBytes(6);
expect(result).toEqual(new Uint8Array([100, 3, 101, 2, 102, 1]));
});
});
});

3
test/unit/test_reports/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
TEST*
temp*

View File

@ -1,70 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>pdf.js unit test</title>
<link rel="shortcut icon" type="image/png" href="../../external/jasmine/jasmine_favicon.png">
<link rel="stylesheet" type="text/css" href="../../external/jasmine/jasmine.css">
<script type="text/javascript" src="../../external/jasmine/jasmine.js"></script>
<script type="text/javascript" src="../../external/jasmine/jasmine-html.js"></script>
<!-- include spec files here... -->
<script type="text/javascript" src="obj_spec.js"></script>
<script type="text/javascript" src="function_spec.js"></script>
<!-- include source files here... -->
<script type="text/javascript" src="../../src/core.js"></script>
<script type="text/javascript" src="../../src/util.js"></script>
<script type="text/javascript" src="../../src/canvas.js"></script>
<script type="text/javascript" src="../../src/obj.js"></script>
<script type="text/javascript" src="../../src/function.js"></script>
<script type="text/javascript" src="../../src/charsets.js"></script>
<script type="text/javascript" src="../../src/cidmaps.js"></script>
<script type="text/javascript" src="../../src/colorspace.js"></script>
<script type="text/javascript" src="../../src/crypto.js"></script>
<script type="text/javascript" src="../../src/evaluator.js"></script>
<script type="text/javascript" src="../../src/fonts.js"></script>
<script type="text/javascript" src="../../src/glyphlist.js"></script>
<script type="text/javascript" src="../../src/image.js"></script>
<script type="text/javascript" src="../../src/metrics.js"></script>
<script type="text/javascript" src="../../src/parser.js"></script>
<script type="text/javascript" src="../../src/pattern.js"></script>
<script type="text/javascript" src="../../src/stream.js"></script>
<script type="text/javascript" src="../../src/worker.js"></script>
<script type="text/javascript" src="../../external/jpgjs/jpg.js"></script>
<script type="text/javascript">
'use strict';
(function pdfJsUnitTest() {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var trivialReporter = new jasmine.TrivialReporter();
jasmineEnv.addReporter(trivialReporter);
jasmineEnv.specFilter = function pdfJsUnitTestSpecFilter(spec) {
return trivialReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function pdfJsUnitTestOnload() {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();
</script>
</head>
<body>
</body>
</html>

View File

@ -5,11 +5,16 @@
// Checking if the typed arrays are supported
(function checkTypedArrayCompatibility() {
if (typeof Uint8Array !== 'undefined')
if (typeof Uint8Array !== 'undefined') {
// some mobile version might not support Float64Array
if (typeof Float64Array === 'undefined')
window.Float64Array = Float32Array;
return;
}
function subarray(start, end) {
return this.slice(start, end);
return new TypedArray(this.slice(start, end));
}
function setArrayOffset(array, offset) {
@ -46,6 +51,8 @@
window.Uint32Array = TypedArray;
window.Int32Array = TypedArray;
window.Uint16Array = TypedArray;
window.Float32Array = TypedArray;
window.Float64Array = TypedArray;
})();
// Object.create() ?

View File

@ -15,6 +15,7 @@ body {
/* === Toolbar === */
#controls {
background-color: #eee;
background: -o-linear-gradient(bottom,#eee 0%,#fff 100%);
background: -moz-linear-gradient(center bottom, #eee 0%, #fff 100%);
background: -webkit-gradient(linear, left bottom, left top, color-stop(0.0, #ddd), color-stop(1.0, #fff));
border-bottom: 1px solid #666;
@ -82,6 +83,7 @@ span#info {
bottom: 18px;
left: -290px;
transition: left 0.25s ease-in-out 1s;
-o-transition: left 0.25s ease-in-out 1s;
-moz-transition: left 0.25s ease-in-out 1s;
-webkit-transition: left 0.25s ease-in-out 1s;
z-index: 1;
@ -90,6 +92,7 @@ span#info {
#sidebar:hover {
left: 0px;
transition: left 0.25s ease-in-out 0s;
-o-transition: left 0.25s ease-in-out 0s;
-moz-transition: left 0.25s ease-in-out 0s;
-webkit-transition: left 0.25s ease-in-out 0s;
}
@ -365,7 +368,7 @@ canvas {
color: black;
padding: 3px;
margin: 3px;
white-space: pre;
width: 98%;
}
.clearBoth {

View File

@ -26,6 +26,7 @@
<script type="text/javascript" src="../src/stream.js"></script> <!-- PDFJSSCRIPT_REMOVE -->
<script type="text/javascript" src="../src/worker.js"></script> <!-- PDFJSSCRIPT_REMOVE -->
<script type="text/javascript" src="../external/jpgjs/jpg.js"></script> <!-- PDFJSSCRIPT_REMOVE -->
<script type="text/javascript" src="../src/jpx.js"></script> <!-- PDFJSSCRIPT_REMOVE -->
<script type="text/javascript">PDFJS.workerSrc = '../src/worker_loader.js';</script> <!-- PDFJSSCRIPT_REMOVE -->
<script type="text/javascript" src="viewer.js"></script>
@ -67,10 +68,11 @@
<option value="0.75">75%</option>
<option value="1">100%</option>
<option value="1.25">125%</option>
<option value="1.5" selected="selected">150%</option>
<option value="1.5">150%</option>
<option value="2">200%</option>
<option id="pageWidthOption" value="page-width">Page Width</option>
<option id="pageFitOption" value="page-fit">Page Fit</option>
<option id="pageAutoOption" value="auto" selected="selected">Auto</option>
</select>
<div class="separator"></div>
@ -113,7 +115,7 @@
</button>
</div>
<div class="clearBoth"></div>
<div id="errorMoreInfo" hidden='true'></div>
<textarea id="errorMoreInfo" hidden='true' readonly="readonly"></textarea>
</div>
<div id="sidebar">

View File

@ -4,7 +4,7 @@
'use strict';
var kDefaultURL = 'compressed.tracemonkey-pldi-09.pdf';
var kDefaultScale = 1.5;
var kDefaultScale = 'auto';
var kDefaultScaleDelta = 1.1;
var kCacheSize = 20;
var kCssUnits = 96.0 / 72.0;
@ -33,6 +33,9 @@ var RenderingQueue = (function RenderingQueueClosure() {
RenderingQueue.prototype = {
enqueueDraw: function RenderingQueueEnqueueDraw(item) {
if (!item.drawingRequired())
return; // as no redraw required, no need for queueing.
if ('rendering' in item)
return; // is already in the queue
@ -146,9 +149,13 @@ var PDFView = {
pages: [],
thumbnails: [],
currentScale: 0,
currentScaleValue: null,
initialBookmark: document.location.hash.substring(1),
setScale: function pdfViewSetScale(val, resetAutoSettings) {
if (val == this.currentScale)
return;
var pages = this.pages;
for (var i = 0; i < pages.length; i++)
pages[i].update(val * kCssUnits);
@ -169,6 +176,7 @@ var PDFView = {
return;
var scale = parseFloat(value);
this.currentScaleValue = value;
if (scale) {
this.setScale(scale, true);
return;
@ -187,6 +195,10 @@ var PDFView = {
this.setScale(
Math.min(pageWidthScale, pageHeightScale), resetAutoSettings);
}
if ('auto' == value)
this.setScale(Math.min(1.0, pageWidthScale), resetAutoSettings);
selectScaleOption(value);
},
zoomIn: function pdfViewZoomIn() {
@ -337,13 +349,14 @@ var PDFView = {
};
moreInfoButton.removeAttribute('hidden');
lessInfoButton.setAttribute('hidden', 'true');
errorMoreInfo.innerHTML = 'PDF.JS Build: ' + PDFJS.build + '\n';
errorMoreInfo.value = 'PDF.JS Build: ' + PDFJS.build + '\n';
if (moreInfo) {
errorMoreInfo.innerHTML += 'Message: ' + moreInfo.message;
errorMoreInfo.value += 'Message: ' + moreInfo.message;
if (moreInfo.stack)
errorMoreInfo.innerHTML += '\n' + 'Stack: ' + moreInfo.stack;
errorMoreInfo.value += '\n' + 'Stack: ' + moreInfo.stack;
}
errorMoreInfo.rows = errorMoreInfo.value.split('\n').length - 1;
},
progress: function pdfViewProgress(level) {
@ -357,6 +370,7 @@ var PDFView = {
// when page is painted, using the image as thumbnail base
pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {
thumbnailView.setImage(pageView.canvas);
preDraw();
};
}
@ -428,6 +442,10 @@ var PDFView = {
this.switchSidebarView('outline');
}
// Reset the current scale, as otherwise the page's scale might not get
// updated if the zoom level stayed the same.
this.currentScale = 0;
this.currentScaleValue = null;
if (this.initialBookmark) {
this.setHash(this.initialBookmark);
this.initialBookmark = null;
@ -435,7 +453,7 @@ var PDFView = {
else if (storedHash)
this.setHash(storedHash);
else {
this.setScale(scale || kDefaultScale, true);
this.parseScale(scale || kDefaultScale, true);
this.page = 1;
}
@ -525,8 +543,16 @@ var PDFView = {
if ('zoom' in params) {
var zoomArgs = params.zoom.split(','); // scale,left,top
// building destination array
// If the zoom value, it has to get divided by 100. If it is a string,
// it should stay as it is.
var zoomArg = zoomArgs[0];
var zoomArgNumber = parseFloat(zoomArg);
if (zoomArgNumber)
zoomArg = zoomArgNumber / 100;
var dest = [null, {name: 'XYZ'}, (zoomArgs[1] | 0),
(zoomArgs[2] | 0), (zoomArgs[0] | 0) / 100];
(zoomArgs[2] | 0), zoomArg];
var currentPage = this.pages[pageNumber - 1];
currentPage.scrollIntoView(dest);
} else
@ -813,8 +839,12 @@ var PageView = function pageView(container, content, id, pageWidth, pageHeight,
}, 0);
};
this.drawingRequired = function() {
return !div.hasChildNodes();
};
this.draw = function pageviewDraw(callback) {
if (div.hasChildNodes()) {
if (!this.drawingRequired()) {
this.updateStats();
callback();
return;
@ -826,9 +856,13 @@ var PageView = function pageView(container, content, id, pageWidth, pageHeight,
div.appendChild(canvas);
this.canvas = canvas;
var textLayer = document.createElement('div');
textLayer.className = 'textLayer';
div.appendChild(textLayer);
var textLayerDiv = null;
if (!PDFJS.disableTextLayer) {
textLayerDiv = document.createElement('div');
textLayerDiv.className = 'textLayer';
div.appendChild(textLayerDiv);
}
var textLayer = textLayerDiv ? new TextLayerBuilder(textLayerDiv) : null;
var scale = this.scale;
canvas.width = pageWidth * scale;
@ -923,6 +957,10 @@ var ThumbnailView = function thumbnailView(container, page, id, pageRatio) {
return ctx;
}
this.drawingRequired = function thumbnailViewDrawingRequired() {
return !this.hasImage;
};
this.draw = function thumbnailViewDraw(callback) {
if (this.hasImage) {
callback();
@ -985,6 +1023,86 @@ var DocumentOutlineView = function documentOutlineView(outline) {
}
};
var TextLayerBuilder = function textLayerBuilder(textLayerDiv) {
this.textLayerDiv = textLayerDiv;
this.beginLayout = function textLayerBuilderBeginLayout() {
this.textDivs = [];
this.textLayerQueue = [];
};
this.endLayout = function textLayerBuilderEndLayout() {
var self = this;
var textDivs = this.textDivs;
var textLayerDiv = this.textLayerDiv;
var renderTimer = null;
var renderingDone = false;
var renderInterval = 0;
var resumeInterval = 500; // in ms
// Render the text layer, one div at a time
function renderTextLayer() {
if (textDivs.length === 0) {
clearInterval(renderTimer);
renderingDone = true;
return;
}
var textDiv = textDivs.shift();
if (textDiv.dataset.textLength > 0) {
textLayerDiv.appendChild(textDiv);
if (textDiv.dataset.textLength > 1) { // avoid div by zero
// Adjust div width (via letterSpacing) to match canvas text
// Due to the .offsetWidth calls, this is slow
// This needs to come after appending to the DOM
textDiv.style.letterSpacing =
((textDiv.dataset.canvasWidth - textDiv.offsetWidth) /
(textDiv.dataset.textLength - 1)) + 'px';
}
} // textLength > 0
}
renderTimer = setInterval(renderTextLayer, renderInterval);
// Stop rendering when user scrolls. Resume after XXX milliseconds
// of no scroll events
var scrollTimer = null;
function textLayerOnScroll() {
if (renderingDone) {
window.removeEventListener('scroll', textLayerOnScroll, false);
return;
}
// Immediately pause rendering
clearInterval(renderTimer);
clearTimeout(scrollTimer);
scrollTimer = setTimeout(function textLayerScrollTimer() {
// Resume rendering
renderTimer = setInterval(renderTextLayer, renderInterval);
}, resumeInterval);
}; // textLayerOnScroll
window.addEventListener('scroll', textLayerOnScroll, false);
}; // endLayout
this.appendText = function textLayerBuilderAppendText(text,
fontName, fontSize) {
var textDiv = document.createElement('div');
// vScale and hScale already contain the scaling to pixel units
var fontHeight = fontSize * text.geom.vScale;
textDiv.dataset.canvasWidth = text.canvasWidth * text.geom.hScale;
textDiv.style.fontSize = fontHeight + 'px';
textDiv.style.fontFamily = fontName || 'sans-serif';
textDiv.style.left = text.geom.x + 'px';
textDiv.style.top = (text.geom.y - fontHeight) + 'px';
textDiv.textContent = text.str;
textDiv.dataset.textLength = text.length;
this.textDivs.push(textDiv);
};
};
window.addEventListener('load', function webViewerLoad(evt) {
var params = document.location.search.substring(1).split('&');
for (var i = 0; i < params.length; i++) {
@ -992,7 +1110,7 @@ window.addEventListener('load', function webViewerLoad(evt) {
params[unescape(param[0])] = unescape(param[1]);
}
var scale = ('scale' in params) ? params.scale : kDefaultScale;
var scale = ('scale' in params) ? params.scale : 0;
PDFView.open(params.file || kDefaultURL, parseFloat(scale));
if (!window.File || !window.FileReader || !window.FileList || !window.Blob)
@ -1001,7 +1119,10 @@ window.addEventListener('load', function webViewerLoad(evt) {
document.getElementById('fileInput').value = null;
if ('disableWorker' in params)
PDFJS.disableWorker = params['disableWorker'] === 'true' ? true : false;
PDFJS.disableWorker = (params['disableWorker'] === 'true');
if ('disableTextLayer' in params)
PDFJS.disableTextLayer = (params['disableTextLayer'] === 'true');
var sidebarScrollView = document.getElementById('sidebarScrollView');
sidebarScrollView.addEventListener('scroll', updateThumbViewArea, true);
@ -1011,26 +1132,64 @@ window.addEventListener('unload', function webViewerUnload(evt) {
window.scrollTo(0, 0);
}, true);
/**
* Render the next not yet visible page already such that it is
* hopefully ready once the user scrolls to it.
*/
function preDraw() {
var pages = PDFView.pages;
var visible = PDFView.getVisiblePages();
var last = visible[visible.length - 1];
// PageView.id is the actual page number, which is + 1 compared
// to the index in `pages`. That means, pages[last.id] is the next
// PageView instance.
if (pages[last.id] && pages[last.id].drawingRequired()) {
renderingQueue.enqueueDraw(pages[last.id]);
return;
}
// If there is nothing to draw on the next page, maybe the user
// is scrolling up, so, let's try to render the next page *before*
// the first visible page
if (pages[visible[0].id - 2]) {
renderingQueue.enqueueDraw(pages[visible[0].id - 2]);
}
}
function updateViewarea() {
var visiblePages = PDFView.getVisiblePages();
var pageToDraw;
for (var i = 0; i < visiblePages.length; i++) {
var page = visiblePages[i];
renderingQueue.enqueueDraw(PDFView.pages[page.id - 1]);
var pageObj = PDFView.pages[page.id - 1];
pageToDraw |= pageObj.drawingRequired();
renderingQueue.enqueueDraw(pageObj);
}
if (!visiblePages.length)
return;
// If there is no need to draw a page that is currenlty visible, preDraw the
// next page the user might scroll to.
if (!pageToDraw) {
preDraw();
}
updateViewarea.inProgress = true; // used in "set page"
var currentId = PDFView.page;
var firstPage = visiblePages[0];
PDFView.page = firstPage.id;
updateViewarea.inProgress = false;
var currentScale = PDFView.currentScale;
var currentScaleValue = PDFView.currentScaleValue;
var normalizedScaleValue = currentScaleValue == currentScale ?
currentScale * 100 : currentScaleValue;
var kViewerTopMargin = 52;
var pageNumber = firstPage.id;
var pdfOpenParams = '#page=' + pageNumber;
pdfOpenParams += '&zoom=' + Math.round(PDFView.currentScale * 100);
pdfOpenParams += '&zoom=' + normalizedScaleValue;
var currentPage = PDFView.pages[pageNumber - 1];
var topLeft = currentPage.getPagePoint(window.pageXOffset,
window.pageYOffset - firstPage.y - kViewerTopMargin);
@ -1039,7 +1198,7 @@ function updateViewarea() {
var store = PDFView.store;
store.set('exists', true);
store.set('page', pageNumber);
store.set('zoom', Math.round(PDFView.currentScale * 100));
store.set('zoom', normalizedScaleValue);
store.set('scrollLeft', Math.round(topLeft.x));
store.set('scrollTop', Math.round(topLeft.y));
@ -1075,7 +1234,8 @@ window.addEventListener('webkitTransitionEnd', updateThumbViewArea, true);
window.addEventListener('resize', function webViewerResize(evt) {
if (document.getElementById('pageWidthOption').selected ||
document.getElementById('pageFitOption').selected)
document.getElementById('pageFitOption').selected ||
document.getElementById('pageAutoOption').selected)
PDFView.parseScale(document.getElementById('scaleSelect').value);
updateViewarea();
});
@ -1112,20 +1272,9 @@ window.addEventListener('change', function webViewerChange(evt) {
document.getElementById('download').setAttribute('hidden', 'true');
}, true);
window.addEventListener('scalechange', function scalechange(evt) {
var customScaleOption = document.getElementById('customScaleOption');
customScaleOption.selected = false;
if (!evt.resetAutoSettings &&
(document.getElementById('pageWidthOption').selected ||
document.getElementById('pageFitOption').selected)) {
updateViewarea();
return;
}
function selectScaleOption(value) {
var options = document.getElementById('scaleSelect').options;
var predefinedValueFound = false;
var value = '' + evt.scale;
for (var i = 0; i < options.length; i++) {
var option = options[i];
if (option.value != value) {
@ -1135,7 +1284,22 @@ window.addEventListener('scalechange', function scalechange(evt) {
option.selected = true;
predefinedValueFound = true;
}
return predefinedValueFound;
}
window.addEventListener('scalechange', function scalechange(evt) {
var customScaleOption = document.getElementById('customScaleOption');
customScaleOption.selected = false;
if (!evt.resetAutoSettings &&
(document.getElementById('pageWidthOption').selected ||
document.getElementById('pageFitOption').selected ||
document.getElementById('pageAutoOption').selected)) {
updateViewarea();
return;
}
var predefinedValueFound = selectScaleOption('' + evt.scale);
if (!predefinedValueFound) {
customScaleOption.textContent = Math.round(evt.scale * 10000) / 100 + '%';
customScaleOption.selected = true;