Commit Graph

577 Commits

Author SHA1 Message Date
Jonas Jenwald
6dc39cb873 Tweak the new mouseState parameter, and its usage, in the viewer components and the AnnotationLayer
- Actually remove the `isDown` property when destroying the scripting-instance.

 - Mark all `mouseState` usage as "private" in the various classes.

 - Ensure that the `AnnotationLayer` actually treats the parameter as properly *optional*, the same way that the viewer components do.

 - For now remove the `mouseState` parameter from the `PDFPageView` class, and keep it only on the `BaseViewer`, since it's questionable if all of the scripting-functionality will work all that well without e.g. a full `BaseViewer`.

 - Append the `mouseState` to the JSDoc for the `AnnotationElement` class, and just move its definition into the base-`AnnotationElement` class.
2020-12-18 22:03:41 +01:00
calixteman
e6e2809825
Merge pull request #12702 from calixteman/doc_actions
JS - Collect and execute actions at doc level
2020-12-18 21:33:32 +01:00
Calixte Denizet
1e2173f038 JS - Collect and execute actions at doc and pages level
* the goal is to execute actions like Open or OpenAction
 * can be tested with issue6106.pdf (auto-print)
 * once #12701 is merged, we can add page actions
2020-12-18 20:03:59 +01:00
Calixte Denizet
4ae9064d60 Dispatch an event on sandbox creation
* the goal is to be able to know when the sandbox is ready for mochitest in m-c
2020-12-18 19:12:43 +01:00
Calixte Denizet
8bff4f1ea9 In order to simplify m-c code, move some in pdf.js
* move set/clear|Timeout/Interval and crackURL code in pdf.js
 * remove the "backdoor" in the proxy (used to dispatch event) and so return the dispatch function in the initializer
 * remove listeners if an error occured during sandbox initialization
 * add support for alert and prompt in the sandbox
 * add a function to eval in the global scope
2020-12-17 15:03:26 +01:00
Calixte Denizet
6502ae889d JS -- Send events to the sandbox from annotation layer 2020-12-15 16:28:47 +01:00
Jonas Jenwald
6218b9a512 Re-factor/re-name the scripting getter, on the externalServices-implementations, to a createScripting method
Given that the GENERIC default viewer supports opening more than one document, and that a unique scripting-instance is now used for each document, the changes made in this patch seem appropriate.
2020-12-09 22:15:50 +01:00
Jonas Jenwald
6c807f3f86 Move destroying of the scripting-instance from PDFViewerApplication.close and into its own helper method
Since the `close` method has become quite large, this small re-factoring shouldn't hurt (and may also be useful with future changes to the `_initializeJavaScript` method).
2020-12-09 22:15:50 +01:00
Jonas Jenwald
8d72981c18 Move cancelling of idleCallbacks from PDFViewerApplication.close and into its own helper method
Since the `close` method has become quite large, this small re-factoring shouldn't hurt.
2020-12-09 22:15:50 +01:00
Jonas Jenwald
1e007f9285 Actually remove a scripting-instance, and its global events, upon document closing
I was actually quite surprised to find that, despite the various `scripting`-getters implementing `destroySandbox` methods, there were no attempts at actually cleaning-up either the "sandbox" or removing the globally registered event listeners.
2020-12-06 14:20:43 +01:00
Jonas Jenwald
f4d8a427f0 Ensure that the *correct* PDF document is still active after *every* asynchronous API-call in PDFViewerApplication._initializeJavaScript
This patch also changes the method to skip *all* data fetching when "enableScripting" isn't active. Finally, simplifies some event-data accesses in the "updateFromSandbox" listener.
2020-12-06 14:18:10 +01:00
Jonas Jenwald
1f2f8c907b Tweak the "filesize" handling in PDFViewerApplication._initializeJavaScript
Another possible option here could be to use the `contentLength`, when it exists, and then using e.g. a custom event to always update the "filesize" in the sandbox "after the fact" with the result of the `getDownloadInfo`-call.
2020-12-06 13:08:36 +01:00
Jonas Jenwald
bfdb39a1e6 Stop re-fetching the metadata unconditionally in PDFViewerApplication._initializeJavaScript
We can easily avoid unnecessary API-calls here, since most of the time the `metadata` will already be available here. In the *rare* case that it's not available, we can simply wait for the existing `getMetadata`-call to resolve.
2020-12-06 12:42:56 +01:00
Jonas Jenwald
f8ea83609f Dispatch a metadataloaded event once the PDFViewerApplication._initializeMetadata method is done
This will be useful in the following patch, and note that there's also an old issue (see 5765) which asked for such an event. However, given that the use-case wasn't *clearly* specified, and that we didn't have an internal use for it at the time it wasn't implemented.

Also, ensure that all of the metadata-related properties are actually reset when the document is closed.
2020-12-06 12:30:33 +01:00
Brendan Dahl
956fcab967
Merge pull request #12631 from calixteman/app
JS -- Implement app object
2020-12-01 16:50:16 -08:00
Calixte Denizet
283aac4c53 JS -- Implement app object
* https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/AcrobatDC_js_api_reference.pdf
 * Add color, fullscreen objects + few constants.
2020-11-20 15:46:52 +01:00
Jonas Jenwald
01d12b465c [api-minor] Add "contentLength" to the information returned by the getMetadata method
Given that we already include the "Content-Disposition"-header filename, when it exists, it shouldn't hurt to also include the information from the "Content-Length"-header.
For PDF documents opened via a URL, which should be a very common way for the PDF.js library to be used, this will[1] thus provide a way of getting the PDF filesize without having to wait for the `getDownloadInfo`-promise to resolve[2].

With these API improvements, we can also simplify the filesize handling in the `PDFDocumentProperties` class.

---
[1] Assuming that the server is correctly configured, of course.

[2] Since that's not *guaranteed* to happen in general, with e.g. `disableAutoFetch = true` set.
2020-11-20 15:30:36 +01:00
Jonas Jenwald
cc861c34e9 Add an AppOptions.setAll method, and use it in PDFViewerApplication._readPreferences
Given that it's generally faster to call *one* function and have it loop through an object, rather than looping through an object and calling a function for every iteration, this patch will reduce the total time spent in `PDFViewerApplication._readPreferences` ever so slightly.
Also, over time we've been adding more and more preferences, rather than removing them, so using the new `AppOptions.setAll` method should be generally beneficial as well.

While the effect of these changes is quite small, it does reduces the time it takes for the preferences to be fully initialized. Given the amount of asynchronous code during viewer initialization, every bit of time that we can save should thus help.
Especially considering the recently added `viewerCssTheme` preference, which needs to be read very early to reduce the risk of the viewer UI "flashing" visibly as the theme changes, I figured that a couple of small patches reducing the time spend reading preferences cannot hurt.
2020-11-18 12:10:21 +01:00
Jonas Jenwald
4886a7cf69 Skip Promise.all in PDFViewerApplication._parseHashParameters unless actually necessary
Given that only two debugging hash parameters (i.e. `disableWorker` and `pdfBug`) will make this method asynchronous, we can avoid what's most of the time is an unnecessary `Promise.all` invocation.
2020-11-18 11:45:18 +01:00
Jonas Jenwald
40a4d53fb3 Add a new preference, viewerCssTheme, to allow forcing the use of the light/dark viewer CSS themes (issue 12290)
While this does work pretty well in my quick testing, it's *very much* a hack since as far as I can tell there's no support in the CSS specification for using e.g. a CSS variable to override a `@media (prefers-color-scheme: dark) {...}` block.

The solution implemented here is thus to *edit* the viewer CSS, by either removing the entire `@media ...` block in light-mode or by ensuring that its rules become *unconditionally* applied in dark-mode.
To simplify the overall implementation, since all of this does seem like somewhat of an edge-case, the `viewerCssTheme` preference will *only* be read during viewer initialization. (Similar to many other existing preferences, a reload is thus required when changing it.)
2020-11-16 21:13:13 +01:00
Calixte Denizet
2dfac4cb41 JS -- Fix events dispatchment and add tests
* dispatch event to take into account calculation order
 * use a map for actions in Field
2020-11-10 17:26:29 +01:00
Calixte Denizet
8de98079ca JS -- Implement doc object
* https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/js_api_reference.pdf#page=335
 * it has all the properties/methods defined in the spec
 * unimplemented methods are there but with an empty body to avoid exception when calling an undefined method
 * implement zoom, zoomType, layout, pageNum, ...
2020-11-10 16:16:42 +01:00
Calixte Denizet
a5279897a7 JS -- Add listener for sandbox events only if there are some actions
* When no actions then set it to null instead of empty object
* Even if a field has no actions, it needs to listen to events from the sandbox in order to be updated if an action changes something in it.
2020-11-09 18:37:59 +01:00
Jonas Jenwald
9602844368 Enable the ESLint no-useless-escape rule (PR 12551 follow-up)
Note that a number of these cases are covered by existing unit-tests, and a few others only matter for the development/build scripts.
Furthermore, I've also tried to the best of my ability to test each case *manually* to hopefully further reduce the likelihood of this patch introducing any bugs.

Please find additional details about the ESLint rule at https://eslint.org/docs/rules/no-useless-escape
2020-11-07 13:06:24 +01:00
Jonas Jenwald
911948c5c0 Also update the browser history when the user *manually* change pages using the pageNumber-input (PR 12493 follow-up)
This patch addresses a review comment, which pointed out that we should *also* handle the pageNumber-input, from PR 12493.

Given that a user *manually* changing pages using the pageNumber-input, on the toolbar, could be regarded as a pretty strong indication of user-intent w.r.t. navigation in the document, hence I suppose that updating the browser history in this case as well probably won't hurt.
2020-11-01 15:37:24 +01:00
Tim van der Meij
e341e6e542
Merge pull request #12525 from brendandahl/mark-info
[api-minor] Implement API to get MarkInfo from the catalog.
2020-10-31 00:05:19 +01:00
Brendan Dahl
8a8b4f9697 Collect telemetry in the viewer on whether a PDF is tagged. 2020-10-30 10:59:45 -07:00
Jonas Jenwald
d9084c0be2 Load the fake worker, in non-PRODUCTION mode, with native async import
This removes the last SystemJS usage from both the API and the default viewer.
2020-10-26 11:11:48 +01:00
Jonas Jenwald
7bf9a872ed Fix a couple of edge-cases in PDFViewerApplication._initializeJavaScript (PR 12432 follow-up)
- Return early in `PDFViewerApplication._initializeJavaScript` for PDF documents without any `fieldObjects`, which is the vast majority of all documents, to prevent errors when trying to parse a non-existent object.

 - Similar to the other `PDFViewerApplication._initialize*` methods, ignore the `fieldObjects` if the document was closed before the data resolved.

 - Fix the JSDoc comment for the `generateRandomStringForSandbox` helper function, since there's currently a bit too much copy-and-paste going on :-)

 - Change `FirefoxScripting` to a class with static methods, which is consistent with the surrounding code in `web/firefoxcom.js`.
2020-10-23 12:28:44 +02:00
Calixte Denizet
e76a96892a JS - Add the basic architecture to be able to execute embedded js 2020-10-21 19:00:56 +02:00
Jonas Jenwald
ba079453bf Enable the ESLint no-debugger and no-alert rules
The `debugger`-statement would only, potentially, make sense during development and we thus want to prevent it from being accidentally included when landing code.
The `alert`, `confirm`, and `prompt` functions should generally be avoided, with the few intended cases manually allowed.

Please find additional details about the ESLint rules at:
 - https://eslint.org/docs/rules/no-debugger
 - https://eslint.org/docs/rules/no-alert
2020-10-05 13:41:06 +02:00
Jonas Jenwald
89ce326d12 Re-factor how printing is triggered in the default viewer
This adds a new `PDFViewerApplication.triggerPrinting` method, which takes care of checking that printing is actually supported before calling `window.print`, to remove the need to duplicate that code in multiple places.

Also, removes the `PDFViewerApplication.printing` getter since it's not really necessary any more.
2020-09-30 15:10:19 +02:00
Tim van der Meij
d49b2f6cc2
Merge pull request #12422 from Snuffleupagus/find-not-shiftKey
Don't trigger searching, in the `GENERIC` viewer, when <kbd>Shift</kbd> is used together with the regular keyboard shortcut (issue 12421)
2020-09-29 22:30:53 +02:00
Jonas Jenwald
db4cefbac3 Add basic support for the optional chaining operator ?.
For now we need to use a Babel-plugin, since part of our build system doesn't support this fully (e.g. Babel-loader, Webpack 4.x, and SystemJS).

While the `?.` operator will thus always be transpiled by Babel, even in modern builds, simply supporting it for development purposes seems like a step in the right direction.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
2020-09-29 15:56:34 +02:00
Jonas Jenwald
f399ac7f16 Don't trigger searching, in the GENERIC viewer, when <kbd>Shift</kbd> is used together with the regular keyboard shortcut (issue 12421)
Please note that this change won't affect the Firefox built-in PDF Viewer, since it uses the native browser findbar. However, it brings the `GENERIC` viewer inline with how searching is normally triggered in browsers.

Note that in Firefox searching is only triggered by <kbd>Ctrl</kbd>+<kbd>F</kbd> (or <kbd>command</kbd>+<kbd>F</kbd> on Mac), but <kbd>Shift</kbd> isn't used; see https://support.mozilla.org/en-US/kb/keyboard-shortcuts-perform-firefox-tasks-quickly#w_search

Furthermore, looking at the "Miscellaneous" section of https://support.mozilla.org/en-US/kb/keyboard-shortcuts-perform-firefox-tasks-quickly#firefox:mac:fx81 the <kbd>command</kbd>+<kbd>Shift</kbd>+<kbd>F</kbd> shortcut is even reserved for the "Toggle Full Screen" functionality on Mac.
2020-09-29 11:50:20 +02:00
Tim van der Meij
6728c8fa61
Merge pull request #12405 from nickyc975/fixed-active-element-in-shadow-dom
Fixed keydown event handling problem with shadow DOM.
2020-09-26 23:02:13 +02:00
Jonas Jenwald
a4e5458774 Update all BaseViewer.getPageView/PDFThumbnailViewer.getThumbnail call-sites, in web/app.js, to check the returned value properly
Given how those are used, there *should* not be any situation in which e.g. `undefined` is ever returned. However, actually checking that the pageView/thumbnail is defined cannot hurt.

Also, re-factor `webViewerPageRendered` slightly since the `pageView` is no longer unconditionally necessary after the previous patches; note in particular that the thumbnails will only be updated when the sidebar *and* the thumbnailView is visible.

Finally, fixes a bug in `webViewerPageChanging` whereby an empty string would not be treated as a valid pageLabel and instead be replaced by `null`.
2020-09-25 14:42:46 +02:00
Jonas Jenwald
e46055a92c Remove the PDFPageView.stats property, and fetch it manually only when debugging is enabled
Given that the default viewer only uses the "page stats" when debugging is enabled, it seems much simpler and more straightforward to simply query the API *directly* when this information is actually required. That way, there's a bit less information that needs to be stored/updated on each `PDFPageView`-instance.

