summaryrefslogtreecommitdiffstats
path: root/chrome/browser/resources/print_preview.js
blob: edb66535b944ee1d82bf4db4921d73964ac7ad52 (plain)
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
// 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.

var localStrings = new LocalStrings();
var hasPDFPlugin = true;
var expectedPageCount = 0;
var pageRangesInfo = [];
var printJobTitle = '';

/**
 * Window onload handler, sets up the page.
 */
function load() {
  $('printer-list').disabled = true;
  $('print-button').disabled = true;

  $('print-button').addEventListener('click', printFile);

  $('cancel-button').addEventListener('click', function(e) {
    window.close();
  });

  $('pages').addEventListener('input', selectPageRange);
  $('pages').addEventListener('blur', validatePageRangeInfo);
  $('all-pages').addEventListener('click', handlePrintAllPages);
  $('print-pages').addEventListener('click', validatePageRangeInfo);
  $('copies').addEventListener('input', validateNumberOfCopies);
  $('copies').addEventListener('blur', handleCopiesFieldBlur);

  updateCollateCheckboxState();
  chrome.send('getPrinters');
};

/**
 * Parses the copies field text for validation and updates the state of print
 * button and collate checkbox. If the specified value is invalid, displays an
 * invalid warning icon on the text box and sets the error message as the title
 * message of text box.
 */
function validateNumberOfCopies() {
  var copiesField = $('copies');
  var message = '';
  if (!isNumberOfCopiesValid())
    message = localStrings.getString('invalidNumberOfCopiesTitleToolTip');
  copiesField.setCustomValidity(message);
  copiesField.title = message;
  updatePrintButtonState();
  updateCollateCheckboxState();
}

/**
 * Handles copies field blur event.
 */
function handleCopiesFieldBlur() {
  checkAndSetInputFieldDefaultValue($('copies'), 1);
}

/**
 * Updates the state of collate checkbox.
 *
 * Depending on the validity of 'copies' value, enables/disables the collate
 * checkbox.
 */
function updateCollateCheckboxState() {
  var copiesField = $('copies');
  var collateField = $('collate');
  collateField.disabled = !(copiesField.checkValidity() &&
                            copiesField.value > 1);
  if (collateField.disabled)
    $('collateOptionLabel').classList.add('disabled-label-text');
  else
    $('collateOptionLabel').classList.remove('disabled-label-text');
}

/**
 * Validates the copies text field value.
 * NOTE: An empty copies field text is considered valid because the blur event
 * listener of this field will set it back to a default value.
 * @return {boolean} true if the number of copies is valid else returns false.
 */
function isNumberOfCopiesValid() {
  var copiesFieldText = $('copies').value.replace(/\s/g, '');
  if (copiesFieldText == '')
    return true;

  var numericExp = /^[0-9]+$/;
  return (numericExp.test(copiesFieldText) && Number(copiesFieldText) > 0);
}

/**
 * Checks whether the input field text is empty or not. If the value is empty,
 * sets the input field default value.
 * @param {HTMLElement} inpElement An input element.
 * @param {string} defaultVal Input field default value.
 */
function checkAndSetInputFieldDefaultValue(inpElement, defaultVal) {
  var inpElementText = inpElement.value.replace(/\s/g, '');
  if (inpElementText == '')
    inpElement.value = defaultVal;
}

/**
 * Validates the 'from' and 'to' values of page range.
 * @param {string} printFromText The 'from' value of page range.
 * @param {string} printToText The 'to' value of page range.
 * @return {boolean} true if the page range is valid else returns false.
 */
function isValidPageRange(printFromText, printToText) {
  var numericExp = /^[0-9]+$/;
  if (numericExp.test(printFromText) && numericExp.test(printToText)) {
    var printFrom = Number(printFromText);
    var printTo = Number(printToText);
    if (printFrom <= printTo && printFrom != 0 && printTo != 0 &&
        printTo <= expectedPageCount) {
      return true;
    }
  }
  return false;
}

/**
 * Parses the given page range text and populates |pageRangesInfo| array.
 *
 * If the page range text is valid, this function populates the |pageRangesInfo|
 * array with page range objects and returns true. Each page range object has
 * 'from' and 'to' fields with values.
 *
 * If the page range text is invalid, returns false.
 *
 * E.g.: If the page range text is specified as '1-3,7-9,8', create an array
 * with three objects [{from:1, to:3}, {from:7, to:9}, {from:8, to:8}].
 *
 * @return {boolean} true if page range text parsing is successful else false.
 */
function parsePageRanges() {
  var pageRangeText = $('pages').value;
  var pageRangeList = pageRangeText.replace(/\s/g, '').split(',');
  pageRangesInfo = [];
  for (var i = 0; i < pageRangeList.length; i++) {
    var tempRange = pageRangeList[i].split('-');
    var tempRangeLen = tempRange.length;
    var printFrom = tempRange[0];
    var printTo;
    if (tempRangeLen > 2)
      return false;  // Invalid page range (E.g.: 1-2-3).
    else if (tempRangeLen > 1)
      printTo = tempRange[1];
    else
      printTo = tempRange[0];

    // Validate the page range information.
    if (!isValidPageRange(printFrom, printTo))
      return false;

    pageRangesInfo.push({'from': parseInt(printFrom, 10),
                         'to': parseInt(printTo, 10)});
  }
  return true;
}

