1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// require: cr/ui/print_preview_cloud.js
var localStrings = new LocalStrings();
// If useCloudPrint is true we attempt to connect to cloud print
// and populate the list of printers with cloud print printers.
var useCloudPrint = false;
// Store the last selected printer index.
var lastSelectedPrinterIndex = 0;
// Used to disable some printing options when the preview is not modifiable.
var previewModifiable = false;
// Destination list special value constants.
const ADD_CLOUD_PRINTER = 'addCloudPrinter';
const MANAGE_CLOUD_PRINTERS = 'manageCloudPrinters';
const MANAGE_LOCAL_PRINTERS = 'manageLocalPrinters';
const MORE_PRINTERS = 'morePrinters';
const SIGN_IN = 'signIn';
const PRINT_TO_PDF = 'Print to PDF';
// State of the print preview settings.
var printSettings = new PrintSettings();
// The name of the default or last used printer.
var defaultOrLastUsedPrinterName = '';
// True when a pending print preview request exists.
var hasPendingPreviewRequest = false;
// The ID of the last preview request.
var lastPreviewRequestID = -1;
// True when a pending print file request exists.
var hasPendingPrintDocumentRequest = false;
// True when preview tab is hidden.
var isTabHidden = false;
// Object holding all the pages related settings.
var pageSettings;
// Object holding all the copies related settings.
var copiesSettings;
// Object holding all the layout related settings.
var layoutSettings;
// Object holding all the color related settings.
var colorSettings;
// True if the user has click 'Advanced...' in order to open the system print
// dialog.
var showingSystemDialog = false;
// The range of options in the printer dropdown controlled by cloud print.
var firstCloudPrintOptionPos = 0;
var lastCloudPrintOptionPos = firstCloudPrintOptionPos;
// TODO(abodenha@chromium.org) A lot of cloud print specific logic has
// made its way into this file. Refactor to create a cleaner boundary
// between print preview and GCP code. Reference bug 88098 when fixing.
// A dictionary of cloud printers that have been added to the printer
// dropdown.
var addedCloudPrinters = {};
// The maximum number of cloud printers to allow in the dropdown.
const maxCloudPrinters = 10;
/**
* Window onload handler, sets up the page and starts print preview by getting
* the printer list.
*/
function onLoad() {
cr.enablePlatformSpecificCSSRules();
if (!checkCompatiblePluginExists()) {
disableInputElementsInSidebar();
displayErrorMessageWithButton(localStrings.getString('noPlugin'),
localStrings.getString('launchNativeDialog'),
launchNativePrintDialog);
$('mainview').parentElement.removeChild($('dummy-viewer'));
return;
}
$('system-dialog-link').addEventListener('click', onSystemDialogLinkClicked);
$('mainview').parentElement.removeChild($('dummy-viewer'));
$('printer-list').disabled = true;
printHeader = print_preview.PrintHeader.getInstance();
pageSettings = print_preview.PageSettings.getInstance();
copiesSettings = print_preview.CopiesSettings.getInstance();
layoutSettings = print_preview.LayoutSettings.getInstance();
colorSettings = print_preview.ColorSettings.getInstance();
printHeader.addEventListeners();
pageSettings.addEventListeners();
copiesSettings.addEventListeners();
layoutSettings.addEventListeners();
colorSettings.addEventListeners();
showLoadingAnimation();
chrome.send('getDefaultPrinter');
}
/**
* Adds event listeners to the settings controls.
*/
function addEventListeners() {
// Controls that require preview rendering.
$('printer-list').onchange = updateControlsWithSelectedPrinterCapabilities;
}
/**
* Removes event listeners from the settings controls.
*/
function removeEventListeners() {
if (pageSettings)
clearTimeout(pageSettings.timerId_);
// Controls that require preview rendering
$('printer-list').onchange = null;
}
/**
* Disables the input elements in the sidebar.
*/
function disableInputElementsInSidebar() {
var els = $('sidebar').querySelectorAll('input, button, select');
for (var i = 0; i < els.length; i++)
els[i].disabled = true;
}
/**
* Disables the controls in the sidebar, shows the throbber and instructs the
* backend to open the native print dialog.
*/
function onSystemDialogLinkClicked() {
showingSystemDialog = true;
disableInputElementsInSidebar();
$('system-dialog-throbber').classList.remove('hidden');
chrome.send('showSystemDialog');
}
/**
* Similar to onSystemDialogLinkClicked(), but specific to the
* 'Launch native print dialog' UI.
*/
function launchNativePrintDialog() {
showingSystemDialog = true;
$('error-button').disabled = true;
$('native-print-dialog-throbber').classList.remove('hidden');
chrome.send('showSystemDialog');
}
/**
* Disables the controls which need the initiator tab to generate preview
* data. This function is called when the initiator tab is closed.
* @param {string} initiatorTabURL The URL of the initiator tab.
*/
function onInitiatorTabClosed(initiatorTabURL) {
disableInputElementsInSidebar();
displayErrorMessageWithButton(
localStrings.getString('initiatorTabClosed'),
localStrings.getString('reopenPage'),
function() { window.location = initiatorTabURL; });
}
/**
* Gets the selected printer capabilities and updates the controls accordingly.
*/
function updateControlsWithSelectedPrinterCapabilities() {
var printerList = $('printer-list');
var selectedIndex = printerList.selectedIndex;
if (selectedIndex < 0)
return;
var skip_refresh = false;
var selectedValue = printerList.options[selectedIndex].value;
if (cloudprint.isCloudPrint(printerList.options[selectedIndex])) {
updateWithCloudPrinterCapabilities();
skip_refresh = true;
} else if (selectedValue == SIGN_IN ||
selectedValue == MANAGE_CLOUD_PRINTERS ||
selectedValue == MANAGE_LOCAL_PRINTERS ||
selectedValue == ADD_CLOUD_PRINTER) {
printerList.selectedIndex = lastSelectedPrinterIndex;
chrome.send(selectedValue);
skip_refresh = true;
} else if (selectedValue == MORE_PRINTERS) {
onSystemDialogLinkClicked();
skip_refresh = true;
} else if (selectedValue == PRINT_TO_PDF) {
updateWithPrinterCapabilities({
'disableColorOption': true,
'setColorAsDefault': true,
'setDuplexAsDefault': false,
'disableCopiesOption': true});
} else {
// This message will call back to 'updateWithPrinterCapabilities'
// function.
chrome.send('getPrinterCapabilities', [selectedValue]);
}
if (!skip_refresh) {
lastSelectedPrinterIndex = selectedIndex;
// Regenerate the preview data based on selected printer settings.
setDefaultValuesAndRegeneratePreview();
}
}
/**
* Updates the printer capabilities for the currently selected
* cloud print printer.
*/
function updateWithCloudPrinterCapabilities() {
var printerList = $('printer-list');
var selectedIndex = printerList.selectedIndex;
cloudprint.updatePrinterCaps(printerList.options[selectedIndex],
doUpdateCloudPrinterCapabilities);
}
/**
* Helper function to do the actual work of updating cloud printer
* capabilities.
* @param {Object} printer The printer object to set capabilities for.
*/
function doUpdateCloudPrinterCapabilities(printer) {
var settings = {'disableColorOption': !cloudprint.supportsColor(printer),
'setColorAsDefault': cloudprint.colorIsDefault(printer),
'disableCopiesOption': true,
'disableLandscapeOption': true};
updateWithPrinterCapabilities(settings);
var printerList = $('printer-list');
var selectedIndex = printerList.selectedIndex;
lastSelectedPrinterIndex = selectedIndex;
// Regenerate the preview data based on selected printer settings.
setDefaultValuesAndRegeneratePreview();
}
/**
* Updates the controls with printer capabilities information.
* @param {Object} settingInfo printer setting information.
*/
function updateWithPrinterCapabilities(settingInfo) {
var customEvent = new cr.Event("printerCapabilitiesUpdated");
customEvent.printerCapabilities = settingInfo;
document.dispatchEvent(customEvent);
}
/**
* Turn on the integration of Cloud Print.
* @param {boolean} enable True if cloud print should be used.
* @param {string} cloudPrintUrl The URL to use for cloud print servers.
*/
function setUseCloudPrint(enable, cloudPrintURL) {
useCloudPrint = enable;
cloudprint.setBaseURL(cloudPrintURL);
}
/**
* Take the PDF data handed to us and submit it to the cloud, closing the print
* preview tab once the upload is successful.
* @param {string} data Data to send as the print job.
*/
function printToCloud(data) {
cloudprint.printToCloud(data, finishedCloudPrinting);
}
/**
* Cloud print upload of the PDF file is finished, time to close the dialog.
*/
function finishedCloudPrinting() {
window.location = cloudprint.getBaseURL();
}
/**
* Checks whether the specified settings are valid.
*
* @return {boolean} true if settings are valid, false if not.
*/
function areSettingsValid() {
return pageSettings.isPageSelectionValid() &&
(copiesSettings.isValid() ||
getSelectedPrinterName() == PRINT_TO_PDF);
}
/**
* Creates an object based on the values in the printer settings.
*
* @return {Object} Object containing print job settings.
*/
function getSettings() {
var deviceName = getSelectedPrinterName();
var printToPDF = (deviceName == PRINT_TO_PDF);
var settings =
{'deviceName': deviceName,
'pageRange': pageSettings.selectedPageRanges,
'printAll': pageSettings.allPagesRadioButton.checked,
'duplex': copiesSettings.duplexMode,
'copies': copiesSettings.numberOfCopies,
'collate': copiesSettings.isCollated(),
'landscape': layoutSettings.isLandscape(),
'color': colorSettings.isColor(),
'printToPDF': printToPDF,
'requestID': 0};
var printerList = $('printer-list');
var selectedPrinter = printerList.selectedIndex;
if (cloudprint.isCloudPrint(printerList.options[selectedPrinter])) {
settings['cloudPrintID'] =
printerList.options[selectedPrinter].value;
}
return settings;
}
/**
* @return {number} The next unused preview request id.
*/
function generatePreviewRequestID() {
return ++lastPreviewRequestID;
}
/**
* @return {boolean} True iff a preview has been requested.
*/
function hasRequestedPreview() {
return lastPreviewRequestID > -1;
}
/**
* Checks if |previewResponseId| matches |lastPreviewRequestId|. Used to ignore
* obsolete preview data responses.
* @param {number} previewResponseId The id to check.
* @return {boolean} True if previewResponseId reffers to the expected response.
*/
function isExpectedPreviewResponse(previewResponseId) {
return lastPreviewRequestID == previewResponseId;
}
/**
* Returns the name of the selected printer or the empty string if no
* printer is selected.
* @return {string} The name of the currently selected printer.
*/
function getSelectedPrinterName() {
var printerList = $('printer-list')
var selectedPrinter = printerList.selectedIndex;
if (selectedPrinter < 0)
return '';
return printerList.options[selectedPrinter].value;
}
/**
* Asks the browser to print the preview PDF based on current print
* settings. If the preview is still loading, printPendingFile() will get
* called once the preview loads.
*/
function requestToPrintDocument() {
hasPendingPrintDocumentRequest = hasPendingPreviewRequest;
var printToPDF = getSelectedPrinterName() == PRINT_TO_PDF;
if (hasPendingPrintDocumentRequest) {
if (printToPDF) {
// TODO(thestig) disable controls here.
} else {
isTabHidden = true;
chrome.send('hidePreview');
}
return;
}
if (printToPDF) {
sendPrintDocumentRequest();
} else {
removeEventListeners();
window.setTimeout(function() { sendPrintDocumentRequest(); }, 1000);
}
}
/**
* Asks the browser to print the pending preview PDF that just finished
* loading.
*/
function requestToPrintPendingDocument() {
hasPendingPrintDocumentRequest = false;
if (!areSettingsValid()) {
if (isTabHidden)
cancelPendingPrintRequest();
return;
}
sendPrintDocumentRequest();
}
/**
* Sends a message to cancel the pending print request.
*/
function cancelPendingPrintRequest() {
chrome.send('cancelPendingPrintRequest');
}
/**
* Sends a message to initiate print workflow.
*/
function sendPrintDocumentRequest() {
var printerList = $('printer-list');
var printer = printerList[printerList.selectedIndex];
chrome.send('saveLastPrinter', [printer.textContent,
cloudprint.getData(printer)]);
chrome.send('print', [JSON.stringify(getSettings()),
cloudprint.getPrintTicketJSON(printer)]);
}
/**
* Asks the browser to generate a preview PDF based on current print settings.
*/
function requestPrintPreview() {
hasPendingPreviewRequest = true;
removeEventListeners();
printSettings.save();
if (!isTabHidden)
showLoadingAnimation();
var settings = getSettings();
settings.requestID = generatePreviewRequestID();
chrome.send('getPreview', [JSON.stringify(settings)]);
}
/**
* Called from PrintPreviewUI::OnFileSelectionCancelled to notify the print
* preview tab regarding the file selection cancel event.
*/
function fileSelectionCancelled() {
// TODO(thestig) re-enable controls here.
}
/**
* Set the default printer. If there is one, generate a print preview.
* @param {string} printer Name of the default printer. Empty if none.
* @param {string} cloudPrintData Cloud print related data to restore if
* the default printer is a cloud printer.
*/
function setDefaultPrinter(printer_name, cloudPrintData) {
// Add a placeholder value so the printer list looks valid.
addDestinationListOption('', '', true, true, true);
if (printer_name) {
defaultOrLastUsedPrinterName = printer_name;
if (cloudPrintData) {
cloudprint.setDefaultPrinter(printer_name,
cloudPrintData,
addCloudPrinters,
doUpdateCloudPrinterCapabilities);
} else {
$('printer-list')[0].value = defaultOrLastUsedPrinterName;
updateControlsWithSelectedPrinterCapabilities();
}
}
chrome.send('getPrinters');
}
/**
* Fill the printer list drop down.
* Called from PrintPreviewHandler::SendPrinterList().
* @param {Array} printers Array of printer info objects.
*/
function setPrinters(printers) {
var printerList = $('printer-list');
// Remove empty entry added by setDefaultPrinter.
if (printerList[0] && printerList[0].textContent == '')
printerList.remove(0);
for (var i = 0; i < printers.length; ++i) {
var isDefault = (printers[i].deviceName == defaultOrLastUsedPrinterName);
addDestinationListOption(printers[i].printerName, printers[i].deviceName,
isDefault, false, false);
}
if (printers.length != 0)
addDestinationListOption('', '', false, true, true);
// Adding option for saving PDF to disk.
addDestinationListOption(localStrings.getString('printToPDF'),
PRINT_TO_PDF,
defaultOrLastUsedPrinterName == PRINT_TO_PDF,
false,
false);
addDestinationListOption('', '', false, true, true);
// Add options to manage printers.
if (!cr.isChromeOS) {
addDestinationListOption(localStrings.getString('manageLocalPrinters'),
MANAGE_LOCAL_PRINTERS, false, false, false);
}
if (useCloudPrint) {
// Fetch recent printers.
cloudprint.fetchPrinters(addCloudPrinters, false);
// Fetch the full printer list.
cloudprint.fetchPrinters(addCloudPrinters, true);
addDestinationListOption(localStrings.getString('manageCloudPrinters'),
MANAGE_CLOUD_PRINTERS, false, false, false);
}
printerList.disabled = false;
if (!hasRequestedPreview())
updateControlsWithSelectedPrinterCapabilities();
}
/**
* Creates an option that can be added to the printer destination list.
* @param {string} optionText specifies the option text content.
* @param {string} optionValue specifies the option value.
* @param {boolean} isDefault is true if the option needs to be selected.
* @param {boolean} isDisabled is true if the option needs to be disabled.
* @param {boolean} isSeparator is true if the option is a visual separator and
* needs to be disabled.
* @return {Object} The created option.
*/
function createDestinationListOption(optionText, optionValue, isDefault,
isDisabled, isSeparator) {
var option = document.createElement('option');
option.textContent = optionText;
option.value = optionValue;
option.selected = isDefault;
option.disabled = isSeparator || isDisabled;
// Adding attribute for improved accessibility.
if (isSeparator)
option.setAttribute("role", "separator");
return option;
}
/**
* Adds an option to the printer destination list.
* @param {string} optionText specifies the option text content.
* @param {string} optionValue specifies the option value.
* @param {boolean} isDefault is true if the option needs to be selected.
* @param {boolean} isDisabled is true if the option needs to be disabled.
* @return {Object} The created option.
*/
function addDestinationListOption(optionText, optionValue, isDefault,
isDisabled, isSeparator) {
var option = createDestinationListOption(optionText,
optionValue,
isDefault,
isDisabled,
isSeparator);
$('printer-list').add(option);
return option;
}
/**
* Adds an option to the printer destination list at a specified position.
* @param {number} position The index in the printer-list wher the option
should be created.
* @param {string} optionText specifies the option text content.
* @param {string} optionValue specifies the option value.
* @param {boolean} isDefault is true if the option needs to be selected.
* @param {boolean} isDisabled is true if the option needs to be disabled.
* @return {Object} The created option.
*/
function addDestinationListOptionAtPosition(position,
optionText,
optionValue,
isDefault,
isDisabled,
isSeparator) {
var option = createDestinationListOption(optionText,
optionValue,
isDefault,
isDisabled,
isSeparator);
var printerList = $('printer-list');
var before = printerList[position];
printerList.add(option, before);
return option;
}
/**
* Test if a particular cloud printer has already been added to the
* printer dropdown.
* @param {string} id A unique value to track this printer.
* @return {boolean} True if this id has previously been passed to
* trackCloudPrinterAdded.
*/
function cloudPrinterAlreadyAdded(id) {
return (addedCloudPrinters[id]);
}
/**
* Record that a cloud printer will added to the printer dropdown.
* @param {string} id A unique value to track this printer.
* @return {boolean} False if adding this printer would exceed
* |maxCloudPrinters|.
*/
function trackCloudPrinterAdded(id) {
if (Object.keys(addedCloudPrinters).length < maxCloudPrinters) {
addedCloudPrinters[id] = true;
return true;
} else {
return false;
}
}
/**
* Add cloud printers to the list drop down.
* Called from the cloudprint object on receipt of printer information from the
* cloud print server.
* @param {Array} printers Array of printer info objects.
* @return {Object} The currently selected printer.
*/
function addCloudPrinters(printers) {
var isFirstPass = false;
var showMorePrintersOption = false;
var printerList = $('printer-list');
if (firstCloudPrintOptionPos == lastCloudPrintOptionPos) {
isFirstPass = true;
// Remove empty entry added by setDefaultPrinter.
if (printerList[0] && printerList[0].textContent == '')
printerList.remove(0);
var option = addDestinationListOptionAtPosition(
lastCloudPrintOptionPos++,
localStrings.getString('cloudPrinters'),
'Label',
false,
true,
false);
cloudprint.setCloudPrint(option, null, null);
}
if (printers != null) {
if (printers.length == 0) {
addDestinationListOptionAtPosition(lastCloudPrintOptionPos++,
localStrings.getString('addCloudPrinter'),
ADD_CLOUD_PRINTER,
false,
false,
false);
} else {
for (var i = 0; i < printers.length; i++) {
if (!cloudPrinterAlreadyAdded(printers[i]['id'])) {
if (!trackCloudPrinterAdded(printers[i]['id'])) {
showMorePrintersOption = true;
break;
}
var option = addDestinationListOptionAtPosition(
lastCloudPrintOptionPos++,
printers[i]['name'],
printers[i]['id'],
printers[i]['name'] == defaultOrLastUsedPrinterName,
false,
false);
cloudprint.setCloudPrint(option,
printers[i]['name'],
printers[i]['id']);
}
}
if (showMorePrintersOption) {
addDestinationListOptionAtPosition(lastCloudPrintOptionPos++,
'',
'',
false,
true,
true);
addDestinationListOptionAtPosition(lastCloudPrintOptionPos++,
localStrings.getString('morePrinters'),
MORE_PRINTERS, false, false, false);
}
}
} else {
if (!cloudPrinterAlreadyAdded(SIGN_IN)) {
addDestinationListOptionAtPosition(lastCloudPrintOptionPos++,
localStrings.getString('signIn'),
SIGN_IN,
false,
false,
false);
trackCloudPrinterAdded(SIGN_IN);
}
}
if (isFirstPass) {
addDestinationListOptionAtPosition(lastCloudPrintOptionPos,
'',
'',
false,
true,
true);
addDestinationListOptionAtPosition(lastCloudPrintOptionPos + 1,
localStrings.getString('localPrinters'),
'',
false,
true,
false);
}
var selectedPrinter = printerList.selectedIndex;
if (selectedPrinter < 0)
return null;
return printerList.options[selectedPrinter];
}
/**
* Sets the color mode for the PDF plugin.
* Called from PrintPreviewHandler::ProcessColorSetting().
* @param {boolean} color is true if the PDF plugin should display in color.
*/
function setColor(color) {
var pdfViewer = $('pdf-viewer');
if (!pdfViewer) {
return;
}
pdfViewer.grayscale(!color);
var printerList = $('printer-list');
cloudprint.setColor(printerList[printerList.selectedIndex], color);
}
/**
* Display an error message in the center of the preview area.
* @param {string} errorMessage The error message to be displayed.
*/
function displayErrorMessage(errorMessage) {
$('print-button').disabled = true;
$('overlay-layer').classList.remove('invisible');
$('dancing-dots-text').classList.add('hidden');
$('error-text').innerHTML = errorMessage;
$('error-text').classList.remove('hidden');
removeEventListeners();
var pdfViewer = $('pdf-viewer');
if (pdfViewer)
$('mainview').removeChild(pdfViewer);
if (isTabHidden)
cancelPendingPrintRequest();
}
/**
* Display an error message in the center of the preview area followed by a
* button.
* @param {string} errorMessage The error message to be displayed.
* @param {string} buttonText The text to be displayed within the button.
* @param {string} buttonListener The listener to be executed when the button is
* clicked.
*/
function displayErrorMessageWithButton(
errorMessage, buttonText, buttonListener) {
var errorButton = $('error-button');
errorButton.disabled = false;
errorButton.textContent = buttonText;
errorButton.onclick = buttonListener;
errorButton.classList.remove('hidden');
$('system-dialog-throbber').classList.add('hidden');
$('native-print-dialog-throbber').classList.add('hidden');
displayErrorMessage(errorMessage);
}
/**
* Display an error message when print preview fails.
* Called from PrintPreviewMessageHandler::OnPrintPreviewFailed().
*/
function printPreviewFailed() {
displayErrorMessage(localStrings.getString('previewFailed'));
}
/**
* Called when the PDF plugin loads its document.
*/
function onPDFLoad() {
if (previewModifiable) {
setPluginPreviewPageCount();
cr.dispatchSimpleEvent(document, 'updateSummary');
}
$('pdf-viewer').fitToHeight();
cr.dispatchSimpleEvent(document, 'PDFLoaded');
hideLoadingAnimation();
}
function setPluginPreviewPageCount() {
$('pdf-viewer').printPreviewPageCount(
pageSettings.previouslySelectedPages.length);
}
/**
* Update the page count and check the page range.
* Called from PrintPreviewUI::OnDidGetPreviewPageCount().
* @param {number} pageCount The number of pages.
* @param {boolean} isModifiable Indicates whether the previewed document can be
* modified.
*/
function onDidGetPreviewPageCount(pageCount, isModifiable) {
pageSettings.updateState(pageCount);
previewModifiable = isModifiable;
}
/**
* Called when no pipelining previewed pages.
*/
function reloadPreviewPages(previewUid, previewResponseId) {
if (!isExpectedPreviewResponse(previewResponseId))
return;
hasPendingPreviewRequest = false;
if (checkIfSettingsChangedAndRegeneratePreview())
return;
cr.dispatchSimpleEvent(document, 'updateSummary');
cr.dispatchSimpleEvent(document, 'updatePrintButton');
addEventListeners();
hideLoadingAnimation();
var pageSet = pageSettings.previouslySelectedPages;
for (var i = 0; i < pageSet.length; i++)
$('pdf-viewer').loadPreviewPage(getPageSrcURL(previewUid, pageSet[i]-1), i);
// TODO(dpapad): handle pending print file requests.
}
/**
* Notification that a print preview page has been rendered.
* Check if the settings have changed and request a regeneration if needed.
* Called from PrintPreviewUI::OnDidPreviewPage().
* @param {number} pageNumber The page number, 0-based.
*/
function onDidPreviewPage(pageNumber, previewUid) {
// Refactor
if (!previewModifiable)
return;
var pageIndex = pageSettings.previouslySelectedPages.indexOf(pageNumber + 1);
if (checkIfSettingsChangedAndRegeneratePreview())
return;
if (pageIndex == 0)
createPDFPlugin(previewUid);
$('pdf-viewer').loadPreviewPage(
getPageSrcURL(previewUid, pageNumber), pageIndex);
}
/**
* Update the print preview when new preview data is available.
* Create the PDF plugin as needed.
* Called from PrintPreviewUI::PreviewDataIsAvailable().
* @param {string} jobTitle The print job title.
* @param {boolean} modifiable If the preview is modifiable.
* @param {string} previewUid Preview unique identifier.
* @param {number} previewResponseId The preview request id that resulted in
* this response.
*/
function updatePrintPreview(jobTitle,
previewUid,
previewResponseId) {
if (!isExpectedPreviewResponse(previewResponseId))
return;
hasPendingPreviewRequest = false;
if (checkIfSettingsChangedAndRegeneratePreview())
return;
document.title = localStrings.getStringF('printPreviewTitleFormat', jobTitle);
if (!previewModifiable) {
// If the preview is not modifiable the plugin has not been created yet.
createPDFPlugin(previewUid);
}
cr.dispatchSimpleEvent(document, 'updateSummary');
cr.dispatchSimpleEvent(document, 'updatePrintButton');
addEventListeners();
if (hasPendingPrintDocumentRequest)
requestToPrintPendingDocument();
}
/**
* Check if any print settings changed and regenerate the preview if needed.
* @return {boolean} true if a new preview is required.
*/
function checkIfSettingsChangedAndRegeneratePreview() {
var tempPrintSettings = new PrintSettings();
tempPrintSettings.save();
if (printSettings.deviceName != tempPrintSettings.deviceName) {
updateControlsWithSelectedPrinterCapabilities();
return true;
}
if (printSettings.isLandscape != tempPrintSettings.isLandscape) {
setDefaultValuesAndRegeneratePreview();
return true;
}
if (pageSettings.requestPrintPreviewIfNeeded())
return true;
return false;
}
/**
* Create the PDF plugin or reload the existing one.
* @param {string} previewUid Preview unique identifier.
*/
function createPDFPlugin(previewUid) {
var pdfViewer = $('pdf-viewer');
if (pdfViewer) {
// Need to call this before the reload(), where the plugin resets its
// internal page count.
pdfViewer.goToPage('0');
pdfViewer.reload();
pdfViewer.grayscale(!colorSettings.isColor());
return;
}
// Get the complete preview document.
var dataIndex = previewModifiable ? '0' : '-1';
pdfViewer = document.createElement('embed');
pdfViewer.setAttribute('id', 'pdf-viewer');
pdfViewer.setAttribute('type',
'application/x-google-chrome-print-preview-pdf');
pdfViewer.setAttribute('src', getPageSrcURL(previewUid, dataIndex));
pdfViewer.setAttribute('aria-live', 'polite');
pdfViewer.setAttribute('aria-atomic', 'true');
$('mainview').appendChild(pdfViewer);
pdfViewer.onload('onPDFLoad()');
pdfViewer.removePrintButton();
pdfViewer.grayscale(true);
}
/**
* @return {boolean} true if a compatible pdf plugin exists.
*/
function checkCompatiblePluginExists() {
var dummyPlugin = $('dummy-viewer')
return !!(dummyPlugin.onload &&
dummyPlugin.goToPage &&
dummyPlugin.removePrintButton &&
dummyPlugin.loadPreviewPage &&
dummyPlugin.printPreviewPageCount);
}
window.addEventListener('DOMContentLoaded', onLoad);
/**
* Sets the default values and sends a request to regenerate preview data.
*/
function setDefaultValuesAndRegeneratePreview() {
pageSettings.resetState();
requestPrintPreview();
}
/**
* Class that represents the state of the print settings.
*/
function PrintSettings() {
this.deviceName = '';
this.isLandscape = '';
}
/**
* Takes a snapshot of the print settings.
*/
PrintSettings.prototype.save = function() {
this.deviceName = getSelectedPrinterName();
this.isLandscape = layoutSettings.isLandscape();
}
/// Pull in all other scripts in a single shot.
<include src="print_preview_animations.js"/>
<include src="print_preview_cloud.js"/>
<include src="print_preview_utils.js"/>
<include src="print_header.js"/>
<include src="page_settings.js"/>
<include src="copies_settings.js"/>
<include src="layout_settings.js"/>
<include src="color_settings.js"/>
|