Finally, since the `EventBus` now exists, we no longer need to handle the "page stats"-case in the regular listeners in `web/app.js`, but can instead add special "page stats"-listeners only when debugging is enabled.
2020-09-25 14:42:44 +02:00
Jonas Jenwald
9efc1784b2 Remove the PDFPageView.error property, and simply include Errors in the "pagerendered" event instead
The way that rendering errors are handled in `PDFPageView` is *very* old, and predates e.g. the introduction of the `EventBus` by several years.
Hence we should be able to simplify things a bit here, by including the Error (when it exists) in the "pagerendered" event and thus avoid having to reach into `PDFPageView` for it.
2020-09-25 14:21:12 +02:00
Nicky Chen
252e258a59 Fixed keydown event handling problem with shadow DOM.
Editable elements in shadow DOMs can not be detected in old version.
2020-09-24 08:17:56 +08:00
Jonas Jenwald
87b002c52f Remove code-paths only relevant for IE 11/Edge (non-Chromium based) from the web/ folder
This patch purposely starts small, by removing IE-specific code from various JS/CSS files in the `web/` folder.

There's obviously lots of potential for additional clean-up, especially the removal of no longer necessary polyfills in `src/shared/compatibility.js`, however that will require some care considering that certain polyfills may also be necessary for e.g. Node.js or the Chromium-extension as well.
Generally speaking, once we start removing polyfills it's probably a good idea to consult the compatibility information on https://developer.mozilla.org/ and also https://caniuse.com/ first. (Deciding on the lowest supported Chromium version, for the extension, would also seem like a good idea.)
2020-09-05 17:18:15 +02:00
Jonas Jenwald
695523712c Add support for /Print and /SaveAs named actions in the viewer (issue 12308)
All of the core/display functionality needed to support this already exists, we simply need to handle these named actions in the viewer and the buttons will "just" work.

Unfortunately there's not really any good way of testing this, but given the size and scope of the patch that's hopefully OK.
2020-09-01 09:24:38 +02:00
Jonas Jenwald
66aabe3ec7 [api-minor] Add support for toggling of Optional Content in the viewer (issue 12096)
*Besides, obviously, adding viewer support:* This patch attempts to improve the general API for Optional Content Groups slightly, by adding a couple of new methods for interacting with the (more complex) data structures of `OptionalContentConfig`-instances. (Thus allowing us to mark some of the data as "private", given that it probably shouldn't be manipulated directly.)

By utilizing not just the "raw" Optional Content Groups, but the data from the `/Order` array when available, we can thus display the Layers in a proper tree-structure with collapsible headings for PDF documents that utilizes that feature.

Note that it's possible to reset all Optional Content Groups to their default visibility state, simply by double-clicking on the Layers-button in the sidebar.
(Currently that's indicated in the Layers-button tooltip, which is obviously easy to overlook, however it's probably the best we can do for now without adding more buttons, or even a dropdown-toolbar, to the sidebar.)

Also, the current Layers-button icons are a little rough around the edges, quite literally, but given that the viewer will soon have its UI modernized anyway they hopefully suffice in the meantime.

To give users *full* control of the visibility of the various Optional Content Groups, even those which according to the `/Order` array should not (by default) be toggleable in the UI, this patch will place those under a *custom* heading which:
 - Is collapsed by default, and placed at the bottom of the Layers-tree, to be a bit less obtrusive.
 - Uses a slightly different formatting, compared to the "regular" headings.
 - Is localizable.

Finally, note that the thumbnails are *purposely* always rendered with all Optional Content Groups at their default visibility state, since that seems the most useful and it's also consistent with other viewers.
To ensure that this works as intended, we'll thus disable the `PDFThumbnailView.setImage` functionality when the Optional Content Groups have been changed in the viewer. (This obviously means that we'll re-render thumbnails instead of using the rendered pages. However, this situation ought to be rare enough for this to not really be a problem.)
2020-08-30 16:28:40 +02:00
Jonas Jenwald
77a1e531c2 Ensure that the sourceEventType parameter is actually optional in PDFViewerApplication.{download, save} (PR 12248 follow-up)
Without these changes, clicking on the "Open With Different Viewer"-button on the Firefox fallback bar won't actually do anything and the following is printed in the web-console:
```
Uncaught TypeError: (destructured parameter) is undefined
    download resource://pdf.js/web/viewer.js:956
    response resource://pdf.js/web/viewer.js:1054
    listener resource://pdf.js/web/viewer.js:11891
viewer.js:956:1
```

Furthermore, this patch also fixes `PDFViewerApplication.fallback` to pass in an explicit `sourceEventType` when triggering downloading. While this, on its own, would obviously have been sufficient to fix the bug described above, it seems wrong to outright break backwards compatibility of any older `PDFViewerApplication.download` calls.
2020-08-26 11:45:25 +02:00
Tim van der Meij
280207c740
Redo the form type detection logic and include unit tests
Good form type detection is important to get reliable telemetry and to
only show the fallback bar if a form cannot be filled out by the user.

