Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(350)

Side by Side Diff: chrome/browser/resources/print_preview/previewarea/preview_area.js

Issue 10108001: Refactor print preview web ui (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Fix fit-to-page tests Created 8 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 cr.define('print_preview', function() {
6 'use strict';
7
8 /**
9 * Creates a PreviewArea object. It represents the area where the preview
10 * document is displayed.
11 * @param {!print_preview.DestinationStore} destinationStore Used to get the
12 * currently selected destination.
13 * @param {!print_preview.PrintTicketStore} printTicketStore Used to get
14 * information about how the preview should be displayed.
15 * @param {!print_preview.NativeLayer} nativeLayer Needed to communicate with
16 * Chromium's preview generation system.
17 * @constructor
18 * @extends {print_preview.Component}
19 */
20 function PreviewArea(destinationStore, printTicketStore, nativeLayer) {
21 print_preview.Component.call(this);
22
23 /**
24 * Used to get the currently selected destination.
25 * @type {!print_preview.DestinationStore}
26 * @private
27 */
28 this.destinationStore_ = destinationStore;
29
30 /**
31 * Used to get information about how the preview should be displayed.
32 * @type {!print_preview.PrintTicketStore}
33 * @private
34 */
35 this.printTicketStore_ = printTicketStore;
36
37 /**
38 * Used to contruct the preview generator.
39 * @type {!print_preview.NativeLayer}
40 * @private
41 */
42 this.nativeLayer_ = nativeLayer;
43
44 /**
45 * Used to read generated page previews.
46 * @type {print_preview.PreviewGenerator}
47 * @private
48 */
49 this.previewGenerator_ = null;
50
51 /**
52 * The embedded pdf plugin object. It's value is null if not yet loaded.
53 * @type {HTMLEmbedElement}
54 * @private
55 */
56 this.plugin_ = null;
57
58 /**
59 * Custom margins component superimposed on the preview plugin.
60 * @type {!print_preview.MarginControlContainer}
61 * @private
62 */
63 this.marginControlContainer_ =
64 new print_preview.MarginControlContainer(this.printTicketStore_);
65 this.addChild(this.marginControlContainer_);
66
67 /**
68 * Current zoom level as a percentage.
69 * @type {?number}
70 * @private
71 */
72 this.zoomLevel_ = null;
73
74 /**
75 * Current page offset which can be used to calculate scroll amount.
76 * @type {print_preview.Coordinate2d}
77 * @private
78 */
79 this.pageOffset_ = null;
80
81 /**
82 * Whether the plugin has finished reloading.
83 * @type {boolean}
84 * @private
85 */
86 this.isPluginReloaded_ = false;
87
88 /**
89 * Whether the document preview is ready.
90 * @type {boolean}
91 * @private
92 */
93 this.isDocumentReady_ = false;
94
95 /**
96 * Timeout object used to display a loading message if the preview is taking
97 * a long time to generate.
98 * @type {Object}
99 * @private
100 */
101 this.loadingTimeout_ = null;
102
103 /**
104 * Overlay element.
105 * @type {HTMLElement}
106 * @private
107 */
108 this.overlayEl_ = null;
109
110 /**
111 * The "Open system dialog" button.
112 * @type {HTMLButtonElement}
113 * @private
114 */
115 this.openSystemDialogButton_ = null;
116 };
117
118 /**
119 * Event types dispatched by the preview area.
120 * @enum {string}
121 */
122 PreviewArea.EventType = {
123 // Dispatched when the "Open system dialog" button is clicked.
124 OPEN_SYSTEM_DIALOG_CLICK:
125 'print_preview.PreviewArea.OPEN_SYSTEM_DIALOG_CLICK',
126
127 // Dispatched when the document preview is complete.
128 PREVIEW_GENERATION_DONE:
129 'print_preview.PreviewArea.PREVIEW_GENERATION_DONE',
130
131 // Dispatched when the document preview failed to be generated.
132 PREVIEW_GENERATION_FAIL:
133 'print_preview.PreviewArea.PREVIEW_GENERATION_FAIL',
134
135 // Dispatched when a new document preview is being generated.
136 PREVIEW_GENERATION_IN_PROGRESS:
137 'print_preview.PreviewArea.PREVIEW_GENERATION_IN_PROGRESS'
138 };
139
140 /**
141 * CSS classes used by the preview area.
142 * @enum {string}
143 * @private
144 */
145 PreviewArea.Classes_ = {
146 COMPATIBILITY_OBJECT: 'preview-area-compatibility-object',
147 CUSTOM_MESSAGE_TEXT: 'preview-area-custom-message-text',
148 MESSAGE: 'preview-area-message',
149 INVISIBLE: 'invisible',
150 OPEN_SYSTEM_DIALOG_BUTTON: 'preview-area-open-system-dialog-button',
151 OPEN_SYSTEM_DIALOG_BUTTON_THROBBER:
152 'preview-area-open-system-dialog-button-throbber',
153 OVERLAY: 'preview-area-overlay-layer',
154 PDF_PLUGIN: 'preview-area-pdf-plugin'
155 };
156
157 /**
158 * Enumeration of IDs shown in the preview area.
159 * @enum {string}
160 * @private
161 */
162 PreviewArea.MessageId_ = {
163 CUSTOM: 'custom',
164 LOADING: 'loading',
165 PREVIEW_FAILED: 'preview-failed'
166 };
167
168 /**
169 * Maps message IDs to the CSS class that contains them.
170 * @type {object.<PreviewArea.MessageId_, string>}
171 * @private
172 */
173 PreviewArea.MessageIdClassMap_ = {};
174 PreviewArea.MessageIdClassMap_[PreviewArea.MessageId_.CUSTOM] =
175 'preview-area-custom-message';
176 PreviewArea.MessageIdClassMap_[PreviewArea.MessageId_.LOADING] =
177 'preview-area-loading-message';
178 PreviewArea.MessageIdClassMap_[PreviewArea.MessageId_.PREVIEW_FAILED] =
179 'preview-area-preview-failed-message';
180
181 /**
182 * Amount of time in milliseconds to wait after issueing a new preview before
183 * the loading message is shown.
184 * @type {number}
185 * @const
186 * @private
187 */
188 PreviewArea.LOADING_TIMEOUT_ = 200;
189
190 PreviewArea.prototype = {
191 __proto__: print_preview.Component.prototype,
192
193 /**
194 * Should only be called after calling this.render().
195 * @return {boolean} Whether the preview area has a compatible plugin to
196 * display the print preview in.
197 */
198 get hasCompatiblePlugin() {
199 return this.previewGenerator_ != null;
200 },
201
202 /**
203 * Processes a keyboard event that could possibly be used to change state of
204 * the preview plugin.
205 * @param {MouseEvent} e Mouse event to process.
206 */
207 handleDirectionalKeyEvent: function(e) {
208 // Make sure the PDF plugin is there.
209 // We only care about: PageUp, PageDown, Left, Up, Right, Down.
210 // If the user is holding a modifier key, ignore.
211 if (!this.plugin_ ||
212 !arrayContains([33, 34, 37, 38, 39, 40], e.keyCode) ||
213 e.metaKey || e.altKey || e.shiftKey || e.ctrlKey) {
214 return;
215 }
216
217 // Don't handle the key event for these elements.
218 var tagName = document.activeElement.tagName;
219 if (arrayContains(['INPUT', 'SELECT', 'EMBED'], tagName)) {
220 return;
221 }
222
223 // For the most part, if any div of header was the last clicked element,
224 // then the active element is the body. Starting with the last clicked
225 // element, and work up the DOM tree to see if any element has a
226 // scrollbar. If there exists a scrollbar, do not handle the key event
227 // here.
228 var element = e.target;
229 while (element) {
230 if (element.scrollHeight > element.clientHeight ||
231 element.scrollWidth > element.clientWidth) {
232 return;
233 }
234 element = element.parentElement;
235 }
236
237 // No scroll bar anywhere, or the active element is something else, like a
238 // button. Note: buttons have a bigger scrollHeight than clientHeight.
239 this.plugin_.sendKeyEvent(e.keyCode);
240 e.preventDefault();
241 },
242
243 /**
244 * Shows a custom message on the preview area's overlay.
245 * @param {string} message Custom message to show.
246 */
247 showCustomMessage: function(message) {
248 this.showMessage_(PreviewArea.MessageId_.CUSTOM, message);
249 },
250
251 /** @override */
252 enterDocument: function() {
253 print_preview.Component.prototype.enterDocument.call(this);
254 this.tracker.add(
255 this.openSystemDialogButton_,
256 'click',
257 this.onOpenSystemDialogButtonClick_.bind(this));
258
259 this.tracker.add(
260 this.printTicketStore_,
261 print_preview.PrintTicketStore.EventType.INITIALIZE,
262 this.onTicketChange_.bind(this));
263 this.tracker.add(
264 this.printTicketStore_,
265 print_preview.PrintTicketStore.EventType.TICKET_CHANGE,
266 this.onTicketChange_.bind(this));
267 this.tracker.add(
268 this.printTicketStore_,
269 print_preview.PrintTicketStore.EventType.CAPABILITIES_CHANGE,
270 this.onTicketChange_.bind(this));
271
272 if (this.checkPluginCompatibility_()) {
273 this.previewGenerator_ = new print_preview.PreviewGenerator(
274 this.destinationStore_, this.printTicketStore_, this.nativeLayer_);
275 this.tracker.add(
276 this.previewGenerator_,
277 print_preview.PreviewGenerator.EventType.PREVIEW_START,
278 this.onPreviewStart_.bind(this));
279 this.tracker.add(
280 this.previewGenerator_,
281 print_preview.PreviewGenerator.EventType.PAGE_READY,
282 this.onPagePreviewReady_.bind(this));
283 this.tracker.add(
284 this.previewGenerator_,
285 print_preview.PreviewGenerator.EventType.FAIL,
286 this.onPreviewGenerationFail_.bind(this));
287 this.tracker.add(
288 this.previewGenerator_,
289 print_preview.PreviewGenerator.EventType.DOCUMENT_READY,
290 this.onDocumentReady_.bind(this));
291 } else {
292 this.showCustomMessage(localStrings.getString('noPlugin'));
293 }
294 },
295
296 /** @override */
297 exitDocument: function() {
298 print_preview.Component.prototype.exitDocument.call(this);
299 if (this.previewGenerator_) {
300 this.previewGenerator_.removeEventListeners();
301 }
302 this.overlayEl_ = null;
303 this.openSystemDialogButton_ = null;
304 },
305
306 /** @override */
307 decorateInternal: function() {
308 this.marginControlContainer_.decorate(this.getElement());
309 this.overlayEl_ = this.getElement().getElementsByClassName(
310 PreviewArea.Classes_.OVERLAY)[0];
311 this.openSystemDialogButton_ = this.getElement().getElementsByClassName(
312 PreviewArea.Classes_.OPEN_SYSTEM_DIALOG_BUTTON)[0];
313 },
314
315 /**
316 * Checks to see if a suitable plugin for rendering the preview exists. If
317 * one does not exist, then an error message will be displayed.
318 * @return {boolean} Whether Chromium has a suitable plugin for rendering
319 * the preview.
320 * @private
321 */
322 checkPluginCompatibility_: function() {
323 var compatObj = this.getElement().getElementsByClassName(
324 PreviewArea.Classes_.COMPATIBILITY_OBJECT)[0];
325 var isCompatible =
326 compatObj.onload &&
327 compatObj.goToPage &&
328 compatObj.removePrintButton &&
329 compatObj.loadPreviewPage &&
330 compatObj.printPreviewPageCount &&
331 compatObj.resetPrintPreviewUrl &&
332 compatObj.onPluginSizeChanged &&
333 compatObj.onScroll &&
334 compatObj.pageXOffset &&
335 compatObj.pageYOffset &&
336 compatObj.setZoomLevel &&
337 compatObj.setPageNumbers &&
338 compatObj.setPageXOffset &&
339 compatObj.setPageYOffset &&
340 compatObj.getHorizontalScrollbarThickness &&
341 compatObj.getVerticalScrollbarThickness &&
342 compatObj.getPageLocationNormalized &&
343 compatObj.getHeight &&
344 compatObj.getWidth;
345 compatObj.parentElement.removeChild(compatObj);
346 return isCompatible;
347 },
348
349 /**
350 * Shows a given message on the overlay.
351 * @param {print_preview.PreviewArea.MessageId_} messageId ID of the message
352 * to show.
353 * @param {string=} opt_message Optional message to show that can be used
354 * by some message IDs.
355 * @private
356 */
357 showMessage_: function(messageId, opt_message) {
358 // Hide all messages.
359 var messageEls = this.getElement().getElementsByClassName(
360 PreviewArea.Classes_.MESSAGE);
361 for (var i = 0, messageEl; messageEl = messageEls[i]; i++) {
362 setIsVisible(messageEl, false);
363 }
364 // Disable jumping animation to conserve cycles.
365 var jumpingDotsEl = this.getElement().querySelector(
366 '.preview-area-loading-message-jumping-dots');
367 jumpingDotsEl.classList.remove('jumping-dots');
368
369 // Show specific message.
370 if (messageId == PreviewArea.MessageId_.CUSTOM) {
371 var customMessageTextEl = this.getElement().getElementsByClassName(
372 PreviewArea.Classes_.CUSTOM_MESSAGE_TEXT)[0];
373 customMessageTextEl.textContent = opt_message;
374 } else if (messageId == PreviewArea.MessageId_.LOADING) {
375 jumpingDotsEl.classList.add('jumping-dots');
376 }
377 var messageEl = this.getElement().getElementsByClassName(
378 PreviewArea.MessageIdClassMap_[messageId])[0];
379 setIsVisible(messageEl, true);
380
381 // Show overlay.
382 this.overlayEl_.classList.remove(PreviewArea.Classes_.INVISIBLE);
383 },
384
385 /**
386 * Hides the message overlay.
387 * @private
388 */
389 hideOverlay_: function() {
390 this.overlayEl_.classList.add(PreviewArea.Classes_.INVISIBLE);
391 // Disable jumping animation to conserve cycles.
392 var jumpingDotsEl = this.getElement().querySelector(
393 '.preview-area-loading-message-jumping-dots');
394 jumpingDotsEl.classList.remove('jumping-dots');
395 },
396
397 /**
398 * Creates a preview plugin and adds it to the DOM.
399 * @param {string} srcUrl Initial URL of the plugin.
400 * @private
401 */
402 createPlugin_: function(srcUrl) {
403 if (this.plugin_) {
404 throw Error('Pdf preview plugin already created');
405 }
406 this.plugin_ = document.createElement('embed');
407 // NOTE: The plugin's 'id' field must be set to 'pdf-viewer' since
408 // chrome/renderer/print_web_view_helper.cc actually references it.
409 this.plugin_.setAttribute('id', 'pdf-viewer');
410 this.plugin_.setAttribute('class', 'preview-area-plugin');
411 this.plugin_.setAttribute(
412 'type', 'application/x-google-chrome-print-preview-pdf');
413 this.plugin_.setAttribute('src', srcUrl);
414 this.plugin_.setAttribute('aria-live', 'polite');
415 this.plugin_.setAttribute('aria-atomic', 'true');
416 this.getElement().appendChild(this.plugin_);
417
418 global['onPreviewPluginLoad'] = this.onPluginLoad_.bind(this);
419 this.plugin_.onload('onPreviewPluginLoad()');
420
421 global['onPreviewPluginVisualStateChange'] =
422 this.onPreviewVisualStateChange_.bind(this);
423 this.plugin_.onScroll('onPreviewPluginVisualStateChange()');
424 this.plugin_.onPluginSizeChanged('onPreviewPluginVisualStateChange()');
425
426 this.plugin_.removePrintButton();
427 this.plugin_.grayscale(!this.printTicketStore_.isColorEnabled());
428 },
429
430 /**
431 * Dispatches a PREVIEW_GENERATION_DONE event if all conditions are met.
432 * @private
433 */
434 dispatchPreviewGenerationDoneIfReady_: function() {
435 if (this.isDocumentReady_ && this.isPluginReloaded_) {
436 cr.dispatchSimpleEvent(
437 this, PreviewArea.EventType.PREVIEW_GENERATION_DONE);
438 this.marginControlContainer_.showMarginControlsIfNeeded();
439 }
440 },
441
442 /**
443 * Called when the open-system-dialog button is clicked. Disables the
444 * button, shows the throbber, and dispatches the OPEN_SYSTEM_DIALOG_CLICK
445 * event.
446 * @private
447 */
448 onOpenSystemDialogButtonClick_: function() {
449 this.openSystemDialogButton_.disabled = true;
450 var openSystemDialogThrobber = this.getElement().getElementsByClassName(
451 PreviewArea.Classes_.OPEN_SYSTEM_DIALOG_BUTTON_THROBBER)[0];
452 setIsVisible(openSystemDialogThrobber, true);
453 cr.dispatchSimpleEvent(
454 this, PreviewArea.EventType.OPEN_SYSTEM_DIALOG_CLICK);
455 },
456
457 /**
458 * Called when the print ticket changes. Updates the preview.
459 * @private
460 */
461 onTicketChange_: function() {
462 if (this.previewGenerator_ && this.printTicketStore_.isTicketValid()) {
463 if (this.previewGenerator_.requestPreview()) {
464 this.loadingTimeout_ = setTimeout(
465 this.showMessage_.bind(this, PreviewArea.MessageId_.LOADING),
466 PreviewArea.LOADING_TIMEOUT_);
467 } else {
468 this.marginControlContainer_.showMarginControlsIfNeeded();
469 }
470 }
471 },
472
473 /**
474 * Called when the preview generator begins loading the preview.
475 * @param {cr.Event} Contains the URL to initialize the plugin to.
476 * @private
477 */
478 onPreviewStart_: function(event) {
479 this.isDocumentReady_ = false;
480 this.isPluginReloaded_ = false;
481 if (!this.plugin_) {
482 this.createPlugin_(event.previewUrl);
483 }
484 this.plugin_.goToPage('0');
485 this.plugin_.resetPrintPreviewUrl(event.previewUrl);
486 this.plugin_.reload();
487 this.plugin_.grayscale(!this.printTicketStore_.isColorEnabled());
488 cr.dispatchSimpleEvent(
489 this, PreviewArea.EventType.PREVIEW_GENERATION_IN_PROGRESS);
490 },
491
492 /**
493 * Called when a page preview has been generated. Updates the plugin with
494 * the new page.
495 * @param {cr.Event} event Contains information about the page preview.
496 * @private
497 */
498 onPagePreviewReady_: function(event) {
499 this.plugin_.loadPreviewPage(event.previewUrl, event.previewIndex);
500 },
501
502 /**
503 * Called when the preview generation is complete and the document is ready
504 * to print.
505 * @private
506 */
507 onDocumentReady_: function(event) {
508 this.isDocumentReady_ = true;
509 this.dispatchPreviewGenerationDoneIfReady_();
510 },
511
512 /**
513 * Called when the generation of a preview fails. Shows an error message.
514 * @private
515 */
516 onPreviewGenerationFail_: function() {
517 this.showMessage_(PreviewArea.MessageId_.PREVIEW_FAILED);
518 cr.dispatchSimpleEvent(
519 this, PreviewArea.EventType.PREVIEW_GENERATION_FAIL);
520 },
521
522 /**
523 * Called when the plugin loads. This is a consequence of calling
524 * plugin.reload(). Certain plugin state can only be set after the plugin
525 * has loaded.
526 * @private
527 */
528 onPluginLoad_: function() {
529 if (this.loadingTimeout_) {
530 clearTimeout(this.loadingTimeout_);
531 this.loadingTimeout_ = null;
532 }
533 // Setting the plugin's page count can only be called after the plugin is
534 // loaded and the document must be modifiable.
535 if (this.printTicketStore_.isDocumentModifiable) {
536 this.plugin_.printPreviewPageCount(
537 this.printTicketStore_.getPageNumberSet().size);
538 }
539 this.plugin_.setPageNumbers(JSON.stringify(
540 this.printTicketStore_.getPageNumberSet().asArray()));
541 if (this.zoomLevel_ != null && this.pageOffset_ != null) {
542 this.plugin_.setZoomLevel(this.zoomLevel_);
543 this.plugin_.setPageXOffset(this.pageOffset_.x);
544 this.plugin_.setPageYOffset(this.pageOffset_.y);
545 } else {
546 this.plugin_.fitToHeight();
547 }
548 this.hideOverlay_();
549 this.isPluginReloaded_ = true;
550 this.dispatchPreviewGenerationDoneIfReady_();
551 },
552
553 /**
554 * Called when the preview plugin's visual state has changed. This is a
555 * consequence of scrolling or zooming the plugin. Updates the custom
556 * margins component if shown.
557 * @private
558 */
559 onPreviewVisualStateChange_: function() {
560 if (this.isPluginReloaded_) {
561 this.zoomLevel_ = this.plugin_.getZoomLevel();
562 this.pageOffset_ = new print_preview.Coordinate2d(
563 this.plugin_.pageXOffset(), this.plugin_.pageYOffset());
564 }
565 var normalized = this.plugin_.getPageLocationNormalized().split(';');
566 var pluginWidth = this.plugin_.getWidth();
567 var pluginHeight = this.plugin_.getHeight();
568 var translationTransform = new print_preview.Coordinate2d(
569 parseFloat(normalized[0]) * pluginWidth,
570 parseFloat(normalized[1]) * pluginHeight);
571 this.marginControlContainer_.updateTranslationTransform(
572 translationTransform);
573 var pageWidthInPixels = parseFloat(normalized[2]) * pluginWidth;
574 this.marginControlContainer_.updateScaleTransform(
575 pageWidthInPixels / this.printTicketStore_.pageSize.width);
576 this.marginControlContainer_.updateClippingMask(
577 new print_preview.Size(
578 pluginWidth - this.plugin_.getVerticalScrollbarThickness(),
579 pluginHeight - this.plugin_.getHorizontalScrollbarThickness()));
580 }
581 };
582
583 // Export
584 return {
585 PreviewArea: PreviewArea
586 };
587 });
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698