/**
 * Creates a JSON string based on the values in the printer settings.
 *
 * @return {string} JSON string with print job settings.
 */
function getSettingsJSON() {
  var selectedPrinter = $('printer-list').selectedIndex;
  var printerName = '';
  if (selectedPrinter >= 0)
    printerName = $('printer-list').options[selectedPrinter].textContent;
  var printAll = $('all-pages').checked;
  var twoSided = $('two-sided').checked;
  var copies = $('copies').value;
  var collate = $('collate').checked;
  var landscape = ($('layout').options[$('layout').selectedIndex].value == '1');
  var color = ($('color').options[$('color').selectedIndex].value == '1');

  return JSON.stringify({'printerName': printerName,
                         'pageRange': pageRangesInfo,
                         'printAll': printAll,
                         'twoSided': twoSided,
                         'copies': copies,
                         'collate': collate,
                         'landscape': landscape,
                         'color': color});
}

/**
 * Asks the browser to print the preview PDF based on current print settings.
 */
function printFile() {
  chrome.send('print', [getSettingsJSON()]);
}

/**
 * Asks the browser to generate a preview PDF based on current print settings.
 */
function getPreview() {
  chrome.send('getPreview', [getSettingsJSON()]);
}

/**
 * Fill the printer list drop down.
 * @param {array} printers Array of printer names.
 */
function setPrinters(printers) {
  if (printers.length > 0) {
    for (var i = 0; i < printers.length; ++i) {
      var option = document.createElement('option');
      option.textContent = printers[i];
      $('printer-list').add(option);
    }
    $('printer-list').disabled = false;
  } else {
    var option = document.createElement('option');
    option.textContent = localStrings.getString('noPrinter');
    $('printer-list').add(option);
  }

  // Once the printer list is populated, generate the initial preview.
  getPreview();
}

function onPDFLoad() {
  $('pdf-viewer').fitToHeight();
}

/**
 * Update the print preview when new preview data is available.
 * Create the PDF plugin as needed.
 * @param {number} pageCount The expected total pages count.
 * @param {string} jobTitle The print job title.
 *
 */
function updatePrintPreview(pageCount, jobTitle) {
  // Set the expected page count.
  if (expectedPageCount != pageCount) {
    expectedPageCount = pageCount;
    // Set the initial page range text.
    $('pages').value = '1-' + expectedPageCount;
  }

  // Set the print job title.
  printJobTitle = jobTitle;

  // Update the current tab title.
  document.title = localStrings.getStringF('printPreviewTitleFormat', jobTitle);

  createPDFPlugin();
}

/**
 * Create the PDF plugin or reload the existing one.
 */
function createPDFPlugin() {
  if (!hasPDFPlugin) {
    return;
  }

  // Enable the print button.
  if (!$('printer-list').disabled) {
    $('print-button').disabled = false;
  }

  if ($('pdf-viewer')) {
    $('pdf-viewer').reload();
    return;
  }

  var loadingElement = $('loading');
  loadingElement.classList.add('hidden');
  var mainView = loadingElement.parentNode;

  var pdfPlugin = document.createElement('object');
  pdfPlugin.setAttribute('id', 'pdf-viewer');
  pdfPlugin.setAttribute('type', 'application/pdf');
  pdfPlugin.setAttribute('src', 'chrome://print/print.pdf');
  mainView.appendChild(pdfPlugin);
  if (!pdfPlugin.onload) {
    hasPDFPlugin = false;
    mainView.removeChild(pdfPlugin);
    $('no-plugin').classList.remove('hidden');
    return;
  }
  pdfPlugin.onload('onPDFLoad()');
}

function selectPageRange() {
  $('print-pages').checked = true;
}

/**
 * Validates the page range text.
 *
 * If the page range text is an empty string, initializes the text value to
 * a default page range and updates the state of print button.
 *
 * If the page range text is not an empty string, parses the page range text
 * for validation. If the specified page range text is valid, |pageRangesInfo|
 * array will have the page ranges information.
 * If the specified page range is invalid, displays an invalid warning icon on
 * the text box and sets the error message as the title message of text box.
 */
function validatePageRangeInfo() {
  var pageRangeField = $('pages');

  checkAndSetInputFieldDefaultValue(pageRangeField, ('1-' + expectedPageCount));

  if ($('print-pages').checked) {
    var message = '';
    if (!parsePageRanges())
      message = localStrings.getString('pageRangeInvalidTitleToolTip');
    pageRangeField.setCustomValidity(message);
    pageRangeField.title = message;
  }
  updatePrintButtonState();
}

/**
 * Handles the 'All' pages option click event.
 */
function handlePrintAllPages() {
  pageRangesInfo = [];
  updatePrintButtonState();
}

/**
 * Updates the state of print button depending on the user selection.
 *
 * If the user has selected 'All' pages option, enables the print button.
 * If the user has selected a page range, depending on the validity of page
 * range text enables/disables the print button.
 * Depending on the validity of 'copies' value, enables/disables the print
 * button.
 */
function updatePrintButtonState() {
  $('print-button').disabled = (!($('all-pages').checked ||
                                  $('pages').checkValidity()) ||
                                !$('copies').checkValidity());
}

window.addEventListener('DOMContentLoaded', load);