PDF.js only supports AcroForm data, so XFA data is explicitly unsupported
(tracked in issue #2373). However, the previous form type detection
couldn't separate AcroForm and XFA well enough, causing form type
telemetry to be incorrect sometimes and the fallback bar to be shown for
forms that could in fact be filled out by the user.

The solution in this commit is found by studying the specification and
the form documents that are available to us. In a nutshell the rules are:

- There is XFA data if the `XFA` entry is a non-empty array or stream.
- There is AcroForm data if the `Fields` entry is a non-empty array and
  it doesn't consist of only document signatures.

The document signatures part was not handled in the old code, causing a
document with only XFA data to also be marked as having AcroForm data.
Moreover, the old code didn't check all the data types.

Now that AcroForm and XFA can be distinguished, the viewer is configured
to only show the fallback bar for documents that only have XFA data. If
a document also has AcroForm data, the viewer can use that to render the
form. We have not found documents where the XFA data was necessary in
that case.

Finally, we include unit tests to ensure that all cases are covered and
move the form type detection out of the `parse` function so that it's
only executed if the document information is actually requested
(potentially making initial parsing a tiny bit faster).
2020-08-25 23:28:55 +02:00
Jonas Jenwald
f2e3d6c819 Don't warn when navigating away from a modified form, if printing has occurred (issue 12262)
This solution is obviously *not* perfect, since printing being cancelled will thus remove the warning as well. However, a similar problem already exists for saving, since the user may cancel that one as well.

All-in-all, since way cannot really detect with absolute certainty that either saving or printing actually finished, this seems good enough for now.
2020-08-22 17:49:56 +02:00
Aki Sasaki
b1423336c3 #12241 followup - move event listener to PDFViewerApplication.load 2020-08-21 09:53:39 -07:00
Brendan Dahl
8023175103 Support file save triggered from the Firefox integrated version.
Related to https://bugzilla.mozilla.org/show_bug.cgi?id=1659753

This allows Firefox trigger a "save" event from ctrl/cmd+s or the "Save
Page As" context menu, which in turn lets pdf.js generate a new PDF if
there is form data to save.

I also now use `sourceEventType` on downloads so Firefox can determine if
it should launch the "open with" dialog or "save as" dialog.
2020-08-20 18:05:08 -07:00
DesWurstes
72f48ee089 Return the query with the findcontrols 2020-08-20 11:18:43 +01:00
Tim van der Meij
192afb87e3
Merge pull request #12203 from staktrace/zoomfix
Bug 1392361 - Fix zooming sensitivity on macOS
2020-08-16 22:36:37 +02:00
Tim van der Meij
66bbe82cc5
Merge pull request #12212 from staktrace/touchfix
Bug 1643508 - Disable touch-based pinch zooming on pdf.js.
2020-08-16 22:12:02 +02:00
Kartikaya Gupta
c6e5686b6a Bug 1643508 - Disable touch-based pinch zooming on pdf.js.
Currently using a touchscreen with pdf.js doesn't work so well. In Firefox,
with apz.allow_zooming = false (default on current release/beta), it does a
reflow zoom which makes the UI elements bigger. And with apz.allow_zooming = true
(default on current Firefox nightly), or in Chrome, it does a smooth pinch-zoom
but that also scales up the entire UI. Neither of these is a particularly good
experience, so this patch just disables any multi-touch gestures. Touch-based
panning (which involves a single touch point) is left unaffected.
2020-08-13 09:22:30 -04:00
Jonas Jenwald
22cb59e7d0 Wait until saving has finished before resetting PDFViewerApplication._saveInProgress (PR 12137 follow-up)
I obviously missed this during review, but currently `PDFViewerApplication._saveInProgress` is reset *synchronously* in `PDFViewerApplication.save`.
That was probably not intended, since it essentially renders the `PDFViewerApplication._saveInProgress` check pointless given that the actual saving is an *asynchronous* operation.
2020-08-13 13:00:29 +02:00
Kartikaya Gupta
213676b5e8 Bug 1392361 - Fix zooming sensitivity on macOS
The original code would get a long sequence of miniscule "tick" values while
pinch-zooming, and each tick value would cause a 1.1x zoom. So even the smallest
pinch gesture on a trackpad would cause high amounts of zoom. This patch
accumulates the wheel deltas until they reach an integer threshold (with a
tweak of the scaling factor to make it feel more natural) at which point it
triggers the zoom based on the integer component of the accumulated delta. The
fractional part is retained in the accumulator.
2020-08-12 17:18:50 -04:00
Brendan Dahl
da62be0685 Enable renderInteractiveForms by default. 2020-08-12 10:28:27 -07:00
Calixte Denizet
1a6816ba98 Add support for saving forms 2020-08-12 10:32:59 +02:00
Jonas Jenwald
5b94ed5487 Remove the disableCreateObjectURL option from web/app_options.js
Prior to PR 11601, the `disableCreateObjectURL` option was present on `getDocument` in the API, since it was (potentially) used when decoding JPEG images natively in the browser. Hence setting this option, which was done automatically using compatibility-code, were in some browsers necessary in order for e.g. JPEG images to be correctly rendered.

The downside of the `disableCreateObjectURL` option is that memory usage increases significantly, since we're forced to build and use `data:` URIs (rather than `blob:` URLs).
However, at this point in time the `disableCreateObjectURL` option is only necessary for *some* (non-essential) functionality in the default viewer; in particular:
 - The openfile functionality, used only when manually opening a new file in the default viewer.
 - The download functionality, used when downloading either the PDF document itself or its attached files (if such exists).
 - The print functionality, in the generic `PDFPrintService` implementation.

Hence neither the general PDF.js library, nor the *basic* functionality of the default viewer, depends on the `disableCreateObjectURL` option any more; which is why I'm thus proposing that we remove the option since using it is a performance footgun.

*Please note:* To not outright break currently "supported" browsers, which lack proper `URL.createObjectURL` support, this patch purposely keeps the compatibility-code to explicitly disable `URL.createObjectURL` usage *only* for browsers which are known to not work correctly.[1]

While it's certainly possible that there's additional, likely older, browsers with broken `URL.createObjectURL` support, the last time that these types of problems were reported was over *three* years ago.[2]
Hence in the *very* unlikely event that additional problems occur, as a result of these changes, we can either add a new case in the compatibility-code or simply declare the affected browser as unsupported.

---
[1] Which are IE11 (see issue 3977), and Google Chrome on iOS (see PR 8081).

[2] Given that `URL.createObjectURL` is used by default, you'd really expect more reports if these problems were widespread.
2020-08-10 15:56:30 +02:00
Jonas Jenwald
97d796e372 Do the AppOptions.get("printResolution") lookup once in web/app.js, when initializing PDFPrintServiceFactory-instances, rather than for every printed page
There's really no point in repeating these lookups over and over, since the value should be constant for the duration of one print invocation anyway.
2020-08-05 13:34:09 +02:00
Tim van der Meij
81ae565d8a
Revert "Populate the find field with the search query when URL has #search hash"
This reverts commit 50f73092e1. This
causes an inconsistency with the integrated find bar that should be
discussed more before moving on with this (refer to PR #12141).
2020-08-01 00:41:56 +02:00
Phillip Johnsen
50f73092e1 Populate the find field with the search query when URL has #search hash
These changes improves the existing search functionality triggered when
the URL contains a `#search` hash.

In addition to performing the actual search immediately like before,
this will ensure the search text field inside the find bar gets
populated with the text currently being searched for.
2020-07-30 10:11:30 +02:00
Jonas Jenwald
1c809c87af Remove a couple of unnecessary PDFJSDev checks from the viewer
- Given the `DefaultExternalServices` implementation, the `PDFViewerApplication.supportsDocumentFonts` getter is guaranteed to be defined and we can thus remove some (now) unnecessary `PDFJSDev` checks from the `webViewerInitialized` function.
 - By slightly tweaking the "pdfBugEnabled" definition in `web/app_options`, similar to the existing ones for "workerSrc" and "cMapUrl", we can remove some `PDFJSDev` checks from the `PDFViewerApplication._parseHashParameters` method.
2020-07-23 18:24:11 +02:00
Jonas Jenwald
f9157ec243 Unconditionally report telemetry, in the viewer, regardless of build target
Given the dummy-methods on `DefaultExternalServices`, there's no longer any compelling reason not to (attempt to) report telemetry unconditionally.

The only larger change consists of moving the `KNOWN_VERSIONS` and `KNOWN_GENERATORS` arrays ouf of the `PDFViewerApplication._initializeMetadata` method.

*Please note:* Most of this patch consists of whitespace-only changes.
2020-07-08 16:05:25 +02:00
Jonas Jenwald
625f8a6f51 Refactor/simplify the "delayedFallback" handling in the default viewer
There's a few things that could be improved in the current implementation, such as:
 - It's currently necessary to *both* manually track the `featureId`s which should trigger delayed fallback, as well as manually report telemetry in affected cases.
Obviously there's only two call-sites as of now (forms and javaScript), but it still feels somewhat error-prone especially if more cases were to be added in the future. To address this, this patch adds a new (private) method which abstracts away these details from the call-sites.

 - Generally, it also seems nice to reduce *and* simplify the amount of state we need to store on `PDFViewerApplication` in order to support the "delayedFallback" functionality.
Also, having to *manually* work with the "delayedFallback"-array in multiple places feels cumbersome and makes e.g. the `PDFViewerApplication.fallback` method less clear as to its behaviour.

 - Having code *outside* of `PDFViewerApplication`, i.e. in the event handlers, directly access properties which are marked as "private" via a leading underscore doesn't seem that great in general.
Furthermore, having the event handlers directly deal with that should be internal state also seem unfortunate. To address this, the patch will instead make use of a new `PDFViewerApplication.triggerDelayedFallback` callback.

 - There's at least one code-path in the viewer, see `PDFViewerApplication.error`, where `fallback` can be called without an argument.
It's currently possible (although maybe somewhat unlikely) that such a call *could* be overridden by the `featureId` of a pending "delayedFallback" call, thus not reporting the *correct* fallback reason.

 - The "delayedFallback"-state weren't being reset on document close (which shouldn't affect Firefox, but nonetheless it ought to be fixed).
2020-07-08 15:30:07 +02:00
Emma Malysz
05fe9c85b6 For #11961: collect telemetry on all unique unsupported features that trigger fallback error.
This expands upon the telemetry we are collecting that shows the fallback error.
2020-06-11 15:12:51 -07:00
Emma Malysz
6e9d158a98 For #11838: trigger fallback bar after user clicks in pdf 2020-06-03 14:03:46 -07:00
Jonas Jenwald
18e0b10d3c [api-minor] Remove the disableCreateObjectURL option from the getDocument parameters, since it's now unused in the API
With the changes in previous patches, the `disableCreateObjectURL` option/functionality is no longer used for anything in the API and/or in the Worker code.

Note however that there's some functionality, mainly related to file loading/downloading, in the GENERIC version of the default viewer which still depends on this option.
Hence the `disableCreateObjectURL` option (and related compatibility code) is moved into the viewer, see e.g. `web/app_options.js`, such that it's still available in the default viewer.
2020-05-22 00:22:48 +02:00
Jonas Jenwald
8d56a69e74 Reduce usage of SystemJS, in the development viewer, even further
With these changes SystemJS is now only used, during development, on the worker-thread and in the unit/font-tests, since Firefox is currently missing support for worker modules; please see https://bugzilla.mozilla.org/show_bug.cgi?id=1247687

Hence all the JavaScript files in the `web/` and `src/display/` folders are now loaded *natively* by the browser (during development) using standard `import` statements/calls, thanks to a nice `import-maps` polyfill.

*Please note:* As soon as https://bugzilla.mozilla.org/show_bug.cgi?id=1247687 is fixed in Firefox, we should be able to remove all traces of SystemJS and thus finally be able to use every possible modern JavaScript feature.
2020-05-20 13:36:52 +02:00
Jonas Jenwald
108258a8f8 [Firefox] Allow PDF attachments to, once again, be opened directly in the browser (bug 1632644)
Apparently the old link format used in MOZCENTRAL-builds, with the blob URL separated from the filename with a `?` character violates the specification; see https://bugzilla.mozilla.org/show_bug.cgi?id=1632644#c5

Obviously just removing the `?`-part of the URL would have worked, but that would also have meant that we'd no longer be able to provide the correct filename when the user attempts to download the opened PDF attachment.
To fix this we'll instead append the filename in the hash-part of the URL, which however required using a *custom* hash-parameter to avoid triggering the fallback "named destination" code-paths in the viewer.

Note that only changing the `web/pdf_attachment_viewer.js` file wasn't sufficient to fix the bug, and we also need to tweak the `webViewerInitialized` function in `web/app.js` since MOZCENTRAL-builds used to ignore *everything* in the URL hash.
This particular code is very old, but changing it *should* be completely safe given that the `PDFViewerApplication.setTitleUsingUrl` method since some time now stores both the original URL (in `this.url`) as well as one without the hash (in `this.baseUrl`). The latter one is already used everywhere where it matters, so this change seem fine to me.

This patch thus restores the original behaviour for PDF attachments in the MOZCENTRAL-build, by once again allowing them to be opened *directly* in the browser without downloading. (The fallback added in PR 11845 is obviously kept, since it seems generally useful to have.)
2020-05-20 12:08:59 +02:00
Jonas Jenwald
744af9eeb8 Enable the ESLint grouped-accessor-pairs rule
This rule complements the existing `accessor-pairs` nicely, and ensures that a getter/setter pair is always consistently ordered.

Please find additional details about this rule at https://eslint.org/docs/rules/grouped-accessor-pairs
2020-05-07 11:43:19 +02:00
Tim van der Meij
b6f69d47b6
Merge pull request #11834 from xelan/feature/preserve-error-types
Preserve error types during translation
2020-04-28 23:47:24 +02:00
Andreas Erhard
f5fd24a61f Preserve error types during translation
By preserving the exception type, more fine-grained error handling can be performed via client-side logic (e.g. redirect to a search page if a PDF is not found, or to a ticket system in case of invalid PDF files).

The original exception is now re-thrown.

Fixes #11658
2020-04-28 09:36:30 +02:00
Tim van der Meij
571f287983
Merge pull request #11825 from Snuffleupagus/extensions-viewer-less-AppOptions-lookup
Avoid reading the "disablePreferences"/"locale" options, when initializing the viewer, in extension builds
2020-04-21 23:31:52 +02:00
Jonas Jenwald
5733d9dd24 Add a new "openfile" keyboard shortcut (Ctrl+O), in GENERIC builds
Somewhat surprisingly, despite the GENERIC viewer implementing "openfile" support, there's never been a keyboard shortcut available. Similar to the previous patch, this utilizes the `EventBus` for consistency with the `Toolbar`/`SecondaryToolbar` buttons.

*Please note:* This patch should NOT be construed as carte blanche to simply convert all of the code in `webViewerKeyDown`, or elsewhere, to make use of the `EventBus` instead of direct function calls.
Any further changes, along the lines in this patch, would need to be evaluated on a case-by-case basis to determine if they are actually wanted, given that many/most existing cases in `webViewerKeyDown` should already be *indirectly* observable through the `EventBus` instance.
2020-04-20 17:15:44 +02:00
Jonas Jenwald
a8a22283c3 Change the "download" keyboard shortcut (Ctrl+S) handling, in GENERIC/CHROME builds, to utilize the EventBus (issue 11657)
This improves the consistency of the "download" handling, in the default viewer, such that the `Toolbar`/`SecondaryToolbar` buttons *and* the keyboard shortcut are now handled in the same way (using the `EventBus`).

Given that the "download" keyboard shortcut handling is limited to GENERIC/CHROME builds and that the issue does raise a valid point about only being able to observe *some* downloads, these changes seem acceptable in this particular case.

Finally the pre-processor condition is adjusted to *explicitly*, rather than implicitly, list the affected build targets.

*Please note:* This patch should NOT be construed as carte blanche to simply convert all of the code in `webViewerKeyDown`, or elsewhere, to make use of the `EventBus` instead of direct function calls.
Any further changes, along the lines in this patch, would need to be evaluated on a case-by-case basis to determine if they are actually wanted, given that many/most existing cases in `webViewerKeyDown` should already be *indirectly* observable through the `EventBus` instance.
2020-04-20 17:11:30 +02:00
Jonas Jenwald
256aae02d2 Avoid reading the "disablePreferences"/"locale" options, when initializing the viewer, in extension builds
These two `AppOptions` are only defined in GENERIC builds, hence it's completely unnecessary to check them in the extension builds (e.g. MOZCENTRAL and CHROME).

Also, simply let the "printResolution" option be defined in all builds since it's being accessed in `web/firefox_print_service.js` as well.
2020-04-20 13:09:33 +02:00
Jonas Jenwald
1cc3dbb694 Enable the dot-notation ESLint rule
*Please note:* These changes were done automatically, using the `gulp lint --fix` command.

This rule is already enabled in mozilla-central, see https://searchfox.org/mozilla-central/rev/567b68b8ff4b6d607ba34a6f1926873d21a7b4d7/tools/lint/eslint/eslint-plugin-mozilla/lib/configs/recommended.js#103-104

The main advantage, besides improved consistency, of this rule is that it reduces the size of the code (by 3 bytes for each case). In the PDF.js code-base there's close to 8000 instances being fixed by the `dot-notation` ESLint rule, which end up reducing the size of even the *built* files significantly; the total size of the `gulp mozcentral` build target changes from `3 247 456` to `3 224 278` bytes, which is a *reduction* of `23 178` bytes (or ~0.7%) for a completely mechanical change.

A large number of these changes affect the (large) lookup tables used on the worker-thread, but given that they are still initialized lazily I don't *think* that the new formatting this patch introduces should undo any of the improvements from PR 6915.

Please find additional details about the ESLint rule at https://eslint.org/docs/rules/dot-notation
2020-04-17 12:24:46 +02:00
Jonas Jenwald
426945b480 Update Prettier to version 2.0
Please note that these changes were done automatically, using `gulp lint --fix`.

Given that the major version number was increased, there's a fair number of (primarily whitespace) changes; please see https://prettier.io/blog/2020/03/21/2.0.0.html
In order to reduce the size of these changes somewhat, this patch maintains the old "arrowParens" style for now (once mozilla-central updates Prettier we can simply choose the same formatting, assuming it will differ here).
2020-04-14 12:28:14 +02:00
Jonas Jenwald
8521f70157 Add a new pdfjs.enablePermissions preference, off by default, to allow the PDF documents to disable copying in the viewer (bug 792816)
*Please note:* Most of the necessary API work was done in PR 10033, and the only remaining thing to do here was to implement it in the viewer.

The new preference should thus allow e.g. enterprise users to disable copying in the viewer, for PDF documents whose permissions specify that.

In order to simplify things the "copy"-permission was implemented using CSS, as suggested in https://bugzilla.mozilla.org/show_bug.cgi?id=792816#c55, which should hopefully suffice.[1]
The advantage of this approach, as opposed to e.g. disabling the `textLayer` completely, is first of all that it ensures that searching still works correctly even in copy-protected documents. Secondly this also greatly simplifies the overall implementation, since it doesn't require a lot of code for something that's disabled by default.

---
[1] As the discussion in the bug shows, this kind of copy-protection is not very strong and is also generally easy to remove/circumvent in various ways. Hence a simple solution, targeting "regular"-users rather than "power"-users is hopefully deemed acceptable here.
2020-04-08 18:20:47 +02:00
Jonas Jenwald
2d46230d23 [api-minor] Change Font.exportData to, by default, stop exporting properties which are completely unused on the main-thread and/or in the API (PR 11773 follow-up)
For years now, the `Font.exportData` method has (because of its previous implementation) been exporting many properties despite them being completely unused on the main-thread and/or in the API.
This is unfortunate, since among those properties there's a number of potentially very large data-structures, containing e.g. Arrays and Objects, which thus have to be first structured cloned and then stored on the main-thread.

With the changes in this patch, we'll thus by default save memory for *every* `Font` instance created (there can be a lot in longer documents). The memory savings obviously depends a lot on the actual font data, but some approximate figures are: For non-embedded fonts it can save a couple of kilobytes, for simple embedded fonts a handful of kilobytes, and for composite fonts the size of this auxiliary can even be larger than the actual font program itself.

All-in-all, there's no good reason to keep exporting these properties by default when they're unused. However, since we cannot be sure that every property is unused in custom implementations of the PDF.js library, this patch adds a new `getDocument` option (named `fontExtraProperties`) that still allows access to the following properties:

 - "cMap": An internal data structure, only used with composite fonts and never really intended to be exposed on the main-thread and/or in the API.
   Note also that the `CMap`/`IdentityCMap` classes are a lot more complex than simple Objects, but only their "internal" properties survive the structured cloning used to send data to the main-thread. Given that CMaps can often be *very* large, not exporting them can also save a fair bit of memory.

 - "defaultEncoding": An internal property used with simple fonts, and used when building the glyph mapping on the worker-thread. Considering how complex that topic is, and given that not all font types are handled identically, exposing this on the main-thread and/or in the API most likely isn't useful.

 - "differences": An internal property used with simple fonts, and used when building the glyph mapping on the worker-thread. Considering how complex that topic is, and given that not all font types are handled identically, exposing this on the main-thread and/or in the API most likely isn't useful.

 - "isSymbolicFont": An internal property, used during font parsing and building of the glyph mapping on the worker-thread.

  - "seacMap": An internal map, only potentially used with *some* Type1/CFF fonts and never intended to be exposed in the API. The existing `Font.{charToGlyph, charToGlyphs}` functionality already takes this data into account when handling text.

 - "toFontChar": The glyph map, necessary for mapping characters to glyphs in the font, which is built upon the various encoding information contained in the font dictionary and/or font program. This is not directly used on the main-thread and/or in the API.

 - "toUnicode": The unicode map, necessary for text-extraction to work correctly, which is built upon the ToUnicode/CMap information contained in the font dictionary, but not directly used on the main-thread and/or in the API.

 - "vmetrics": An array of width data used with fonts which are composite *and* vertical, but not directly used on the main-thread and/or in the API.

 - "widths": An array of width data used with most fonts, but not directly used on the main-thread and/or in the API.
2020-04-06 11:47:09 +02:00
Jonas Jenwald
9ef58347ed A couple of small improvements of the PDFViewerApplication.{_initializeMetadata, _initializePdfHistory} methods
- Use template strings when printing document/viewer information in `_initializeMetadata`, since the old format feels overly verbose.
   Also, get the WebGL state from the `BaseViewer` instance[1] rather than the `AppOptions`. Since the `AppOptions` value could theoretically have been changed (by the user) after the viewer components were initialized, it seems much more useful to print the *actual* value that'll be used during rendering.

 - Change `_initializePdfHistory` to actually do the "is embedded"-check first, in accordance with the comment and given that the "disableHistory" option usually shouldn't be set.

---
[1] Admittedly reaching into the `BaseViewer` instance and just grabbing the value perhaps isn't a great approach overall, but given that the WebGL-backend isn't even on by default this probably doesn't matter too much.
2020-04-05 15:41:00 +02:00
Jonas Jenwald
b9add65099 Move the initialization of "auto print" out of PDFViewerApplication.load
Over time, with more and more API-functionality added, the `PDFViewerApplication.load` method has become quite large and complex. In an attempt to improve the current situation somewhat, this patch moves the fetching and initialization of "auto print" out into its own (private) helper method instead.
2020-04-05 15:41:00 +02:00
Jonas Jenwald
d07be1a89b Move the initialization of "metadata" out of PDFViewerApplication.load
Over time, with more and more API-functionality added, the `PDFViewerApplication.load` method has become quite large and complex. In an attempt to improve the current situation somewhat, this patch moves the fetching and initialization of "metadata" out into its own (private) helper method instead.
2020-04-05 15:41:00 +02:00
Jonas Jenwald
32f1d0de76 Move the initialization of "page labels" out of PDFViewerApplication.load
Over time, with more and more API-functionality added, the `PDFViewerApplication.load` method has become quite large and complex. In an attempt to improve the current situation somewhat, this patch moves the fetching and initialization of "page labels" out into its own (private) helper method instead.
2020-04-05 15:41:00 +02:00
Jonas Jenwald
664b79abe0 [api-minor] Remove the eventBusDispatchToDOM option/preference, and thus the general ability to dispatch "viewer components" events to the DOM
This functionality was only added to the default viewer for backwards compatibility and to support the various PDF viewer tests in mozilla-central, with the intention to eventually remove it completely.
While the different mozilla-central tests cannot be *easily* converted from DOM events, it's however possible to limit that functionality to only MOZCENTRAL builds *and* when tests are running.

Rather than depending of the re-dispatching of internal events to the DOM, the default viewer can instead be used in e.g. the following way:
```javascript
document.addEventListener("webviewerloaded", function() {
  PDFViewerApplication.initializedPromise.then(function() {
    // The viewer has now been initialized, and its properties can be accessed.

    PDFViewerApplication.eventBus.on("pagerendered", function(event) {
      console.log("Has rendered page number: " + event.pageNumber);
    });
  });
});
```
2020-03-29 12:24:46 +02:00
gdh1995
a527eb8c92 Add passive: false when removing wheel listeners
Code of listening `wheel` event uses `{passive: false}`,
while this argument will be treated as `true` before Firefox 49,
accordin to https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Browser_compatibility .

This commit adds it when removing wheel listeners,
so that such listeners can be really removed.
2020-03-25 22:42:27 +08:00
Jonas Jenwald
9f70bca12c Re-factor PDFViewerApplication.load such that {PDFViewer, PDFThumbnailViewer}.setDocument happens slightly earlier
The `BaseViewer.setDocument` method in particular is necessary for rendering to start when the viewer loads, hence you obviously want that to happen as soon as possible and without any unnecessary delays.
Unfortunately *some* API calls need to be done before that, note existing comments, however the `ViewHistory` initialization (and subsequent fetching of data) in particular can be moved slightly without any adverse effects.

As part of testing I've used logging with `performance.now()` inserted in various parts of this code, and there's *obviously* no discernible changes between `master` and this patch for e.g. rendering starting in the viewer.

*Note:* The vast majority of this patch is simple indentation changes, which were forced by Prettier (and done automatically with `gulp lint --fix`).
2020-03-22 10:21:05 +01:00
Jonas Jenwald
300a663458 Move the webViewerOpenFile function, and the "openfile" eventBus listener, since they only matter in GENERIC builds of the default viewer
This is similar to the existing implementation of the `webViewerFileInputChange` function and its associated "fileinputchange" event.
2020-03-17 13:30:38 +01:00
Jonas Jenwald
b3d7d1c614 Ensure that the JavaScript-warning is always displayed, in the viewer, regardless of browser printing support
The viewer doesn't currently support executing of any JavaScript, as found in some PDF documents, for security reasons. (Although there's a small hack to at least provide basic support for automatic printing on document load, without running scripts.)

