5fad4c8dce29afef5f69d32f728a12295a695a60
[platform/framework/web/crosswalk.git] / src / chrome / browser / resources / print_preview / native_layer.js
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    * An interface to the native Chromium printing system layer.
10    * @constructor
11    * @extends {cr.EventTarget}
12    */
13   function NativeLayer() {
14     cr.EventTarget.call(this);
15
16     // Bind global handlers
17     global['setInitialSettings'] = this.onSetInitialSettings_.bind(this);
18     global['setUseCloudPrint'] = this.onSetUseCloudPrint_.bind(this);
19     global['setPrinters'] = this.onSetPrinters_.bind(this);
20     global['updateWithPrinterCapabilities'] =
21         this.onUpdateWithPrinterCapabilities_.bind(this);
22     global['failedToGetPrinterCapabilities'] =
23         this.onFailedToGetPrinterCapabilities_.bind(this);
24     global['failedToGetPrivetPrinterCapabilities'] =
25       this.onFailedToGetPrivetPrinterCapabilities_.bind(this);
26     global['reloadPrintersList'] = this.onReloadPrintersList_.bind(this);
27     global['printToCloud'] = this.onPrintToCloud_.bind(this);
28     global['fileSelectionCancelled'] =
29         this.onFileSelectionCancelled_.bind(this);
30     global['fileSelectionCompleted'] =
31         this.onFileSelectionCompleted_.bind(this);
32     global['printPreviewFailed'] = this.onPrintPreviewFailed_.bind(this);
33     global['invalidPrinterSettings'] =
34         this.onInvalidPrinterSettings_.bind(this);
35     global['onDidGetDefaultPageLayout'] =
36         this.onDidGetDefaultPageLayout_.bind(this);
37     global['onDidGetPreviewPageCount'] =
38         this.onDidGetPreviewPageCount_.bind(this);
39     global['onDidPreviewPage'] = this.onDidPreviewPage_.bind(this);
40     global['updatePrintPreview'] = this.onUpdatePrintPreview_.bind(this);
41     global['printScalingDisabledForSourcePDF'] =
42         this.onPrintScalingDisabledForSourcePDF_.bind(this);
43     global['onDidGetAccessToken'] = this.onDidGetAccessToken_.bind(this);
44     global['autoCancelForTesting'] = this.autoCancelForTesting_.bind(this);
45     global['onPrivetPrinterChanged'] = this.onPrivetPrinterChanged_.bind(this);
46     global['onPrivetCapabilitiesSet'] =
47       this.onPrivetCapabilitiesSet_.bind(this);
48     global['onPrivetPrintFailed'] = this.onPrivetPrintFailed_.bind(this);
49   };
50
51   /**
52    * Event types dispatched from the Chromium native layer.
53    * @enum {string}
54    * @const
55    */
56   NativeLayer.EventType = {
57     ACCESS_TOKEN_READY: 'print_preview.NativeLayer.ACCESS_TOKEN_READY',
58     CAPABILITIES_SET: 'print_preview.NativeLayer.CAPABILITIES_SET',
59     CLOUD_PRINT_ENABLE: 'print_preview.NativeLayer.CLOUD_PRINT_ENABLE',
60     DESTINATIONS_RELOAD: 'print_preview.NativeLayer.DESTINATIONS_RELOAD',
61     DISABLE_SCALING: 'print_preview.NativeLayer.DISABLE_SCALING',
62     FILE_SELECTION_CANCEL: 'print_preview.NativeLayer.FILE_SELECTION_CANCEL',
63     FILE_SELECTION_COMPLETE:
64         'print_preview.NativeLayer.FILE_SELECTION_COMPLETE',
65     GET_CAPABILITIES_FAIL: 'print_preview.NativeLayer.GET_CAPABILITIES_FAIL',
66     INITIAL_SETTINGS_SET: 'print_preview.NativeLayer.INITIAL_SETTINGS_SET',
67     LOCAL_DESTINATIONS_SET: 'print_preview.NativeLayer.LOCAL_DESTINATIONS_SET',
68     PAGE_COUNT_READY: 'print_preview.NativeLayer.PAGE_COUNT_READY',
69     PAGE_LAYOUT_READY: 'print_preview.NativeLayer.PAGE_LAYOUT_READY',
70     PAGE_PREVIEW_READY: 'print_preview.NativeLayer.PAGE_PREVIEW_READY',
71     PREVIEW_GENERATION_DONE:
72         'print_preview.NativeLayer.PREVIEW_GENERATION_DONE',
73     PREVIEW_GENERATION_FAIL:
74         'print_preview.NativeLayer.PREVIEW_GENERATION_FAIL',
75     PRINT_TO_CLOUD: 'print_preview.NativeLayer.PRINT_TO_CLOUD',
76     SETTINGS_INVALID: 'print_preview.NativeLayer.SETTINGS_INVALID',
77     PRIVET_PRINTER_CHANGED: 'print_preview.NativeLayer.PRIVET_PRINTER_CHANGED',
78     PRIVET_CAPABILITIES_SET:
79         'print_preview.NativeLayer.PRIVET_CAPABILITIES_SET',
80     PRIVET_PRINT_FAILED: 'print_preview.NativeLayer.PRIVET_PRINT_FAILED'
81   };
82
83   /**
84    * Constant values matching printing::DuplexMode enum.
85    * @enum {number}
86    */
87   NativeLayer.DuplexMode = {
88     SIMPLEX: 0,
89     LONG_EDGE: 1,
90     UNKNOWN_DUPLEX_MODE: -1
91   };
92
93   /**
94    * Enumeration of color modes used by Chromium.
95    * @enum {number}
96    * @private
97    */
98   NativeLayer.ColorMode_ = {
99     GRAY: 1,
100     COLOR: 2
101   };
102
103   /**
104    * Version of the serialized state of the print preview.
105    * @type {number}
106    * @const
107    * @private
108    */
109   NativeLayer.SERIALIZED_STATE_VERSION_ = 1;
110
111   NativeLayer.prototype = {
112     __proto__: cr.EventTarget.prototype,
113
114     /**
115      * Requests access token for cloud print requests.
116      * @param {string} authType type of access token.
117      */
118     startGetAccessToken: function(authType) {
119       chrome.send('getAccessToken', [authType]);
120     },
121
122     /** Gets the initial settings to initialize the print preview with. */
123     startGetInitialSettings: function() {
124       chrome.send('getInitialSettings');
125     },
126
127     /**
128      * Requests the system's local print destinations. A LOCAL_DESTINATIONS_SET
129      * event will be dispatched in response.
130      */
131     startGetLocalDestinations: function() {
132       chrome.send('getPrinters');
133     },
134
135     /**
136      * Requests the network's privet print destinations. A number of
137      * PRIVET_PRINTER_CHANGED events will be fired in response, followed by a
138      * PRIVET_SEARCH_ENDED.
139      */
140     startGetPrivetDestinations: function() {
141       chrome.send('getPrivetPrinters');
142     },
143
144     /**
145      * Requests that the privet print stack stop searching for privet print
146      * destinations.
147      */
148     stopGetPrivetDestinations: function() {
149       chrome.send('stopGetPrivetPrinters');
150     },
151
152     /**
153      * Requests the privet destination's printing capabilities. A
154      * PRIVET_CAPABILITIES_SET event will be dispatched in response.
155      * @param {string} destinationId ID of the destination.
156      */
157     startGetPrivetDestinationCapabilities: function(destinationId) {
158       chrome.send('getPrivetPrinterCapabilities', [destinationId]);
159     },
160
161     /**
162      * Requests the destination's printing capabilities. A CAPABILITIES_SET
163      * event will be dispatched in response.
164      * @param {string} destinationId ID of the destination.
165      */
166     startGetLocalDestinationCapabilities: function(destinationId) {
167       chrome.send('getPrinterCapabilities', [destinationId]);
168     },
169
170     /**
171      * Requests that a preview be generated. The following events may be
172      * dispatched in response:
173      *   - PAGE_COUNT_READY
174      *   - PAGE_LAYOUT_READY
175      *   - PAGE_PREVIEW_READY
176      *   - PREVIEW_GENERATION_DONE
177      *   - PREVIEW_GENERATION_FAIL
178      * @param {print_preview.Destination} destination Destination to print to.
179      * @param {!print_preview.PrintTicketStore} printTicketStore Used to get the
180      *     state of the print ticket.
181      * @param {!print_preview.DocumentInfo} documentInfo Document data model.
182      * @param {number} ID of the preview request.
183      */
184     startGetPreview: function(
185         destination, printTicketStore, documentInfo, requestId) {
186       assert(printTicketStore.isTicketValidForPreview(),
187              'Trying to generate preview when ticket is not valid');
188
189       var ticket = {
190         'pageRange': printTicketStore.pageRange.getDocumentPageRanges(),
191         'landscape': printTicketStore.landscape.getValue(),
192         'color': printTicketStore.color.getValue() ?
193             NativeLayer.ColorMode_.COLOR : NativeLayer.ColorMode_.GRAY,
194         'headerFooterEnabled': printTicketStore.headerFooter.getValue(),
195         'marginsType': printTicketStore.marginsType.getValue(),
196         'isFirstRequest': requestId == 0,
197         'requestID': requestId,
198         'previewModifiable': documentInfo.isModifiable,
199         'printToPDF':
200             destination != null &&
201             destination.id ==
202                 print_preview.Destination.GooglePromotedId.SAVE_AS_PDF,
203         'printWithCloudPrint': destination != null && !destination.isLocal,
204         'printWithPrivet': destination != null && destination.isPrivet,
205         'deviceName': destination == null ? 'foo' : destination.id,
206         'generateDraftData': documentInfo.isModifiable,
207         'fitToPageEnabled': printTicketStore.fitToPage.getValue(),
208
209         // NOTE: Even though the following fields don't directly relate to the
210         // preview, they still need to be included.
211         'duplex': printTicketStore.duplex.getValue() ?
212             NativeLayer.DuplexMode.LONG_EDGE : NativeLayer.DuplexMode.SIMPLEX,
213         'copies': printTicketStore.copies.getValueAsNumber(),
214         'collate': printTicketStore.collate.getValue(),
215         'shouldPrintBackgrounds': printTicketStore.cssBackground.getValue(),
216         'shouldPrintSelectionOnly': printTicketStore.selectionOnly.getValue()
217       };
218
219       // Set 'cloudPrintID' only if the destination is not local.
220       if (destination && !destination.isLocal) {
221         ticket['cloudPrintID'] = destination.id;
222       }
223
224       if (printTicketStore.marginsType.isCapabilityAvailable() &&
225           printTicketStore.marginsType.getValue() ==
226               print_preview.ticket_items.MarginsType.Value.CUSTOM) {
227         var customMargins = printTicketStore.customMargins.getValue();
228         var orientationEnum =
229             print_preview.ticket_items.CustomMargins.Orientation;
230         ticket['marginsCustom'] = {
231           'marginTop': customMargins.get(orientationEnum.TOP),
232           'marginRight': customMargins.get(orientationEnum.RIGHT),
233           'marginBottom': customMargins.get(orientationEnum.BOTTOM),
234           'marginLeft': customMargins.get(orientationEnum.LEFT)
235         };
236       }
237
238       chrome.send(
239           'getPreview',
240           [JSON.stringify(ticket),
241            requestId > 0 ? documentInfo.pageCount : -1,
242            documentInfo.isModifiable]);
243     },
244
245     /**
246      * Requests that the document be printed.
247      * @param {!print_preview.Destination} destination Destination to print to.
248      * @param {!print_preview.PrintTicketStore} printTicketStore Used to get the
249      *     state of the print ticket.
250      * @param {print_preview.CloudPrintInterface} cloudPrintInterface Interface
251      *     to Google Cloud Print.
252      * @param {!print_preview.DocumentInfo} documentInfo Document data model.
253      * @param {boolean=} opt_isOpenPdfInPreview Whether to open the PDF in the
254      *     system's preview application.
255      */
256     startPrint: function(destination, printTicketStore, cloudPrintInterface,
257                          documentInfo, opt_isOpenPdfInPreview) {
258       assert(printTicketStore.isTicketValid(),
259              'Trying to print when ticket is not valid');
260
261       var ticket = {
262         'pageRange': printTicketStore.pageRange.getDocumentPageRanges(),
263         'pageCount': printTicketStore.pageRange.getPageNumberSet().size,
264         'landscape': printTicketStore.landscape.getValue(),
265         'color': printTicketStore.color.getValue() ?
266             NativeLayer.ColorMode_.COLOR : NativeLayer.ColorMode_.GRAY,
267         'headerFooterEnabled': printTicketStore.headerFooter.getValue(),
268         'marginsType': printTicketStore.marginsType.getValue(),
269         'generateDraftData': true, // TODO(rltoscano): What should this be?
270         'duplex': printTicketStore.duplex.getValue() ?
271             NativeLayer.DuplexMode.LONG_EDGE : NativeLayer.DuplexMode.SIMPLEX,
272         'copies': printTicketStore.copies.getValueAsNumber(),
273         'collate': printTicketStore.collate.getValue(),
274         'shouldPrintBackgrounds': printTicketStore.cssBackground.getValue(),
275         'shouldPrintSelectionOnly': printTicketStore.selectionOnly.getValue(),
276         'previewModifiable': documentInfo.isModifiable,
277         'printToPDF': destination.id ==
278             print_preview.Destination.GooglePromotedId.SAVE_AS_PDF,
279         'printWithCloudPrint': !destination.isLocal,
280         'printWithPrivet': destination.isPrivet,
281         'deviceName': destination.id,
282         'isFirstRequest': false,
283         'requestID': -1,
284         'fitToPageEnabled': printTicketStore.fitToPage.getValue(),
285         'pageWidth': documentInfo.pageSize.width,
286         'pageHeight': documentInfo.pageSize.height
287       };
288
289       if (!destination.isLocal) {
290         // We can't set cloudPrintID if the destination is "Print with Cloud
291         // Print" because the native system will try to print to Google Cloud
292         // Print with this ID instead of opening a Google Cloud Print dialog.
293         ticket['cloudPrintID'] = destination.id;
294       }
295
296       if (printTicketStore.marginsType.isCapabilityAvailable() &&
297           printTicketStore.marginsType.isValueEqual(
298               print_preview.ticket_items.MarginsType.Value.CUSTOM)) {
299         var customMargins = printTicketStore.customMargins.getValue();
300         var orientationEnum =
301             print_preview.ticket_items.CustomMargins.Orientation;
302         ticket['marginsCustom'] = {
303           'marginTop': customMargins.get(orientationEnum.TOP),
304           'marginRight': customMargins.get(orientationEnum.RIGHT),
305           'marginBottom': customMargins.get(orientationEnum.BOTTOM),
306           'marginLeft': customMargins.get(orientationEnum.LEFT)
307         };
308       }
309
310       if (destination.isPrivet) {
311         ticket['ticket'] = printTicketStore.createPrintTicket(destination);
312         ticket['capabilities'] = JSON.stringify(destination.capabilities);
313       }
314
315       if (opt_isOpenPdfInPreview) {
316         ticket['OpenPDFInPreview'] = true;
317       }
318
319       chrome.send('print', [JSON.stringify(ticket)]);
320     },
321
322     /** Requests that the current pending print request be cancelled. */
323     startCancelPendingPrint: function() {
324       chrome.send('cancelPendingPrintRequest');
325     },
326
327     /** Shows the system's native printing dialog. */
328     startShowSystemDialog: function() {
329       chrome.send('showSystemDialog');
330     },
331
332     /** Shows Google Cloud Print's web-based print dialog.
333      * @param {number} pageCount Number of pages to print.
334      */
335     startShowCloudPrintDialog: function(pageCount) {
336       chrome.send('printWithCloudPrintDialog', [pageCount]);
337     },
338
339     /** Closes the print preview dialog. */
340     startCloseDialog: function() {
341       chrome.send('closePrintPreviewDialog');
342       chrome.send('dialogClose');
343     },
344
345     /** Hide the print preview dialog and allow the native layer to close it. */
346     startHideDialog: function() {
347       chrome.send('hidePreview');
348     },
349
350     /**
351      * Opens the Google Cloud Print sign-in tab. The DESTINATIONS_RELOAD event
352      *     will be dispatched in response.
353      * @param {boolean} addAccount Whether to open an 'add a new account' or
354      *     default sign in page.
355      */
356     startCloudPrintSignIn: function(addAccount) {
357       chrome.send('signIn', [addAccount]);
358     },
359
360     /** Navigates the user to the system printer settings interface. */
361     startManageLocalDestinations: function() {
362       chrome.send('manageLocalPrinters');
363     },
364
365     /** Navigates the user to the Google Cloud Print management page. */
366     startManageCloudDestinations: function() {
367       chrome.send('manageCloudPrinters');
368     },
369
370     /** Forces browser to open a new tab with the given URL address. */
371     startForceOpenNewTab: function(url) {
372       chrome.send('forceOpenNewTab', [url]);
373     },
374
375     /**
376      * @param {!Object} initialSettings Object containing all initial settings.
377      */
378     onSetInitialSettings_: function(initialSettings) {
379       var numberFormatSymbols =
380           print_preview.MeasurementSystem.parseNumberFormat(
381               initialSettings['numberFormat']);
382       var unitType = print_preview.MeasurementSystem.UnitType.IMPERIAL;
383       if (initialSettings['measurementSystem'] != null) {
384         unitType = initialSettings['measurementSystem'];
385       }
386
387       var nativeInitialSettings = new print_preview.NativeInitialSettings(
388           initialSettings['printAutomaticallyInKioskMode'] || false,
389           initialSettings['hidePrintWithSystemDialogLink'] || false,
390           numberFormatSymbols[0] || ',',
391           numberFormatSymbols[1] || '.',
392           unitType,
393           initialSettings['previewModifiable'] || false,
394           initialSettings['initiatorTitle'] || '',
395           initialSettings['documentHasSelection'] || false,
396           initialSettings['shouldPrintSelectionOnly'] || false,
397           initialSettings['printerName'] || null,
398           initialSettings['appState'] || null);
399
400       var initialSettingsSetEvent = new Event(
401           NativeLayer.EventType.INITIAL_SETTINGS_SET);
402       initialSettingsSetEvent.initialSettings = nativeInitialSettings;
403       this.dispatchEvent(initialSettingsSetEvent);
404     },
405
406     /**
407      * Turn on the integration of Cloud Print.
408      * @param {string} cloudPrintURL The URL to use for cloud print servers.
409      * @private
410      */
411     onSetUseCloudPrint_: function(cloudPrintURL) {
412       var cloudPrintEnableEvent = new Event(
413           NativeLayer.EventType.CLOUD_PRINT_ENABLE);
414       cloudPrintEnableEvent.baseCloudPrintUrl = cloudPrintURL;
415       this.dispatchEvent(cloudPrintEnableEvent);
416     },
417
418     /**
419      * Updates the print preview with local printers.
420      * Called from PrintPreviewHandler::SetupPrinterList().
421      * @param {Array} printers Array of printer info objects.
422      * @private
423      */
424     onSetPrinters_: function(printers) {
425       var localDestsSetEvent = new Event(
426           NativeLayer.EventType.LOCAL_DESTINATIONS_SET);
427       localDestsSetEvent.destinationInfos = printers;
428       this.dispatchEvent(localDestsSetEvent);
429     },
430
431     /**
432      * Called when native layer gets settings information for a requested local
433      * destination.
434      * @param {Object} settingsInfo printer setting information.
435      * @private
436      */
437     onUpdateWithPrinterCapabilities_: function(settingsInfo) {
438       var capsSetEvent = new Event(NativeLayer.EventType.CAPABILITIES_SET);
439       capsSetEvent.settingsInfo = settingsInfo;
440       this.dispatchEvent(capsSetEvent);
441     },
442
443     /**
444      * Called when native layer gets settings information for a requested local
445      * destination.
446      * @param {string} printerId printer affected by error.
447      * @private
448      */
449     onFailedToGetPrinterCapabilities_: function(destinationId) {
450       var getCapsFailEvent = new Event(
451           NativeLayer.EventType.GET_CAPABILITIES_FAIL);
452       getCapsFailEvent.destinationId = destinationId;
453       getCapsFailEvent.destinationOrigin =
454           print_preview.Destination.Origin.LOCAL;
455       this.dispatchEvent(getCapsFailEvent);
456     },
457
458     /**
459      * Called when native layer gets settings information for a requested privet
460      * destination.
461      * @param {string} printerId printer affected by error.
462      * @private
463      */
464     onFailedToGetPrivetPrinterCapabilities_: function(destinationId) {
465       var getCapsFailEvent = new Event(
466           NativeLayer.EventType.GET_CAPABILITIES_FAIL);
467       getCapsFailEvent.destinationId = destinationId;
468       getCapsFailEvent.destinationOrigin =
469           print_preview.Destination.Origin.PRIVET;
470       this.dispatchEvent(getCapsFailEvent);
471     },
472
473     /** Reloads the printer list. */
474     onReloadPrintersList_: function() {
475       cr.dispatchSimpleEvent(this, NativeLayer.EventType.DESTINATIONS_RELOAD);
476     },
477
478     /**
479      * Called from the C++ layer.
480      * Take the PDF data handed to us and submit it to the cloud, closing the
481      * print preview dialog once the upload is successful.
482      * @param {string} data Data to send as the print job.
483      * @private
484      */
485     onPrintToCloud_: function(data) {
486       var printToCloudEvent = new Event(
487           NativeLayer.EventType.PRINT_TO_CLOUD);
488       printToCloudEvent.data = data;
489       this.dispatchEvent(printToCloudEvent);
490     },
491
492     /**
493      * Called from PrintPreviewUI::OnFileSelectionCancelled to notify the print
494      * preview dialog regarding the file selection cancel event.
495      * @private
496      */
497     onFileSelectionCancelled_: function() {
498       cr.dispatchSimpleEvent(this, NativeLayer.EventType.FILE_SELECTION_CANCEL);
499     },
500
501     /**
502      * Called from PrintPreviewUI::OnFileSelectionCompleted to notify the print
503      * preview dialog regarding the file selection completed event.
504      * @private
505      */
506     onFileSelectionCompleted_: function() {
507       // If the file selection is completed and the dialog is not already closed
508       // it means that a pending print to pdf request exists.
509       cr.dispatchSimpleEvent(
510           this, NativeLayer.EventType.FILE_SELECTION_COMPLETE);
511     },
512
513     /**
514      * Display an error message when print preview fails.
515      * Called from PrintPreviewMessageHandler::OnPrintPreviewFailed().
516      * @private
517      */
518     onPrintPreviewFailed_: function() {
519       cr.dispatchSimpleEvent(
520           this, NativeLayer.EventType.PREVIEW_GENERATION_FAIL);
521     },
522
523     /**
524      * Display an error message when encountered invalid printer settings.
525      * Called from PrintPreviewMessageHandler::OnInvalidPrinterSettings().
526      * @private
527      */
528     onInvalidPrinterSettings_: function() {
529       cr.dispatchSimpleEvent(this, NativeLayer.EventType.SETTINGS_INVALID);
530     },
531
532     /**
533      * @param {{contentWidth: number, contentHeight: number, marginLeft: number,
534      *          marginRight: number, marginTop: number, marginBottom: number,
535      *          printableAreaX: number, printableAreaY: number,
536      *          printableAreaWidth: number, printableAreaHeight: number}}
537      *          pageLayout Specifies default page layout details in points.
538      * @param {boolean} hasCustomPageSizeStyle Indicates whether the previewed
539      *     document has a custom page size style.
540      * @private
541      */
542     onDidGetDefaultPageLayout_: function(pageLayout, hasCustomPageSizeStyle) {
543       var pageLayoutChangeEvent = new Event(
544           NativeLayer.EventType.PAGE_LAYOUT_READY);
545       pageLayoutChangeEvent.pageLayout = pageLayout;
546       pageLayoutChangeEvent.hasCustomPageSizeStyle = hasCustomPageSizeStyle;
547       this.dispatchEvent(pageLayoutChangeEvent);
548     },
549
550     /**
551      * Update the page count and check the page range.
552      * Called from PrintPreviewUI::OnDidGetPreviewPageCount().
553      * @param {number} pageCount The number of pages.
554      * @param {number} previewResponseId The preview request id that resulted in
555      *      this response.
556      * @private
557      */
558     onDidGetPreviewPageCount_: function(pageCount, previewResponseId) {
559       var pageCountChangeEvent = new Event(
560           NativeLayer.EventType.PAGE_COUNT_READY);
561       pageCountChangeEvent.pageCount = pageCount;
562       pageCountChangeEvent.previewResponseId = previewResponseId;
563       this.dispatchEvent(pageCountChangeEvent);
564     },
565
566     /**
567      * Notification that a print preview page has been rendered.
568      * Check if the settings have changed and request a regeneration if needed.
569      * Called from PrintPreviewUI::OnDidPreviewPage().
570      * @param {number} pageNumber The page number, 0-based.
571      * @param {number} previewUid Preview unique identifier.
572      * @param {number} previewResponseId The preview request id that resulted in
573      *     this response.
574      * @private
575      */
576     onDidPreviewPage_: function(pageNumber, previewUid, previewResponseId) {
577       var pagePreviewGenEvent = new Event(
578           NativeLayer.EventType.PAGE_PREVIEW_READY);
579       pagePreviewGenEvent.pageIndex = pageNumber;
580       pagePreviewGenEvent.previewUid = previewUid;
581       pagePreviewGenEvent.previewResponseId = previewResponseId;
582       this.dispatchEvent(pagePreviewGenEvent);
583     },
584
585     /**
586      * Notification that access token is ready.
587      * @param {string} authType Type of access token.
588      * @param {string} accessToken Access token.
589      * @private
590      */
591     onDidGetAccessToken_: function(authType, accessToken) {
592       var getAccessTokenEvent = new Event(
593           NativeLayer.EventType.ACCESS_TOKEN_READY);
594       getAccessTokenEvent.authType = authType;
595       getAccessTokenEvent.accessToken = accessToken;
596       this.dispatchEvent(getAccessTokenEvent);
597     },
598
599     /**
600      * Update the print preview when new preview data is available.
601      * Create the PDF plugin as needed.
602      * Called from PrintPreviewUI::PreviewDataIsAvailable().
603      * @param {number} previewUid Preview unique identifier.
604      * @param {number} previewResponseId The preview request id that resulted in
605      *     this response.
606      * @private
607      */
608     onUpdatePrintPreview_: function(previewUid, previewResponseId) {
609       var previewGenDoneEvent = new Event(
610           NativeLayer.EventType.PREVIEW_GENERATION_DONE);
611       previewGenDoneEvent.previewUid = previewUid;
612       previewGenDoneEvent.previewResponseId = previewResponseId;
613       this.dispatchEvent(previewGenDoneEvent);
614     },
615
616     /**
617      * Updates the fit to page option state based on the print scaling option of
618      * source pdf. PDF's have an option to enable/disable print scaling. When we
619      * find out that the print scaling option is disabled for the source pdf, we
620      * uncheck the fitToPage_ to page checkbox. This function is called from C++
621      * code.
622      * @private
623      */
624     onPrintScalingDisabledForSourcePDF_: function() {
625       cr.dispatchSimpleEvent(this, NativeLayer.EventType.DISABLE_SCALING);
626     },
627
628     /**
629      * Simulates a user click on the print preview dialog cancel button. Used
630      * only for testing.
631      * @private
632      */
633     autoCancelForTesting_: function() {
634       var properties = {view: window, bubbles: true, cancelable: true};
635       var click = new MouseEvent('click', properties);
636       document.querySelector('#print-header .cancel').dispatchEvent(click);
637     },
638
639     /**
640      * @param {{serviceName: string, name: string}} printer Specifies
641      *     information about the printer that was added.
642      * @private
643      */
644     onPrivetPrinterChanged_: function(printer) {
645       var privetPrinterChangedEvent =
646             new Event(NativeLayer.EventType.PRIVET_PRINTER_CHANGED);
647       privetPrinterChangedEvent.printer = printer;
648       this.dispatchEvent(privetPrinterChangedEvent);
649     },
650
651     /**
652      * @param {Object} printer Specifies information about the printer that was
653      *    added.
654      * @private
655      */
656     onPrivetCapabilitiesSet_: function(printer, capabilities) {
657       var privetCapabilitiesSetEvent =
658             new Event(NativeLayer.EventType.PRIVET_CAPABILITIES_SET);
659       privetCapabilitiesSetEvent.printer = printer;
660       privetCapabilitiesSetEvent.capabilities = capabilities;
661       this.dispatchEvent(privetCapabilitiesSetEvent);
662     },
663
664     /**
665      * @param {string} http_error The HTTP response code or -1 if not an HTTP
666      *    error.
667      * @private
668      */
669     onPrivetPrintFailed_: function(http_error) {
670       var privetPrintFailedEvent =
671             new Event(NativeLayer.EventType.PRIVET_PRINT_FAILED);
672       privetPrintFailedEvent.httpError = http_error;
673       this.dispatchEvent(privetPrintFailedEvent);
674     }
675   };
676
677   /**
678    * Initial settings retrieved from the native layer.
679    * @param {boolean} isInKioskAutoPrintMode Whether the print preview should be
680    *     in auto-print mode.
681    * @param {string} thousandsDelimeter Character delimeter of thousands digits.
682    * @param {string} decimalDelimeter Character delimeter of the decimal point.
683    * @param {!print_preview.MeasurementSystem.UnitType} unitType Unit type of
684    *     local machine's measurement system.
685    * @param {boolean} isDocumentModifiable Whether the document to print is
686    *     modifiable.
687    * @param {string} documentTitle Title of the document.
688    * @param {boolean} documentHasSelection Whether the document has selected
689    *     content.
690    * @param {boolean} selectionOnly Whether only selected content should be
691    *     printed.
692    * @param {?string} systemDefaultDestinationId ID of the system default
693    *     destination.
694    * @param {?string} serializedAppStateStr Serialized app state.
695    * @constructor
696    */
697   function NativeInitialSettings(
698       isInKioskAutoPrintMode,
699       hidePrintWithSystemDialogLink,
700       thousandsDelimeter,
701       decimalDelimeter,
702       unitType,
703       isDocumentModifiable,
704       documentTitle,
705       documentHasSelection,
706       selectionOnly,
707       systemDefaultDestinationId,
708       serializedAppStateStr) {
709
710     /**
711      * Whether the print preview should be in auto-print mode.
712      * @type {boolean}
713      * @private
714      */
715     this.isInKioskAutoPrintMode_ = isInKioskAutoPrintMode;
716
717     /**
718      * Whether we should hide the link which shows the system print dialog.
719      * @type {boolean}
720      * @private
721      */
722     this.hidePrintWithSystemDialogLink_ = hidePrintWithSystemDialogLink;
723
724     /**
725      * Character delimeter of thousands digits.
726      * @type {string}
727      * @private
728      */
729     this.thousandsDelimeter_ = thousandsDelimeter;
730
731     /**
732      * Character delimeter of the decimal point.
733      * @type {string}
734      * @private
735      */
736     this.decimalDelimeter_ = decimalDelimeter;
737
738     /**
739      * Unit type of local machine's measurement system.
740      * @type {string}
741      * @private
742      */
743     this.unitType_ = unitType;
744
745     /**
746      * Whether the document to print is modifiable.
747      * @type {boolean}
748      * @private
749      */
750     this.isDocumentModifiable_ = isDocumentModifiable;
751
752     /**
753      * Title of the document.
754      * @type {string}
755      * @private
756      */
757     this.documentTitle_ = documentTitle;
758
759     /**
760      * Whether the document has selection.
761      * @type {string}
762      * @private
763      */
764     this.documentHasSelection_ = documentHasSelection;
765
766     /**
767      * Whether selection only should be printed.
768      * @type {string}
769      * @private
770      */
771     this.selectionOnly_ = selectionOnly;
772
773     /**
774      * ID of the system default destination.
775      * @type {?string}
776      * @private
777      */
778     this.systemDefaultDestinationId_ = systemDefaultDestinationId;
779
780     /**
781      * Serialized app state.
782      * @type {?string}
783      * @private
784      */
785     this.serializedAppStateStr_ = serializedAppStateStr;
786   };
787
788   NativeInitialSettings.prototype = {
789     /**
790      * @return {boolean} Whether the print preview should be in auto-print mode.
791      */
792     get isInKioskAutoPrintMode() {
793       return this.isInKioskAutoPrintMode_;
794     },
795
796     /**
797      * @return {boolean} Whether we should hide the link which shows the
798            system print dialog.
799      */
800     get hidePrintWithSystemDialogLink() {
801       return this.hidePrintWithSystemDialogLink_;
802     },
803
804     /** @return {string} Character delimeter of thousands digits. */
805     get thousandsDelimeter() {
806       return this.thousandsDelimeter_;
807     },
808
809     /** @return {string} Character delimeter of the decimal point. */
810     get decimalDelimeter() {
811       return this.decimalDelimeter_;
812     },
813
814     /**
815      * @return {!print_preview.MeasurementSystem.UnitType} Unit type of local
816      *     machine's measurement system.
817      */
818     get unitType() {
819       return this.unitType_;
820     },
821
822     /** @return {boolean} Whether the document to print is modifiable. */
823     get isDocumentModifiable() {
824       return this.isDocumentModifiable_;
825     },
826
827     /** @return {string} Document title. */
828     get documentTitle() {
829       return this.documentTitle_;
830     },
831
832     /** @return {bool} Whether the document has selection. */
833     get documentHasSelection() {
834       return this.documentHasSelection_;
835     },
836
837     /** @return {bool} Whether selection only should be printed. */
838     get selectionOnly() {
839       return this.selectionOnly_;
840     },
841
842     /** @return {?string} ID of the system default destination. */
843     get systemDefaultDestinationId() {
844       return this.systemDefaultDestinationId_;
845     },
846
847     /** @return {?string} Serialized app state. */
848     get serializedAppStateStr() {
849       return this.serializedAppStateStr_;
850     }
851   };
852
853   // Export
854   return {
855     NativeInitialSettings: NativeInitialSettings,
856     NativeLayer: NativeLayer
857   };
858 });