However, in the event that the browser doesn't support printing we're not run *any* of this code. In particular that means that we're also not displaying the "Warning: JavaScript is not supported" message, which seems strange since JavaScript found in a PDF document can really contain *anything* (and not only printing instructions).

It thus seem reasonable, as far as I'm concerned, to always display the JavaScript-warning *even* if printing happens to be unsupported.
2020-03-15 14:41:13 +01:00
Tim van der Meij
aa3e5a2b8f
Merge pull request #11644 from Snuffleupagus/openAction
[api-minor] Add more general OpenAction support (PR 10334 follow-up, issue 11642)
2020-03-15 13:16:37 +01:00
Jonas Jenwald
886b256ada Remove variable shadowing from the JavaScript files in the web/ folder
*This is part of a series of patches that will try to split PR 11566 into smaller chunks, to make reviewing more feasible.*

Once all the code has been fixed, we'll be able to eventually enable the ESLint `no-shadow` rule; see https://eslint.org/docs/rules/no-shadow
2020-03-13 12:59:58 +01:00
Jonas Jenwald
1fac29d184 Slightly improve the BaseViewer.{firstPagePromise, onePageRendered, pagesPromise} functionality
There's a couple of issues with this functionality:
 - The respective `PromiseCapability` instances are not being reset, in `BaseViewer._resetView`, when the document is closed which is inconsistent with all other state.
 - While the default viewer depends on these promises, and they thus ought to be considered part of e.g. the `PDFViewer` API-surface, they're not really defined in a particularily user-visible way (being that they're attached to the `BaseViewer` instance *inline* in `BaseViewer.setDocument`).
 - There's some internal `BaseViewer` state, e.g. `BaseViewer._pageViewsReady`, which is tracked manually and could instead be tracked indirectly via the relevant `PromiseCapability`, thus reducing the need to track state *twice* since that's always best to avoid.

*Please note:* In the existing implementation, these promises are not defined *until* the `BaseViewer.setDocument` method has been called.
While it would've been simple to lift that restriction in this patch, I'm purposely choosing *not* to do so since this ensures that any Promise handlers added inside of `BaseViewer.setDocument` are always invoked *before* any external ones (and keeping that behaviour seems generally reasonable).
2020-03-08 09:23:44 +01:00
Jiwon Jeon
df22dfb531 Fix typo 2020-03-07 12:37:22 +09:00
Jonas Jenwald
01fb309a2a [api-minor] Add more general OpenAction support (PR 10334 follow-up, issue 11642)
This patch deprecates the existing `getOpenActionDestination` API method, in favor of a better and more general `getOpenAction` method instead. (For now JavaScript actions, related to printing, are still handled as before.)

By clearly separating "regular" Print actions from the JavaScript handling, it's thus possible to get rid of the somewhat annoying and strictly incorrect warning when the viewer loads.
2020-03-06 13:03:00 +01:00
Tim van der Meij
52749d1f0d
Merge pull request #11631 from Snuffleupagus/getGlobalEventBus-deprecate
[api-minor] Deprecate `getGlobalEventBus` and update the "viewer components" examples accordingly
2020-03-02 23:30:07 +01:00
Jonas Jenwald
4a1b056c82 Re-factor the EventBus to allow servicing of "external" event listeners *after* the viewer components have updated
Since the goal has always been, essentially since the `EventBus` abstraction was added, to remove all dispatching of DOM events[1] from the viewer components this patch tries to address one thing that came up when updating the examples:
The DOM events are always dispatched last, and it's thus guaranteed that all internal event listeners have been invoked first.
However, there's no such guarantees with the general `EventBus` functionality and the order in which event listeners are invoked is *not* specified. With the promotion of the `EventBus` in the examples, over DOM events, it seems like a good idea to at least *try* to keep this ordering invariant[2] intact.

Obviously this won't prevent anyone from manually calling the new *internal* viewer component methods on the `EventBus`, but hopefully that won't be too common since any existing third-party code would obviously use the `on`/`off` methods and that all of the examples shows the *correct* usage (which should be similarily documented on the "Third party viewer usage" Wiki-page).

---
[1] Looking at the various Firefox-tests, I'm not sure that it'll be possible to (easily) re-write all of them to not rely on DOM events (since getting access to `PDFViewerApplication` might be generally difficult/messy depending on scopes).
In any case, even if technically feasible, it would most likely add *a lot* of complication that may not be desireable in the various Firefox-tests. All-in-all, I'd be fine with keeping the DOM events only for the `MOZCENTRAL` target and gated on `Cu.isInAutomation` (or similar) rather than a preference.

[2] I wouldn't expect any *real* bugs in a custom implementation, simply based on event ordering, but it nonetheless seem like a good idea if any "external" events are still handled last.
2020-02-27 19:38:13 +01:00
Jonas Jenwald
9a437a158f [api-minor] Deprecate getGlobalEventBus and update the "viewer components" examples accordingly
To avoid outright breaking third-party usages of the "viewer components" the `getGlobalEventBus` functionality is left intact, but a deprecation message is printed if the function is invoked.

The various examples are updated to *explicitly* initialize an `EventBus` instance, and provide that when initializing the relevant viewer components.
2020-02-27 14:44:48 +01:00
Jonas Jenwald
03f5dd2cf2 Add a ignoreDestinationZoom option/preference to allow users to preserve the current zoom level when navigating to internal destinations (issue 5064, 11606) 2020-02-27 08:42:50 +01:00
Jonas Jenwald
44587f3459 Add a PDFViewerApplication.initializedPromise property to allow (easier) tracking of when the default viewer has been initialized
This complements the existing `PDFViewerApplication.initialized` boolean property, and may be helpful for custom implementations of the default viewer. This will thus provide users of the default viewer an alternative to setting the preference to dispatch events to the DOM (and listen for the "localized" event), since they can instead use:
```javascript
document.addEventListener("webviewerloaded", function() {
  PDFViewerApplication.initializedPromise.then(function() {
    // The viewer has now been initialized.
  })
});
```

Note that in order to avoid manually tracking the initialization state *twice*, this implementation purposely uses the `PromiseCapability` functionality to handle both `PDFViewerApplication.initialized` and `PDFViewerApplication.initializedPromise` internally.
2020-02-17 14:14:56 +01:00
Jonas Jenwald
a12f78154c Use the native URL.createObjectURL method in web/debugger.js
There's no particular reason for using the PDF.js helper function `createObjectURL`[1] in the debugger, instead of the native `URL.createObjectURL` directly, for a couple of reasons:
 - The relevant code-path only applies to fonts loaded with the Font Loading API, and this isn't supported in IE anyway.
 - The debugger can, since quite some time, not even be loaded in IE any more.
 - General support for IE is now limited, and there's no guaratee that everything actually works.

---
[1] It provides a fallback for browsers with broken `Blob` support, which as usual means Internet Explorer :-P
2020-01-28 21:21:08 +01:00
Tim van der Meij
d2d9441373
Merge pull request #11489 from Snuffleupagus/rm-FIREFOX-define
Remove the `FIREFOX` build flag, since it's completely unused and simplify a couple of `PDFJSDev` checks
2020-01-24 23:59:13 +01:00
Jonas Jenwald
9a6ee1b7f2 Remove the "useOnlyCssZoom" (debugging) hash parameter
The debugging hash parameters[1] are intended to facilitate access to various tools/settings in PRODUCTION builds, protected by the `pdfBugEnabled` preference.
At this point, the remaining debugging hash parameters are mainly intended to allow access to the `PDFBug` tools and/or to quickly toggle certain larger features.

The "useOnlyCssZoom" functionality doesn't really seem to fit in with the rest of these hash parameters, since:
 - This is, comparatively speaking, a minor viewer-specific feature.
 - The zooming implementation will (almost) always fallback to CSS-only zooming, for any document, once the canvases becomes large enough. Hence, the majority of the CSS zooming feature can still be tested *directly* in any build of the viewer.
 - After the initial implementation, years ago, the CSS-only zooming code in question hasn't changed much (or even at all), i.e. it doesn't seem like an active development target.[2]
 - If the "useOnlyCssZoom" functionality was added today, it's unlikely that a hash parameter would've been added.
 - Last, but not least, there's also a `useOnlyCssZoom` preference hence toggling this functionality shouldn't be too difficult (e.g. if someone needs to hack on it).

All in all, I'm thus suggesting that we remove the "useOnlyCssZoom" hash parameter.

---
[1] Originally these hash parameters could be used directly in any build, which was bad since it would allow any link to potentially disable functionality and/or reduce performance.

[2] If it had seen active development over the years, I'd be *much* more inclined to keep the hash parameter.
2020-01-23 15:49:58 +01:00
Jonas Jenwald
0f3e87911f Return early in PDFViewerApplication._parseHashParameters when the hash is empty
For people running e.g. Firefox with the `pdfBugEnabled` preference set, to allow quick access to debugging tools, this method will obviously run for every opened PDF file. However, in most cases the URL hash is empty and we can thus skip most of the parsing and simply return early instead.
2020-01-23 12:05:43 +01:00
Jonas Jenwald
a39943554a Simplify, and tweak, a couple of PDFJSDev checks
This removes a couple of, thanks to preceeding code, unnecessary `typeof PDFJSDev` checks, and also fixes a couple of incorrectly implemented (my fault) checks intended for `TESTING` builds.
2020-01-21 00:06:15 +01:00
Jonas Jenwald
7322a24ce4 Remove the FIREFOX build flag, since it's completely unused
After PR 9566, which removed all of the old Firefox extension code, the `FIREFOX` build flag is no longer used for anything.
It thus seems to me that it should be removed, for a couple of reasons:
 - It's simply dead code now, which only serves to add confusion when looking at the `PDFJSDev` calls.
 - It used to be that `MOZCENTRAL` and `FIREFOX` was *almost* always used together. However, ever since PR 9566 there's obviously been no effort put into keeping the `FIREFOX` build flags up to date.
 - In the event that a new, Webextension based, Firefox addon is created in the future you'd still need to audit all `MOZCENTRAL` (and possibly `CHROME`) build flags to see what'd make sense for the addon.
2020-01-21 00:06:15 +01:00
Jonas Jenwald
f171d99799 Ensure that the viewer telemetry reporting, and fallback code, runs in development mode and GENERIC builds
While only the `MOZCENTRAL` builds will actually do anything meaningful with the telemetry data, none of the code in question actually runs *at all* in e.g. development mode.[1]
This seems bad since it essentially means that this code is completely untested, despite being quite important for the built-in Firefox PDF viewer, and this thus ought to be fixed.

In this case, the explanation for the current state of the code should be "for historical reasons". Before the viewer was split into the current components and before the pre-processor was improved, back when all code resided in the `web/viewer.js` file, the telemetry reporting was done with *direct* `FirefoxCom` calls. However, with the dummy `DefaultExternalServices.reportTelemetry` method there's nothing actually preventing attempting to report telemetry in any type of build.

NOTE: By running this code in GENERIC builds as well, in addition to just locally, the *viewer* part of telemetry reporting becomes tested e.g. in preview builds too which should help with reviewing.

---
[1] When fixing bug 1606566, I had to edit the relevant `PDFJSDev` checks to be able to actually test the changes locally.
2020-01-20 11:46:38 +01:00
Jonas Jenwald
a977882f54 Remove the supportsDocumentColors warning in MOZCENTRAL builds (bug 844349 follow-up)
With https://bugzilla.mozilla.org/show_bug.cgi?id=844349 now being fixed in Firefox, the textLayer will now actually stay hidden as intended regardless of the browser settings.
Hence it should no longer be necessary to display the fallback bar, nor print a warning in the console, for documents which contains a textLayer.

Besides removing the `supportsDocumentColors` methods in the default viewer, we can also remove a now unused l10n string.
2020-01-19 14:49:26 +01:00
Jonas Jenwald
1b87b1c384 Re-factor the various ExternalServices, used in the default viewer, to classes with static methods
This seems nicer overall, since it's now a bit clearer that the various build targets *extend* the default implementation.
2020-01-15 14:26:47 +01:00
Jonas Jenwald
1ceffac9c5 Enable the no-nested-ternary ESLint rule in the web/ directory
This rule is already enabled in mozilla-central, and helps avoid some confusing formatting[1], see https://searchfox.org/mozilla-central/rev/a92ed79b0bc746159fc31af1586adbfa9e45e264/tools/lint/eslint/eslint-plugin-mozilla/lib/configs/recommended.js#209-210

Since some cases may not be aren't entirely straightforward to convert, and some we probably don't want to change either[2], this patch is limited to the `web/` directory as a proof-of-concept.

Please find additional details about the ESLint rule at https://eslint.org/docs/rules/no-nested-ternary

---
[1] One example with *three* ternary statements: 93aa613db7/src/core/fonts.js (L2623-L2630)

[2] One example that should be whitelisted: 93aa613db7/src/core/jbig2.js (L82-L92)
2020-01-08 11:56:10 +01:00
Tim van der Meij
93aa613db7
Merge pull request #11465 from Snuffleupagus/import-file-extension
Ensure that all `import` and `require` statements, in the entire code-base, have a `.js` file extension
2020-01-06 23:24:43 +01:00
Jonas Jenwald
36881e3770 Ensure that all import and require statements, in the entire code-base, have a .js file extension
In order to eventually get rid of SystemJS and start using native `import`s instead, we'll need to provide "complete" file identifiers since otherwise there'll be MIME type errors when attempting to use `import`.
2020-01-04 13:01:43 +01:00
Jonas Jenwald
299ba44bb9 [Firefox] Slightly simplify how the generator is determined, when sending telemetry data from the viewer
When working on PR 11463 I couldn't help thinking that the `Array.prototype.some` callback function, used when determining the generator, was somewhat difficult to read with its partly unused and strangely named parameters.
2020-01-02 23:29:00 +01:00
Jonas Jenwald
bee941b0d2 [Firefox] Ensure that telemetry will be correctly recorded even when the PDF header is missing (bug 1606566)
As suggested in the bug we'll now always fallback to "other", which should be fine considering that that value is listed in the histogram definition; see https://searchfox.org/mozilla-central/rev/331f0c3b25089c9a16be65f4dc8c601aeaac8cc4/toolkit/components/telemetry/Histograms.json#9097-9106

Fixes https://bugzilla.mozilla.org/show_bug.cgi?id=1606566
2020-01-01 22:23:11 +01:00
Jonas Jenwald
d9a5d50664 Fix remaining linting errors, from enabling the prefer-const ESLint rule in the web/ directory
This covers the handful of cases that the `--fix` command couldn't deal with, and the changes aren't just fixing the linting errors but attempt to slightly improve the relevant code.
2019-12-27 01:03:58 +01:00
Jonas Jenwald
5d14e68bec Enable the ESLint prefer-const rule in the web/ directory
Please find additional details about the ESLint rule at https://eslint.org/docs/rules/prefer-const

Note that this patch is generated automatically, by using the ESLint `--fix` argument, and will thus require some additional clean-up (which is done separately).
2019-12-27 01:03:58 +01:00
Jonas Jenwald
d9d856020f Move the regular expression, used with auto printing in the viewer, to web/ui_utils.js and also use it in the API unit-tests
Rather than having a copy of this regular expression in the `test/unit/api_spec.js` file, with a comment about keeping it up-to-date with the code in the viewer (note the incorrect file reference as well), we can just import it instead to simplify all of this.
2019-12-27 00:38:28 +01:00
Jonas Jenwald
a63f7ad486 Fix the linting errors, from the Prettier auto-formatting, that ESLint --fix couldn't handle
This patch makes the follow changes:
 - Remove no longer necessary inline `// eslint-disable-...` comments.
 - Fix `// eslint-disable-...` comments that Prettier moved down, thus causing new linting errors.
 - Concatenate strings which now fit on just one line.
 - Fix comments that are now too long.
 - Finally, and most importantly, adjust comments that Prettier moved down, since the new positions often is confusing or outright wrong.
2019-12-26 12:35:12 +01:00
Jonas Jenwald
de36b2aaba Enable auto-formatting of the entire code-base using Prettier (issue 11444)
Note that Prettier, purposely, has only limited [configuration options](https://prettier.io/docs/en/options.html). The configuration file is based on [the one in `mozilla central`](https://searchfox.org/mozilla-central/source/.prettierrc) with just a few additions (to avoid future breakage if the defaults ever changes).

Prettier is being used for a couple of reasons:

 - To be consistent with `mozilla-central`, where Prettier is already in use across the tree.

 - To ensure a *consistent* coding style everywhere, which is automatically enforced during linting (since Prettier is used as an ESLint plugin). This thus ends "all" formatting disussions once and for all, removing the need for review comments on most stylistic matters.

Many ESLint options are now redundant, and I've tried my best to remove all the now unnecessary options (but I may have missed some).
Note also that since Prettier considers the `printWidth` option as a guide, rather than a hard rule, this patch resorts to a small hack in the ESLint config to ensure that *comments* won't become too long.

*Please note:* This patch is generated automatically, by appending the `--fix` argument to the ESLint call used in the `gulp lint` task. It will thus require some additional clean-up, which will be done in a *separate* commit.

(On a more personal note, I'll readily admit that some of the changes Prettier makes are *extremely* ugly. However, in the name of consistency we'll probably have to live with that.)
2019-12-26 12:34:24 +01:00
Jonas Jenwald
ad0b0d60a5 Ignore Metadata entries with incorrectly encoded characters, when setting the viewer title (bug 1605526)
Apparently Ghostscript can, in some cases, generate/include `Metadata` with incorrectly encoded characters.[1] This results in the viewer title looking wrong, which we thus attempt to avoid by falling back to the `Info` entry instead.

*Please note:* Obviously it would be better if this was fixed in the `Metadata` parser instead, rather than using a viewer work-around, but I'm just not sure how or even *if* that could actually be done given that the `Metadata` stream contains no trace of the *original* character.

Fixes https://bugzilla.mozilla.org/show_bug.cgi?id=1605526

---
[1] The problematic characters are from the Specials Unicode block, see https://en.wikipedia.org/wiki/Specials_(Unicode_block)
2019-12-22 17:20:14 +01:00
Jonas Jenwald
eeaea85294 Re-factor how the viewer title is determined, based on the Info/Metadata data
With these changes we'll always set the `pdfTitle` to the `Info` dictionary entry *first* (assuming it exists and isn't empty), before attempting to override it with the `Metadata` stream entry (assuming it exists, is non-empty *and* valid).

There should be no functional changes with this patch, but it will simplify the following patch somewhat.
2019-12-21 18:59:17 +01:00
Jonas Jenwald
8519f87efb Re-factor the setupFakeWorkerGlobal function (in src/display/api.js), and the loadFakeWorker function (in web/app.js)
This patch reduces some duplication, by moving *all* fake worker loader code into the `setupFakeWorkerGlobal` function. Furthermore, the functions are simplified further by using `async`/`await` where appropriate.
2019-12-20 17:36:10 +01:00
Jonas Jenwald
d621899d50 Add a reset method to the PDFHistory implementation
This patch addresses a couple of smaller issues with the `PDFHistory` class:
 - Most, if not all, other viewer components can be reset in one way or another, and there's no good reason for the `PDFHistory` implementation to be different here.

 - Currently it's (technically) possible to keep adding entries to the browser history, via the `PDFHistory` instance, even after the document has been closed. That obviously makes no sense, and is caused by the lack of a `reset` method.

 - The internal `this._isPagesLoaded` property was never actually reset, which would lead to it being temporarily wrong when a new document was opened in the default viewer.
2019-12-13 10:38:39 +01:00
Jonas Jenwald
1c466b4648 Remove the viewer option from the PDFPresentationMode constructor
The `viewer` option was *only* used for checking that a document is loaded in `PDFPresentationMode.request`, however that's just as easy to do by simply utilizing `BaseViewer.pagesCount` instead and this way we can also avoid the DOM lookup.
2019-12-06 00:20:56 +01:00
Jonas Jenwald
eedd449cb4 Remove some unused require statements, used when loading fake workers, in non-PRODUCTION mode
The code in question is *only* relevant in non-`PRODUCTION` mode, i.e. the *development* version of the viewer run with `gulp server`, and has been completely unused at least since SystemJS was added.
I really cannot see any reason to keep this, since it's code which first of all isn't shipping and secondly isn't even being used in the development viewer.
2019-10-31 12:08:07 +01:00
Jonas Jenwald
d67a5d395c Avoid handling keyboard shortcuts for contentEditable DOM elements (issue 7156)
The issue has been open for years now, and has even been marked with `5-good-beginner-bug` for *months*, without any movement.
Considering just how simple the suggested solution is, I'm submitting this patch just to close out a long-standing issue.
2019-10-16 16:50:43 +02:00
Tim van der Meij
f4daafc077
Consistently use square brackets for optional parameters in JSDoc comments
Square brackets are recommended to indicate optional parameters. Using
them helps for automatically generating correct documentation.
2019-10-13 13:58:17 +02:00
Tim van der Meij
efd331daa1
Consistently use string for string data types in JSDoc comments
Sometimes we also used `String`, but `string` is the what the JSDoc
documentation recommends.
2019-10-13 13:58:17 +02:00
Tim van der Meij
1f5ebfbf0c
Replace our URL polyfill with the one from core-js
`core-js` polyfills have proven to be of good quality and using them
prevents us from having to maintain them ourselves.
2019-09-19 14:09:51 +02:00
Jonas Jenwald
e7baf2ab61 Prevent "offsetParent is not set -- cannot scroll" errors when the viewer loads in e.g. a hidden <iframe>
Besides avoiding errors during loading, this also ensures that the document will be correctly scrolled/zoomed into view once the viewer becomes visible.
This "new" behaviour was always intended, see PR 2613, however various re-factoring over the years seem to have broken this (and I'm probably at least somewhat responsible for that).
2019-09-08 14:13:50 +02:00
Priestch
000780d27e Use shorthand method signature for afterPrint in web/app.js 2019-08-24 18:26:25 +08:00
Brendan Dahl
98e989116c Add a way to disable external links. 2019-08-21 11:20:41 -07:00
Jonas Jenwald
446ce88f81 Remove the non-PRODUCTION only 'disablebcmaps' hash parameter
This was added in PR 4470, but doesn't appear to have been used since.
While it's certainly easy to understand how this was helpful during development of that PR, actually providing this hash parameter isn't going to work anymore given that the original CMap files were also removed from the repository.

I suppose that the hash parameter *could* be useful if you'd attempt to update the BCMap files, however that hasn't been attempted even once in over *five* years time. Furthermore, at this point using the `AppOptions` directly in that situation should also work fine.

All in all, this seems like a piece of old and unused code which we can simply remove now.
2019-08-10 15:40:33 +02:00
Jonas Jenwald
04a3dc65e4 Move the sidebar toggleButton event listener into PDFSidebar
This is consistent with other functionality, such as e.g. `SecondaryToolbar` and `PDFFindBar`.
2019-08-10 15:38:33 +02:00
Brendan Dahl
47077f8de9 Add page rendered timestamp to telemetry. 2019-08-06 09:46:33 -07:00
Tim van der Meij
e0b38bed3c
Merge pull request #11029 from brendandahl/pdfjs-telemetry-update
[api-minor] Update telemetry to use 'categorical' histograms.
2019-08-02 00:11:02 +02:00
Brendan Dahl
31d71808e7 [api-minor] Update telemetry to use 'categorical' histograms.
Firefox telemetry supports using string labels now. Convert our integers
that we used for categories to just use strings.

The upstream work will happen in:
https://bugzilla.mozilla.org/show_bug.cgi?id=1566882
2019-08-01 09:51:02 -07:00
Tim van der Meij
9b72089886
Merge pull request #11003 from Snuffleupagus/webViewerWheel-supportedKeys
Ensure that setting the `zoomDisabledTimeout` isn't skipped, regardless of the supported zoom keys, when handling mouse wheel events (PR 7097 follow-up)
2019-07-23 22:28:36 +02:00
Jonas Jenwald
1eed5b7235 Ensure that setting the zoomDisabledTimeout isn't skipped, regardless of the supported zoom keys, when handling mouse wheel events (PR 7097 follow-up)
*Possible follow-up:* It probably wouldn't hurt to try and shorten the `supportedMouseWheelZoomModifierKeys` name a bit, but I'm not attempting that here since it'd also require updating `PdfStreamConverter.jsm` in mozilla-central in order to be consistent.
2019-07-23 17:42:12 +02:00
Jonas Jenwald
46b61ff12e Avoid creating a PDFFindBar instance, in the Firefox built-in viewer, when not actually necessary
This is similar to how `PDFPresentationMode` isn't used when the Fullscreen API isn't supported.
2019-07-23 07:51:14 +02:00
Jonas Jenwald
53a854bb0a Remove an unnecessary PDFDocumentProperties.setFileSize call, relevant for the Firefox built-in viewer, and use the "normal" code-path in PDFViewerApplication.open instead
Since calling `getDocument` with a `PDFDataRangeTransport` argument will always unconditionally override a manually provided `length` argument, see a1a667809f/src/display/api.js (L390-L394), this patch should thus be safe.
2019-07-21 11:38:17 +02:00
Jonas Jenwald
ba2c042a75 Add the docBaseUrl API parameter to AppOptions in the viewer
This unfortunately required a bit of special handling, to correctly deal with the various extension builds.
2019-07-20 13:39:34 +02:00
Jonas Jenwald
8e5aa484fb [Firefox] Re-factor the 'zoomreset' message handling in the viewer (PR 10652 follow-up)
Given that this special-case only matters for the Firefox PDF viewer, it's probably better to just move it into `firefoxcom.js` instead to reduce unnecessary confusion.
2019-07-18 14:27:43 +02:00
Jonas Jenwald
19f6facc1e Ensure that PDFViewerApplication.{zoomIn, zoomOut} won't run when PresentationMode is active (PR 10652 follow-up)
Similar to the `zoomReset` method we need to ensure that this code won't run for zoom events originating within the browser UI itself, since checks in e.g. the `keydown` event handler won't help in that case.
2019-07-11 15:41:44 +02:00
Jonas Jenwald
173fbef05b Enable the consistent-return ESLint rule
This rule is already enabled in mozilla-central, and helps ensure more consistent functions/methods, see https://searchfox.org/mozilla-central/rev/b9da45f63cb567244933c77b2c7e827a057d3f9b/tools/lint/eslint/eslint-plugin-mozilla/lib/configs/recommended.js#119-120

Please see https://eslint.org/docs/rules/consistent-return for additional information.
2019-05-11 14:27:21 +02:00
Jonas Jenwald
468bd829f2 Add passive: false to the wheel event listener, to work-around broken default behaviour in Chrome 73 and above (issue 10761)
Let's try this, since it doesn't appear to break scrolling/zooming in IE11.
2019-04-24 17:37:25 +02:00
Jonas Jenwald
7a999d1d67 [api-minor] Add basic support for PageLayout in the API and the viewer
Please see the specification, https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf#G6.2393749, and refer to the inline comments for additional details.
2019-04-05 11:32:01 +02:00
Jonas Jenwald
2e044bf646 Prepare the MOZCENTRAL viewer for receiving zoom events from the browser UI (bug 786674, bug 1177385)
This lays the necessary foundation for handling zoom events originating within the browser itself, rather than in the viewer. Please note that this will also require a follow-up patch to `mozilla-central`, such that the viewer is actually notified when zooming occurs.
2019-03-21 12:42:04 +01:00
Jonas Jenwald
f7cc331654 Add type validation to the default_preferences generation (PR 10548 follow-up)
The generated `default_preferences.json` file is necessary when initializing the Firefox preferences, which only supports certain types, hence this patch adds additional validation to help prevent run-time errors in Firefox.

Given that these changes add a code-path to `AppOptions.getAll` which could throw, the `OptionKind.PREFERENCE` branch is also modified to require *exact* matching to prevent (future) errors in the viewer.

Finally the conditionally defined `defaultOptions` will no longer (potentially) be considered during the `gulp default_preferences` task, to make it more difficult for them to be accidentally included.
2019-03-03 12:51:57 +01:00
Jonas Jenwald
1753f91c6b Re-factor the PDFSidebar constructor to simplify its call-site (PR 10123 follow-up) 2019-02-24 13:15:24 +01:00
Jonas Jenwald
0f0650f426 Generate the default_preferences.json file from AppOptions
Currently any editing of the preferences require updates in *three* separate files, which isn't a great developer experience to say the least.

This has annoyed me sufficiently to write this patch, which moves the definition of all preferences into `AppOptions` and adds a new `gulp` task to generate the `default_preferences.json` file for the builds where it's needed.
2019-02-14 20:40:34 +01:00
Jonas Jenwald
9d8342002c Move the PDFHistory initialization into a helper method in PDFViewerApplication
This avoids having the initialization code "spread out", and will become even simpler once the `TODO` is addressed (which I'm planning on fixing as soon as possible).
2019-02-02 10:21:18 +01:00
Jonas Jenwald
6806248030 Modify a number of the viewer preferences, whose current default value is 0, such that they behave as expected with the view history
The intention with preferences such as `sidebarViewOnLoad`/`scrollModeOnLoad`/`spreadModeOnLoad` were always that they should be able to *unconditionally* override their view history counterparts.
Due to the way that these preferences were initially implemented[1], trying to e.g. force the sidebar to remain hidden on load cannot be guaranteed[2]. The reason for this is the use of "enumeration values" containing zero, which in hindsight was an unfortunate choice on my part.
At this point it's also not as simple as just re-numbering the affected structures, since that would wreak havoc on existing (modified) preferences. The only reasonable solution that I was able to come up with was to change the *default* values of the preferences themselves, but not their actual values or the meaning thereof.

As part of the refactoring, the `disablePageMode` preference was combined with the *adjusted* `sidebarViewOnLoad` one, to hopefully reduce confusion by not tracking related state separately.

Additionally, the `showPreviousViewOnLoad` and `disableOpenActionDestination` preferences were combined into a *new* `viewOnLoad` enumeration preference, to further avoid tracking related state separately.
2019-02-02 10:21:18 +01:00
Jonas Jenwald
86472e9981 Enable the no-useless-catch ESLint rule
See https://eslint.org/docs/rules/no-useless-catch
2019-01-28 11:00:09 +01:00
Jonas Jenwald
9743708a24 Prevent TypeError: views[index] is undefined being throw in getVisibleElements when the viewer, or all pages, are hidden
Previously a couple of different attempts at fixing this problem has been rejected, given how *crucial* this code is for the correct function of the viewer, since no one has thus far provided any evidence that the problem actually affects the default viewer[1] nor an example using the viewer components directly (without another library on top).
The fact that none of the prior patches contained even a *simple* unit-test probably contributed to the unwillingness of a reviewer to sign off on the suggested changes.

However, it turns out that it's possible to create a reduced test-case, using the default viewer, that demonstrates the error[2]. Since this utilizes a hidden `<iframe>`, please note that this error will thus affect Firefox as well.
Note that while errors are thrown when the hidden `<iframe>` loads, the default viewer doesn't break completely since rendering does start working once the `<iframe>` becomes visible (although the errors do break the initial Toolbar state).

Before making any changes here, I carefully read through not just the immediately relevant code but also the rendering code in the viewer (given it's dependence on `getVisibleElements`). After concluding that the changes should be safe in general, the default viewer was tested without any issues found. (The above being much easier with significant prior experience of working with the viewer code.)
Finally the patch also adds new unit-tests, one of which explicitly triggers the relevant code-path and will thus fail with the current `master` branch.

This patch also makes `PDFViewerApplication` slightly more robust against errors during document opening, to ensure that viewer/document initialization always completes as expected.
Please keep in mind that even though this patch prevents an error in `getVisibleElements`, it's still not possible to set the initial position/zoom level/sidebar view etc. when the viewer is hidden since rendering and scrolling is completely dependent[3] on being able to actually access the DOM elements.

---
[1] And hence the PDF Viewer that's built-in to Firefox.

[2] Copy the HTML code below and save it as `iframe.html`, and place the file in the `web/` folder. Then start the server, with `gulp server`, and navigate to http://localhost:8888/web/iframe.html

```html
<!DOCTYPE html>
<html>
  <head>
    <title>Iframe test</title>

    <script>
      window.onload = function() {
        const button = document.getElementById('button1');
        const frame = document.getElementById('frame1');

        button.addEventListener('click', function(evt) {
          frame.hidden = !frame.hidden;
        });
      };
    </script>
  </head>

  <body>
    <button id="button1">Toggle iframe</button>
    <br>
    <iframe id="frame1" width="800" height="600" src="http://localhost:8888/web/viewer.html" hidden="true"></iframe>
  </body>
</html>
```

[3] This is an old, pre-exisiting, issue that's not relevant to this patch as such (and it's already being tracked elsewhere).
2019-01-13 11:34:24 +01:00
Jonas Jenwald
4773bf6fcb Add support for updating the document hash, off by default, when the browser history is updated (issue 5753)
This is *really* the best that we can do here, since other proposed solutions would interfere with (and break) the painstakingly implemented browsing history that's present in the default viewer.

I'm still not convinced that this is a good idea in general, but this patch implements it in a way where it is possible to toggle[1] for users that wish to have this feature. In particular, there's a couple of reasons why I'm not finding this feature necessary/great:
 - It's already possible to easily obtain the current hash, by simply clicking on the `viewBookmark` button at any time.
 - Hash changes requires a bit of special handling[2], i.e. extra code, to prevent issues when the browser history is traversed (see `PDFHistory._popState`). Currently this is only necessary when the user has manually changed the hash, with this patch it will always be the case (assuming the feature is active).
 - It's not always possible to change the URL when updating the browser history. For example: In the Firefox built-in viewer, the URL cannot be modified for local files (i.e. those using the `file://` protocol).
This leads to inconsistent behaviour, and may in some cases even result in errors being thrown and the history thus not updating, if the browser prevents changes to the URL during `pushState`/`replaceState` calls.

---
[1] Using the `historyUpdateUrl` viewer preference.

[2] This depends, to a great extent, on browsers always firing `popstate` events *before* `hashchange` events, which may or may not actually be guaranteed.
2019-01-06 20:09:02 +01:00
Jonas Jenwald
a7e70a50f5 Add OpenAction destination support, off by default, to the viewer
Given that it's really not clear to me if this is actually desired functionality in the default viewer, and considering that it doesn't fit in *great* with the way that `PDFHistory` is initialized, this feature is currently off by default[1].

---
[1] It's controlled with the `disableOpenActionDestination` Preference/AppOption.
2018-12-19 11:45:17 +01:00
Thiago da Silva
2abea7d7c2 Add keyboard shortcut to toggle sidebar 2018-12-16 13:00:15 -02:00
Jonas Jenwald
5d594885de Attempt to ignore mouse wheel zooming during tab switches (bug 1503412)
This patch re-factors, and extends, the already existing `zoomDisabledTimeout` used during mouse wheel zooming.
Unfortunately I haven't got the required hardware to actually test this patch, but there's a decent chance that it will fix, or at least reduce, the problems reported in https://bugzilla.mozilla.org/show_bug.cgi?id=1503412.
2018-12-12 13:46:47 +01:00
Jonas Jenwald
d9743e462d Replace the OVERRIDES list in PDFViewerApplication._readPreferences with a disablePreferences, in GENERIC builds, `AppOption instead
Rather than having a (somewhat) randomly choosen list of Preferences which `AppOptions` are allowed to override, it makes much more sense to simply add an AppOption to allow custom implementations to ignore Preferences altogether (it's also inline with the AppOption that allows the `ViewHistory` to be bypassed on load).
2018-11-29 11:46:40 +01:00
Jonas Jenwald
9a47a86565 Attempt to tweak the error messages, in BaseViewer, for invalid pageNumbers/pageLabels (bug 1505824)
Rather than closing [bug 1505824](https://bugzilla.mozilla.org/show_bug.cgi?id=1505824) as WONTFIX (which is my preferred solution), given how *minor* this "problem" is, it's still possible to adjust the error messages a bit.

The main point here, which is relevant even if the changes in `BaseViewer` are ultimately rejected during review, is that we'll no longer attempt to call `BaseViewer.currentPageLabel` with an empty string from `webViewerPageNumberChanged` in `app.js`.

The other changes are:
 - Stop printing an error in `BaseViewer._setCurrentPageNumber`, and have it return a boolean indicating if the page is within bounds.
 - Have the `BaseViewer.{currentPageNumber, currentPageLabel}` setters print their own errors for invalid pages.
 - Have the `BaseViewer.currentPageLabel` setter no longer depend, indirectly, on the `BaseViewer.currentPageNumber` setter.
 - Improve a couple of other error messages.
2018-11-17 17:23:09 +01:00
Jonas Jenwald
e2e9657ed0 Remove the attachDOMEventsToEventBus functionality, since EventBus instances are able to re-dispatch events to the DOM (PR 10019, bug 1492849 follow-up)
This also removes the old 'pagechange'/'scalechange'/'documentload' events.
2018-10-31 23:32:39 +01:00
Jonas Jenwald
755c6edc5e Ensure that the PDFDocumentLoadingTask is rejected when "setting up fake worker" failed (issue 10135)
This should, hopefully, cover all the possible ways[1] in which "fake workers" are loaded. Given the different code-paths, adding unit-tests might not be that simple.
Note that in order to make this work, the various `fakeWorkerFilesLoader` functions were converted to return `Promises`.

---
[1] Unfortunately there's lots of them, for various build targets and configurations.
2018-10-06 13:18:51 +02:00
Jonas Jenwald
5d421964e5 Remove the unused mainContainer parameter from the Toolbar constructor
Looking at the history of this code, this parameter has never been used.
I'm guessing that most likely the code in `web/toolbar.js` began life as a copy of `web/secondary_toolbar.js`, which would probably explain why that parameter exists.
2018-10-05 10:17:37 +02:00
Jonas Jenwald
2ed3591b22 Make PDFFindController less confusing to use, by allowing searching to start when setDocument is called
*This patch is based on something that I noticed while working on PR 10126.*

The recent re-factoring of `PDFFindController` brought many improvements, among those the fact that access to `BaseViewer` is no longer required. However, with these changes there's one thing which now strikes me as not particularly user-friendly[1]: The fact that in order for searching to actually work, `PDFFindController.setDocument` must be called *and* a 'pagesinit' event must be dispatched (from somewhere).

For all other viewer components, calling the `setDocument` method[2] is enough in order for the component to actually be usable.
The `PDFFindController` thus stands out quite a bit, and it also becomes difficult to work with in any sort of custom implementation. For example: Imagine someone trying to use `PDFFindController` separately from the viewer[3], which *should* now be relatively simple given the re-factoring, and thus having to (somehow) figure out that they'll also need to manually dispatch a 'pagesinit' event for searching to work.

Note that the above even affects the unit-tests, where an out-of-place 'pagesinit' event is being used.
To attempt to address these problems, I'm thus suggesting that *only* `setDocument` should be used to indicate that searching may start. For the default viewer and/or the viewer components, `BaseViewer.setDocument` will now call `PDFFindController.setDocument` when the document is ready, thus requiring no outside configuration anymore[4]. For custom implementation, and the unit-tests, it's now as simple as just calling `PDFFindController.setDocument` to allow searching to start.

---
[1] I should have caught this during review of PR 10099, but unfortunately it's sometimes not until you actually work with the code in question that things like these become clear.

[2] Assuming, obviously, that the viewer component in question actually implements such a method :-)

[3] There's even a very recent issue, filed by someone trying to do just that.

[4] Short of providing a `PDFFindController` instance when creating a `BaseViewer` instance, of course.
2018-10-04 10:28:50 +02:00
Jonas Jenwald
8eda8c27f8 Attempt to simplify the signature of the PDFSidebar constructor, by moving the eventBus parameter from the options object and removing the PDFOutlineViewer dependency
This is similar to the format used by a number of other viewer components, and should simplify the `PDFSidebar` initialization slightly.
Furthermore, by using the `eventBus` it's no longer necessary for `PDFSidebar` to have a direct dependency on `PDFOutlineViewer`.

There's still room for improvement here, but this patch is at least a start (since it's not clear to me how best to handle the viewers).
2018-10-02 13:14:11 +02:00
Jonas Jenwald
3f3ddaf541 Attempt to simplify the signature of the PDFFindBar constructor, by moving the eventBus parameter from the options object
This is similar to the format used by a number of other viewer components, and should simplify the `PDFFindBar` initialization slightly.
2018-10-02 12:57:07 +02:00
Tim van der Meij
f79fb88864
Remove the find controller setter in web/base_viewer.js
With `PDFFindController` instances no longer (directly) depending on
`BaseViewer` instances, we can pass a single `findController` when
initializing a viewer, similar to other components.
2018-09-30 16:59:58 +02:00
Tim van der Meij
38ff79186a
Replace callbacks for updating the UI with dispatching events on the event bus
This makes it more similar to how other components update the viewer UI
and avoids the need to have extra member variables and checks.
2018-09-30 16:59:57 +02:00
Tim van der Meij
e0c811f2ed
Use the link service for getting and setting page information
This removes the dependency on a `PDFViewer` instance from the find
controller, which makes it more similar to other components and makes it
easier to unit test with a mock link service.

Finally, we remove the search capabilities from the SVG example since it
doesn't work there because there is no separate text layer.
2018-09-30 16:59:46 +02:00
Tim van der Meij
e293c12afc
Implement the setDocument method for the find controller
Now it follows the same pattern as e.g., the document properties
component, which allows us to have one instance of the find controller
and set a new document to search upon switching documents.

Moreover, this allows us to get rid of the dependency on `pdfViewer` in
order to fetch the text content for a page. This is working towards
getting rid of the `pdfViewer` dependency upon initializing the
component entirely in future commits.

Finally, we make the `reset` method private since it's not supposed to
be used from the outside anymore now that `setDocument` takes care of
this, similar to other components.
2018-09-30 16:57:40 +02:00
Tim van der Meij
7aca53b1a4
Remove the find bar's dependency on the find controller
Pull request #10100 removed the last usage of the find controller from
the find bar, so we can drop the dependency now.
2018-09-30 16:55:30 +02:00
Jonas Jenwald
6da78bcc3f Update {PDFLinkService, PDFDocumentProperties}.setDocument to make the "url" parameter optional
This way the resetting of `PDFLinkService`/`PDFDocumentProperties` instances, as is done in `PDFViewerApplication.close`, only requires passing in *one* `null` argument instead of two.
2018-09-30 12:28:56 +02:00
Jonas Jenwald
6d804d657f Add initial support for "Whole words" searching in the viewer
As outlined in https://bugzilla.mozilla.org/show_bug.cgi?id=1282759 the internal Firefox name for the feature is `entireWord`, hence that name is used here as well for consistency (with "Whole words" being limited to the UI).

Given existing limitations of the PDF.js search functionality, e.g. the existing problems of searching across "new lines", there's some edge-cases where "Whole words" searching will ignore (valid) results.
However, considering that this is a pre-existing issue related to the way that the find controller joins text-content together, that shouldn't have to block this new feature in my opionion.

*Please note:* In order to enable this feature in the `MOZCENTRAL` version, a small follow-up patch for [PdfjsChromeUtils.jsm](https://hg.mozilla.org/mozilla-central/file/tip/browser/extensions/pdfjs/content/PdfjsChromeUtils.jsm) will be required once this has landed in `mozilla-central`.
2018-09-10 11:59:29 +02:00
Jonas Jenwald
c9a2564882 Display the index of the currently active search result in the matches counter of the findbar (issue 6993, bug 1062025)
For the `PDFFindBar` implementation, similar to the native Firefox findbar, the matches count displayed is now limited to a (hopefully) reasonable value.

*Please note:* In order to enable this feature in the `MOZCENTRAL` version, a follow-up patch will be required once this has landed in `mozilla-central`.
2018-09-08 21:50:22 +02:00
Jonas Jenwald
1bdfdd07b8 Utilize async/await in PDFViewerApplication.load to reduce the number of Promises and temporary variables necessary when setting the initial document location 2018-09-03 09:52:36 +02:00
Jonas Jenwald
3eba7ea267 Refactor a number of methods in PDFViewerApplication to be async rather than manually returning Promises
*Ignoring whitespace changes is probably necessary, in order for the diff to be readable.*
2018-09-03 09:52:36 +02:00
Jonas Jenwald
0b1f41c5b3 Add general support for re-dispatching events, on EventBus instances, to the DOM
This patch is the first step to be able to eventually get rid of the `attachDOMEventsToEventBus` function, by allowing `EventBus` instances to simply re-dispatch most[1] events to the DOM.
Note that the re-dispatching is purposely implemented to occur *after* all registered `EventBus` listeners have been serviced, to prevent the ordering issues that necessitated the duplicated page/scale-change events.

The DOM events are currently necessary for the `mozilla-central` tests, see https://hg.mozilla.org/mozilla-central/file/tip/browser/extensions/pdfjs/test, and perhaps also for custom deployments of the PDF.js default viewer.

Once this have landed, and been successfully uplifted to `mozilla-central`, I intent to submit a patch to update the test-code to utilize the new preference. This will thus, eventually, make it possible to remove the `attachDOMEventsToEventBus` functionality.

*Please note:* I've successfully ran all `mozilla-central` tests locally, with these patches applied.

---
[1] The exception being events that originated on the `window` or `document`, since those are already globally available anyway.
2018-08-30 17:28:12 +02:00
Jonas Jenwald
7bc4bfcc8b Add 'documentinit'/'documentloaded' events to PDFViewerApplication.load
The new events follow the same naming pattern as the 'pagesinit'/'pagesloaded' events dispatched on `BaseViewer` instances, and the intention is to allow the eventual removal of 'documentload'.
2018-08-30 10:39:32 +02:00
Jonas Jenwald
486c843215 Add source parameters to all remaining EventBus.dispatch calls that are currently missing those
This is necessary for subsequent patches, and will help avoid unnecessary event re-dispatching in cases where the event source is `window`.
2018-08-30 10:39:32 +02:00
Jonas Jenwald
50a47be190 [api-minor] Remove the obsolete createBlob helper function
At this point in time, all supported browsers have native support for `Blob`; please see https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob#Browser_compatibility.
Furthermore, note how the helper function was throwing an error if `Blob` isn't available anyway.
2018-08-19 13:37:19 +02:00
Jonas Jenwald
780cbadcd7 Stop re-loading the Preferences in PDFViewerApplication.open, and remove the BasePreferences.reload method
Given that the various Preferences are currently, and have been for quite some time, only used when initializing `PDFViewerApplication` re-loading them when a new PDF file is opened in the viewer is essentially a no-op.

Furthermore, with the only usage of `BasePreferences.reload` now gone, the value of that method seems questionable at best. In the event that the functionality is actually needed again, similar to the `ViewHistory`, it'd probably make more sense to simply replace `PDFViewerApplication.preferences` with a new `BasePreferences` instance instead (using e.g. `DefaultExternalServices.createPreferences`).
2018-07-28 13:50:16 +02:00
Jonas Jenwald
34957ec8eb Add a BasePreferences.getAll method and use it to fetch all Preferences at once in PDFViewerApplication._readPreferences
Given that *all* Preferences are already fetched in `PDFViewerApplication._readPreferences`, the amount of boilerplate/duplication can be considerably reduced with the addition of a `BasePreferences.getAll` method.
2018-07-25 10:43:36 +02:00
Jonas Jenwald
c3433aea48 Remove a (now) unnecessary externalLinkTarget check in PDFViewerApplication._readPreferences
The only reason that this check ever existed in the first place, is that originally there was a global `PDFJS.openExternalLinkInNewWindow` option which was then subsumed by the (more generic) `PDFJS.externalLinkTarget` option. (The `externalLinkTarget` has since been moved into a `PDFLinkService` option, as part of PDF.js version `2.0`.)

Hence, during the period where both `PDFJS.openExternalLinkInNewWindow` and `PDFJS.externalLinkTarget` existed side-by-side, there was a need to allow the former one to override the latter one (for backward compatibility purposes). However, that's no longer the case, and this extra `externalLinkTarget` check can now be removed.
2018-07-25 10:43:36 +02:00
Jonas Jenwald
c6a0ae08f1 Ensure that the externalLinkTarget option is correctly set when the viewer is embedded (PR 9479 follow-up)
*This was a stupid error on my part; sorry about breaking this!*

With the current code, the value of the `externalLinkTarget` option is now (potentially) updated *after* the viewer components have been initialized. For the "viewer in iframe/object tag" case, the result is that the value of the `externalLinkTarget` option isn't adjusted as intended any more.
2018-07-25 10:43:36 +02:00
Jonas Jenwald
200e3d6bd8 Update the various ESLint packages to their latest versions 2018-07-09 12:52:55 +02:00
Jonas Jenwald
a9ce4e8417 Stop exposing the URL polyfill in the global scope
This moves/exposes the `URL` polyfill similarily to the existing `ReadableStream` polyfill, rather than exposing it globally, to avoid interfering with any "outside" code.
Both the `URL` and `ReadableStream` polyfills are now exposed on the `pdfjsLib` object, such that they are accessible to the viewer components.
Furthermore, the `no-restricted-globals` ESLint rule is also enabled to prevent accidental usage of the native `URL`/`ReadableStream` implementations directly in the `src/` and `web/` folders; see also https://eslint.org/docs/rules/no-restricted-globals

Addresses the remaining TODO in https://github.com/mozilla/pdf.js/projects/6
2018-07-04 09:16:28 +02:00
Jonas Jenwald
39a1fce59b Refactor PDFFindController to use the 'pagesinit' event, dispatched on the eventBus, to resolve the _firstPagePromise
Rather than having to manually call a method on `PDFFindController` instances from `BaseViewer.setDocument`, thus essentially having to resolve the private `_firstPagePromise` from the "outside", this can be done easily with the 'pagesinit' event dispatched on the `eventBus` instead.
Please note this particular `PDFFindController` code pre-dates the `eventBus` by almost three years, which should explain why the code looks the way it does.
2018-07-01 16:25:51 +02:00
Jonas Jenwald
a7ac27e385 Replace setScrollMode/setSpreadMode methods with getters/setters
Since all the other viewer methods use the getter/setter pattern, e.g. for setting page/scale/rotation, the way that the Scroll/Spread modes are set thus stands out. For consistency, this really ought to use the same pattern as the rest of the `BaseViewer`. (To avoid breaking third-party implementations, the old methods are kept around as aliases.)
2018-06-30 12:36:54 +02:00
Jonas Jenwald
a9a93bd923 Allow the scrollModeOnLoad/spreadModeOnLoad Preferences to override ViewHistory settings
Note how the other "...OnLoad" preferences will allow a *non-default* value to always override a history entry. To improve overall consistency for the viewer options, and to reduce possibly confusing behaviour, this patch changes the `scrollModeOnLoad`/`spreadModeOnLoad` preferences to behave as all the other ones.
2018-06-30 12:19:02 +02:00
Jonas Jenwald
e522b2d87e Remove the unused PDFViewerApplication.documentFingerprint property
This property isn't accessed anywhere in the `web/app.js` file, and is also not being reset in `PDFViewerApplication.close`. Hence it seems that it can simply be removed, especially since the fingerprint is already synchronously available through `PDFViewerApplication.pdfDocument.fingerprint` (provided that a document is loaded).
2018-06-30 12:19:02 +02:00
Jonas Jenwald
95a4fa25b9 Don't wait arbitrary long for all pages to be resolved before attempting to re-apply the initial position on load (PR 6318 follow-up)
With the current code, the location in the viewer could change *well* after the user has started to interact with the viewer (for very large and/or slow loading documents). Attempt to reduce the likelyhood of that happening, by adding an upper bound to the time spent waiting before attempting to re-apply the initial position.
2018-06-26 14:19:59 +02:00
Jonas Jenwald
3691f9cc78 Simplify the handling of the defaultZoomValue preference in PDFViewerApplication.load 2018-06-26 14:13:44 +02:00
Jonas Jenwald
5bbbbf152e Stop storing/using the 'exists' property of ViewHistory database entries
Rather than using a "special" property to check if a `ViewHistory` database entry existed on load, it seems that you could just as well check for the existence of one of the actually needed properties instead (here 'page' is used).

This way we can avoid storing what, more of less, amounts to useless state, which will help reduce the size of the `ViewHistory` database. Given that we don't directly, nor need to, validate the `ViewHistory` data but rely on other parts of the code-base to do so, the existance of an 'exists' property doesn't in and of itself really add much utility.

Finally, to simplify the implementation the 'exists' property won't be actively removed from the `ViewHistory` data. Instead we'll simply stop adding 'exists' when writing `ViewHistory` data, and rely on the existing pruning of old entries to eventually remove any remnants of 'exists' from storage.
2018-06-26 14:12:21 +02:00
Jonas Jenwald
c8384061cf Ensure that the locale viewer option is never defined in the (various) extension builds (PR 9493 follow-up) 2018-06-23 13:33:40 +02:00
Jonas Jenwald
3e4a159a45 Set the correct document title when opening a new file in the GENERIC default viewer 2018-06-17 13:55:53 +02:00
Jonas Jenwald
84920f39b2 Change the casing of the originalURL parameter, to originalUrl, in the onOpenWithURL method
The `onOpenWithURL` method, in `PDFViewerApplication.initPassiveLoading`, accepts a `originalURL` parameter which is then passed on to `PDFViewerApplication.open` as is. However, the latter method expects the name of the parameter to be `originalUrl` (note the casing), meaning that `getDocument` will fail in this case.

For consistency, and to avoid confusion, the renaming is done in `web/chromecom.js` as well.
2018-06-17 13:32:30 +02:00
Brendan Dahl
7892122201
Merge pull request #9595 from Rob--W/crx-ftp-file
Disable ftp support in Chrome 59+, add file chooser at file
2018-06-15 14:48:19 -07:00
Jonas Jenwald
349b7d5e9c Remove the disableFullscreen hack for embedded IE 11 (issue 9585)
It appears that Microsoft silently fixed the problem that required disabling of fullscreen mode, in e.g. `iframe`s, in IE 11; please see issue 4711 and PR 5525 for historical context.

Unfortunately my Google-fu isn't strong enough to find any *official* information regarding the fixing of the browser bug in IE. However testing of the default viewer in IE 11, with this patch applied, it now appears that Presentation Mode is working correctly even in an `iframe` in IE 11.
Further anecdotal evidence that the bug is in fact fixed, is for example that jQuery previously contained a work-around for the IE bug. However, that's removed over two years ago now; see ff1a0822f7 and the issues referenced there.

Given that the default viewer isn't intended to be used as-is anyway (in custom deployments), it didn't seem necessary to keep the `disableFullscreen` option around since it was *only* ever added for compatibility purposes.

Fixes 9585.
2018-06-14 12:25:28 +02:00
Jonas Jenwald
ba623c77d2 Disable (drag-and-drop) file opening if Presentation Mode is active (PR 9794 follow-up) 2018-06-11 10:51:43 +02:00
Dimitris Kountanis
8e95506116
Implement drag-and-drop support in the viewer for local files 2018-06-10 15:42:55 +02:00
Jonas Jenwald
07d610615c Move, and modernize, Util.loadScript from src/shared/util.js to src/display/dom_utils.js
Not only is the `Util.loadScript` helper function unused on the Worker side, even trying to use it there would throw an Error (since `document` isn't defined/available in Workers).
Hence this helper function is moved, and its code modernized slightly by having it return a Promise rather than needing a callback function.

Finally, to reduced code duplication, the "new" loadScript function is exported and used in the viewer.
2018-06-07 13:52:40 +02:00
Tim van der Meij
057994d781
Backout of pull request #9345 2018-05-28 22:54:09 +02:00
Ryan Hendrickson
d7c051e807 Add preferences for default scroll/spread modes
This commit adds `scrollModeOnLoad` and `spreadModeOnLoad` preferences
that control the default viewer state when opening a new document for
the first time.

This commit also contains a minor refactoring of some of the option UI
rendering code in extensions/chromium/options/options.js, as I couldn't
bear creating two more functions nearly identical to the four that
already existed.
2018-05-14 23:10:33 -04:00
Ryan Hendrickson
c24bc29757 Remember last used scroll and spread modes 2018-05-14 23:10:33 -04:00
Ryan Hendrickson
eaf14e5d47 Modify key events for horizontal scrolling
Specifically, when there is no vertical scrollbar, let up, down, page
up, and page down all trigger moving to the next or previous page.
2018-05-14 23:10:32 -04:00
Ryan Hendrickson
3d83c646c6 Add spread modes to web viewer
This builds on the scrolling mode work to add three buttons for joining
page spreads together: one for the default view, with no page spreads,
and two for spreads starting on odd-numbered or even-numbered pages.
2018-05-14 23:10:32 -04:00
Ryan Hendrickson
91cbc185da Add scrolling modes to web viewer
In addition to the default scrolling mode (vertical), this commit adds
horizontal and wrapped scrolling, implemented primarily with CSS.
2018-05-14 23:10:32 -04:00
Jonas Jenwald
8b09f7c34e Clean-up getMainThreadWorkerMessageHandler for non-PRODUCTION mode
*This is a final piece of clean-up of code that I recently wrote, after which I'm done :-)*

When the `getMainThreadWorkerMessageHandler` function was added, in PR 9385, it did so by basically introducing a `web/app.js` dependency in `src/display/api.js` through the `window.pdfjsNonProductionPdfWorker` property[1]. Even though this is limited to non-`PRODUCTION` mode, i.e. `gulp server`, it still seems unfortunate to have that sort of viewer dependency in the API code itself.

With the new, much nicer and shorter, names introduced in PR 9565 we can remove this non-`PRODUCTION` hack and just use `window.pdfjsWorker` in both the viewer and the API regardless of the build mode.

---

[1] It didn't seem correct to piggy-back on the `window.pdfjsDistBuildPdfWorker` property in non-`PRODUCTION` mode.
2018-03-29 11:03:47 +02:00
Rob Wu
29c370af27 [CRX] Add file chooser as fallback (fixes #9411)
Test case to exercise the different encodings:
1. Create a file "some file#@%M<br>%25 .pdf"
2. Build the extension with `gulp chromium` and load it in Chrome.
3. Go to `chrome://extensions/` and ensure that the
   "Allow access to file URLs" is disabled.
4. Try to open the file from step 1 in Chrome (maybe reload once).
5. PDF.js should be showing a file chooser button.
6. Click on that button and select a different file.

   Test: Check that a confirmation dialog pops up that warns about
   a different file name. Cancel the dialog.

7. Click on the button again and select the original file.

   Test: Check that the file opens as expected.
2018-03-21 18:21:46 +01:00
Jonas Jenwald
c2f1523f06 Move the cursorToolOnLoad preference handling into AppOptions (PR 9493 follow-up)
Since no other viewer component is currently reading preferences itself, this patch thus unifies the behaviour across the viewer.
2018-03-19 23:24:56 +01:00
Jonas Jenwald
51ddcd6380 Display the pageSize of the *currently* active page in the document properties dialog 2018-03-18 09:10:21 +01:00
Jonas Jenwald
212553840f Move the pdfBug option from the global PDFJS object and into getDocument instead
Also removes the now unused `getDefaultSetting` helper function.
2018-03-01 18:11:17 +01:00
Jonas Jenwald
1d03ad0060 Move the disableCreateObjectURL option from the global PDFJS object and into getDocument instead 2018-03-01 18:11:17 +01:00
Jonas Jenwald
05c05bdef5 Move the disableStream option from the global PDFJS object and into getDocument instead 2018-03-01 18:11:16 +01:00
Jonas Jenwald
b69abf1111 Move the disableRange option from the global PDFJS object and into getDocument instead 2018-03-01 18:11:16 +01:00
Jonas Jenwald
69d7191034 Move the disableAutoFetch option from the global PDFJS object and into getDocument instead
One additional complication with removing this option from the global `PDFJS` object, is that the viewer currently needs to check `disableAutoFetch` in a couple of places. To address this I'm thus proposing adding a getter in `PDFDocumentProxy`, to allow checking the *actually* used values for a particular `getDocument` invocation.
2018-03-01 18:11:16 +01:00
Jonas Jenwald
c7c583583b Move the disableFontFace option from the global PDFJS object and into getDocument instead 2018-03-01 18:11:16 +01:00
Jonas Jenwald
3c2fbdffe6 Move the cMapUrl and cMapPacked options from the global PDFJS object and into getDocument instead 2018-03-01 18:11:16 +01:00
Jonas Jenwald
b0956a5d91 Refactor how the default viewer handles the worker options, by making use of AppOptions instead of the global PDFJS object 2018-03-01 18:11:16 +01:00
Jonas Jenwald
57165afb08 Move the defaultUrl parameter from the appConfig and into AppOptions instead
The `appConfig` contains (mostly) references to various DOM elements, used when initializing the viewer components.
Hence `defaultUrl` seem like a slightly better fit for the new `AppOptions` abstraction, not to mention that it should thus be easier to set/modify it for custom deployments of the default viewer.
2018-03-01 18:11:16 +01:00
Jonas Jenwald
81c550903f Move various viewer components options from PDFJS/PDFViewerApplication.viewerPrefs and into AppOptions instead 2018-03-01 18:11:16 +01:00
Rob Wu
a6aca3cabe Don't block origin-less blob:-URLs in hosted viewer 2018-02-23 12:48:52 +01:00
Jonas Jenwald
a97901efb6 Move the verbosity option from the global PDFJS object and into getDocument/PDFWorker instead
Given the purpose of this option, it doesn't seem necessary to make it available through `GlobalWorkerOptions`.
2018-02-16 13:22:35 +01:00
Jonas Jenwald
c3c1fc511d Move the workerSrc option from the global PDFJS object and into GlobalWorkerOptions instead 2018-02-16 13:22:35 +01:00
Jonas Jenwald
e95c11a7f0 Remove the undocumented PDFJS.enableStats option
In order to simplify things, the undocumented `enableStats` option was removed and `pdfBug` is now instead used to enabled general debugging *and* page request/rendering stats.
Considering that in the default viewer the `stats` was only used when debugging was also enabled, this simplification (code wise) definitely seem worthwhile to me.
2018-02-13 16:56:57 +01:00
Jonas Jenwald
74ffd1d865 Pass in the PDFJS.locale option to ExternalServices.createL10n
This allows us to remove an otherwise unnecessary `PDFJS` dependency from the `web/genericcom.js` file.
2018-02-13 16:56:56 +01:00
Jonas Jenwald
77efed6626 Replace the PDFJS.disableWebGL option with a enableWebGL option passed, via BaseViewer/PDFPageView, to PDFPageProxy.render
Please note that the, pre-existing, viewer preference is already named `enableWebGL`; fixes 4919.
2018-02-13 16:56:56 +01:00
Jonas Jenwald
a1cfa5f4d7 Replace the disableTextLayer and enhanceTextSelection options/preferences with a single textLayerMode option/preference
Rather than having two different (but connected) options for the textLayer, I think that it makes sense to try and unify this. For example: currently if `disableTextLayer === true`, then the value of `enhanceTextSelection` is simply ignored.

Since PDF.js version `2.0` already won't be backwards compatible in lots of ways, I don't think that we need to worry about migrating existing preferences here.
2018-02-13 16:56:54 +01:00
Jonas Jenwald
3a6f6d23d6 Move the externalLinkTarget and externalLinkRel options to PDFLinkService options
This removes the `PDFJS.externalLinkTarget`/`PDFJS.externalLinkRel` dependency from the viewer components, but please note that as a *temporary* solution the default viewer still uses it.
2018-02-13 14:28:40 +01:00
Jonas Jenwald
c45c394364 Move the imageResourcesPath option to a BaseViewer/PDFPageView/AnnotationLayerBuilder option
This removes the `PDFJS.imageResourcesPath` dependency from the viewer components and the test-suite, but please note that as a *temporary* solution the default viewer still uses it.
2018-02-13 14:28:38 +01:00
Jonas Jenwald
fdf99c6af5 Move the maxCanvasPixels option to a BaseViewer/PDFPageView option
This removes the `PDFJS.maxCanvasPixels` dependency from the viewer components, but please note that as a *temporary* solution the default viewer still uses it.
2018-02-13 13:42:03 +01:00
Jonas Jenwald
f4280368f7 Move the useOnlyCssZoom option to a BaseViewer/PDFPageView option
This removes the `PDFJS.useOnlyCssZoom` dependency from the viewer components, but please note that as a *temporary* solution the default viewer still uses it.
2018-02-13 13:42:03 +01:00
Jonas Jenwald
9e0a31f662 Move viewer specific compatibility options from src/shared/compatibility.js and into a separate file
Unfortunately, as far as I can tell, we still need the ability to adjust certain viewer options depending on the browser environment in PDF.js version `2.0`. However, we should be able to separate this from the general compatibility code in the `src/shared/compatibility.js` file.
2018-02-13 13:41:59 +01:00
Jonas Jenwald
1cf116ab88 Enable the mozilla/use-includes-instead-of-indexOf ESLint rule globally
This rule is available from https://www.npmjs.com/package/eslint-plugin-mozilla, and is enforced in mozilla-central. Note that we have the necessary `Array`/`String` polyfills and that most cases have already been fixed, see PRs 9032 and 9434.
2018-02-10 23:24:50 +01:00
Jonas Jenwald
56a8c934dd [api-major] Remove the PDFJS.disableWorker option
Despite this patch removing the `disableWorker` option itself, please note that we'll still fallback to loading the worker file(s) on the main-thread when running in environments without proper Web Worker support.

Furthermore it's still possible, even with this patch, to force the use of fake workers by manually loading the necessary file using a `<script>` tag on the main-thread.[1]
That way, the functionality of the now removed `SINGLE_FILE` build target and the resulting `build/pdf.combined.js` file can still be achieved simply by adding e.g. `<script src="build/pdf.worker.js"></script>` to the HTML (obviously with the path adjusted as needed).

Finally note that the `disableWorker` option is a performance footgun, and unfortunately many existing third-party examples actually use it without providing any sort of warning/justification.

---

[1] This approach is used in the default viewer, since certain kind of debugging may be easier if the code is running directly on the main-thread.
2018-01-31 12:52:10 +01:00
Jonas Jenwald
69a8336cf1 Address the final round of review comments for Content-Disposition filename extraction
This patch updates the `IPDFStreamReader` interface and ensures that the interface/implementation of `network.js`, `fetch_stream.js`, `node_stream.js`, and `transport_stream.js` all match properly.
The unit-tests are also adjusted, to more closely replicate the actual behaviour of the various actual `IPDFStreamReader` implementations.
Finally, this patch adjusts the use of the Content-Disposition filename when setting the title in the viewer, and adds `PDFDocumentProperties` support as well.
2018-01-18 17:39:22 +01:00
Juan Salvador Perez Garcia
eb1f6f4c24 Content disposition filename
File name is extracted from headers.
2018-01-18 17:38:44 +01:00
Soumya Himanish Mohapatra
06b3bb8214 Download button is now hidden for PDFs which are opened from 'file://' 2018-01-18 16:13:25 +05:30
Nitish Bansal
d60cba5065 Added enter key functionality for presentation mode 2018-01-05 03:27:14 +05:30
Jonas Jenwald
7c5ba9aad5 [api-major] Only create a StatTimer for pages when enableStats == true (issue 5215)
Unless the debugging tools (i.e. `PDFBug`) are enabled, or the `browsertest` is running, the `PDFPageProxy.stats` aren't actually used for anything.
Rather than initializing unnecessary `StatTimer` instances, we can simply re-use *one* dummy class (with static methods) for every page. Note that by using a dummy `StatTimer` in this way, rather than letting `PDFPageProxy.stats` be undefined, we don't need to guard *every* single stats collection callsite.

Since it wouldn't make much sense to attempt to use `PDFPageProxy.stats` when stat collection is disabled, it was instead changed to a "private" property (i.e. `PDFPageProxy._stats`) and a getter was added for accessing `PDFPageProxy.stats`. This getter will now return `null` when stat collection is disabled, making that case easy to handle.

For benchmarking purposes, the test-suite used to re-create the `StatTimer` after loading/rendering each page. However, modifying properties on various API code from the outside in this way seems very error-prone, and is an anti-pattern that we really should avoid at all cost. Hence the `PDFPageProxy.cleanup` method was modified to accept an optional parameter, which will take care of resetting `this.stats` when necessary, and `test/driver.js` was updated accordingly.

Finally, a tiny bit more validation was added on the viewer side, to ensure that all the code we're attempting to access is defined when handling `PDFPageProxy` stats.
2017-12-06 23:12:25 +01:00
Jonas Jenwald
c1f385eda9 Remove the pageRotation getter in PDFViewerApplication
This was added, during the refactoring in PR 8556, to avoid outright breaking third-party users of the default viewer.
With PDF.js version `2.0`, where we're making API changes that aren't backwards compatible, we ought to be able to remove this piece of viewer code as well.
2017-11-26 10:39:24 +01:00
Jonas Jenwald
c7ebea40b9 Don't display error messages, in the default viewer, for PDF files other than the current one
We've never attempted to limit the errors displayed in the default viewer to the current PDF file, but that's not really been a problem before. However after PR 7926, it's now possible to get password related error messages for *previously* opened PDF files in the default viewer.

**STR:**
 1. Open a password protected PDF file, e.g. `issue6010_1.pdf` from the test-suite.
 2. Cancel the password prompt.
 3. Open any new PDF file in the viewer.

**AR:**
The error UI is displayed, with a `No password given` message.

**ER:**
No error displayed, since it's only relevent for a now closed PDF file.

This is obviously a minor issue, caused by us now rejecting the still pending `pdfLoadingTask` during the `PDFViewerApplication.close` call, but I don't think that it (generally) makes sense to show errors if they're not relevant to the *currently* displayed PDF file.
2017-11-23 14:00:02 +01:00
Jonas Jenwald
25d6bc9de9 Extract parsing of debugging hash parameters into its own method in PDFViewerApplication
In order to move viewer related options from the global `PDFJS` object and into the initialization of the relevant components, we'll need to parse the hash parameters *before* calling `PDFViewerApplication._initializeViewerComponents`.
2017-11-15 10:08:57 +01:00
Jonas Jenwald
2f936f88f4 Remove the ignoreCurrentPositionOnZoom viewer option
The only reason for adding this parameter in the first place, all the way back in PR 4074, was that the "maintain document position on zooming" feature was landed and backed out a couple of times before it finally stuck.
Hence it seemed, at the time, like a good idea to have a simple way to disable that behaviour. However, that was almost four years ago, and it's just not likely that we'd want/need to ever disable it now.

Furthermore I really cannot imagine why anyone would actually *want* to reset the position whenever zooming occurs, since it results in a quite annoying UX.

*So, to summarize:* Based on the above, I think that we should try to remove this parameter now. On the off chance that anyone complains, re-adding it shouldn't be difficult.
2017-11-14 15:28:50 +01:00
Jonas Jenwald
085e7a7a74 Implement sidebar resizing for modern browsers, by utilizing CSS variables (issue 2072)
By making use of modern CSS features, in this case [CSS variables](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables), implementing sidebar resizing is actually quite simple. Not only will the amount of added code be fairly small, but it should also be easy to maintain since there's no need for complicated JavaScript hacks in order to update the CSS. Another benefit is that the JavaScript code doesn't need to make detailed assumptions about the exact structure of the HTML/CSS code.

Obviously this will not work in older browsers, such as IE, that lack support for CSS variables. In those cases sidebar resizing is simply disabled (via feature detection), and the resizing DOM element hidden, and the behaviour is thus *identical* to the current (fixed-width) sidebar.
However, considering the simplicity of the implementation, I really don't see why limiting this feature to "modern" browsers is a problem.

Finally, note that a few edge-cases meant that the patch is a bit larger than what the basic functionality would dictate. Among those is first of all proper RTL support, and secondly (automatic) resizing of the sidebar when the width of the *entire* viewer changes. Another, pre-existing, issue fixed here is the incomplete interface of `NullL10n`.

*Please note:* This patch has been successfully tested in both LTR and RTL viewer locales, in recent versions of Firefox and Chrome.

Fixes 2072.
2017-11-06 15:58:24 +01:00
Tim van der Meij
f87c16bcc4
Merge pull request #8993 from Snuffleupagus/sidebar-constant-position
Layout the sidebar in the same vertical position regardless of the viewer width (issue 4052, bug 850591)
2017-11-04 16:53:11 +01:00
Yury Delendik
b4e25fb2e8 Merge remote-tracking branch 'mozilla/version-2.0' into v2 2017-10-27 14:01:45 -05:00
Tim van der Meij
17cc94db4e Merge pull request #9034 from Snuffleupagus/javascript-null
[api-major] Change `getJavaScript` to return `null`, rather than an empty Array, when no JavaScript exists
2017-10-17 21:58:45 +02:00
Tim van der Meij
7d7edd9cc6
[api-major] Remove the PDFJS_NEXT option
Nothing uses this option anymore, so setting it is a no-op now. We can
safely remove it.

Use `SKIP_BABEL` (instead of `PDFJS_NEXT`) now if you want to skip Babel
translation for a build.
2017-10-16 23:16:51 +02:00
Jonas Jenwald
1cd1582cb9 [api-major] Change getJavaScript to return null, rather than an empty Array, when no JavaScript exists
Other API methods already return `null`, rather than empty Arrays/Objects, hence it makes sense to change `getJavaScript` to be consistent.
2017-10-15 22:17:14 +02:00
Jonas Jenwald
816ffa29aa Remove all warning/fallback code for obsolete method signatures in web/ files 2017-10-15 16:57:30 +02:00