Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / webui / print_preview / print_preview_ui.cc
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 #include "chrome/browser/ui/webui/print_preview/print_preview_ui.h"
6
7 #include <map>
8 #include <vector>
9
10 #include "base/id_map.h"
11 #include "base/lazy_instance.h"
12 #include "base/memory/ref_counted_memory.h"
13 #include "base/metrics/histogram.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/string_split.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/synchronization/lock.h"
19 #include "base/values.h"
20 #include "chrome/browser/browser_process.h"
21 #include "chrome/browser/printing/background_printing_manager.h"
22 #include "chrome/browser/printing/print_preview_data_service.h"
23 #include "chrome/browser/profiles/profile.h"
24 #include "chrome/browser/ui/webui/metrics_handler.h"
25 #include "chrome/browser/ui/webui/print_preview/print_preview_handler.h"
26 #include "chrome/browser/ui/webui/theme_source.h"
27 #include "chrome/common/print_messages.h"
28 #include "chrome/common/url_constants.h"
29 #include "content/public/browser/url_data_source.h"
30 #include "content/public/browser/web_contents.h"
31 #include "content/public/browser/web_ui_data_source.h"
32 #include "grit/browser_resources.h"
33 #include "grit/chromium_strings.h"
34 #include "grit/generated_resources.h"
35 #include "grit/google_chrome_strings.h"
36 #include "printing/page_size_margins.h"
37 #include "printing/print_job_constants.h"
38 #include "ui/base/l10n/l10n_util.h"
39 #include "ui/gfx/rect.h"
40 #include "ui/web_dialogs/web_dialog_delegate.h"
41 #include "ui/web_dialogs/web_dialog_ui.h"
42
43 using content::WebContents;
44 using printing::PageSizeMargins;
45
46 namespace {
47
48 #if defined(OS_MACOSX)
49 // U+0028 U+21E7 U+2318 U+0050 U+0029 in UTF8
50 const char kAdvancedPrintShortcut[] = "\x28\xE2\x8c\xA5\xE2\x8C\x98\x50\x29";
51 #elif defined(OS_WIN) || defined(OS_CHROMEOS)
52 const char kAdvancedPrintShortcut[] = "(Ctrl+Shift+P)";
53 #else
54 const char kAdvancedPrintShortcut[] = "(Shift+Ctrl+P)";
55 #endif
56
57 // Thread-safe wrapper around a std::map to keep track of mappings from
58 // PrintPreviewUI IDs to most recent print preview request IDs.
59 class PrintPreviewRequestIdMapWithLock {
60  public:
61   PrintPreviewRequestIdMapWithLock() {}
62   ~PrintPreviewRequestIdMapWithLock() {}
63
64   // Gets the value for |preview_id|.
65   // Returns true and sets |out_value| on success.
66   bool Get(int32 preview_id, int* out_value) {
67     base::AutoLock lock(lock_);
68     PrintPreviewRequestIdMap::const_iterator it = map_.find(preview_id);
69     if (it == map_.end())
70       return false;
71     *out_value = it->second;
72     return true;
73   }
74
75   // Sets the |value| for |preview_id|.
76   void Set(int32 preview_id, int value) {
77     base::AutoLock lock(lock_);
78     map_[preview_id] = value;
79   }
80
81   // Erases the entry for |preview_id|.
82   void Erase(int32 preview_id) {
83     base::AutoLock lock(lock_);
84     map_.erase(preview_id);
85   }
86
87  private:
88   // Mapping from PrintPreviewUI ID to print preview request ID.
89   typedef std::map<int, int> PrintPreviewRequestIdMap;
90
91   PrintPreviewRequestIdMap map_;
92   base::Lock lock_;
93
94   DISALLOW_COPY_AND_ASSIGN(PrintPreviewRequestIdMapWithLock);
95 };
96
97 // Written to on the UI thread, read from any thread.
98 base::LazyInstance<PrintPreviewRequestIdMapWithLock>
99     g_print_preview_request_id_map = LAZY_INSTANCE_INITIALIZER;
100
101 // PrintPreviewUI IDMap used to avoid exposing raw pointer addresses to WebUI.
102 // Only accessed on the UI thread.
103 base::LazyInstance<IDMap<PrintPreviewUI> >
104     g_print_preview_ui_id_map = LAZY_INSTANCE_INITIALIZER;
105
106 // PrintPreviewUI serves data for chrome://print requests.
107 //
108 // The format for requesting PDF data is as follows:
109 // chrome://print/<PrintPreviewUIID>/<PageIndex>/print.pdf
110 //
111 // Parameters (< > required):
112 //    <PrintPreviewUIID> = PrintPreview UI ID
113 //    <PageIndex> = Page index is zero-based or
114 //                  |printing::COMPLETE_PREVIEW_DOCUMENT_INDEX| to represent
115 //                  a print ready PDF.
116 //
117 // Example:
118 //    chrome://print/123/10/print.pdf
119 //
120 // Requests to chrome://print with paths not ending in /print.pdf are used
121 // to return the markup or other resources for the print preview page itself.
122 bool HandleRequestCallback(
123     const std::string& path,
124     const content::WebUIDataSource::GotDataCallback& callback) {
125   // ChromeWebUIDataSource handles most requests except for the print preview
126   // data.
127   if (!EndsWith(path, "/print.pdf", true))
128     return false;
129
130   // Print Preview data.
131   scoped_refptr<base::RefCountedBytes> data;
132   std::vector<std::string> url_substr;
133   base::SplitString(path, '/', &url_substr);
134   int preview_ui_id = -1;
135   int page_index = 0;
136   if (url_substr.size() == 3 &&
137       base::StringToInt(url_substr[0], &preview_ui_id),
138       base::StringToInt(url_substr[1], &page_index) &&
139       preview_ui_id >= 0) {
140     PrintPreviewDataService::GetInstance()->GetDataEntry(
141         preview_ui_id, page_index, &data);
142   }
143   if (data.get()) {
144     callback.Run(data.get());
145     return true;
146   }
147   // Invalid request.
148   scoped_refptr<base::RefCountedBytes> empty_bytes(new base::RefCountedBytes);
149   callback.Run(empty_bytes.get());
150   return true;
151 }
152
153 content::WebUIDataSource* CreatePrintPreviewUISource() {
154   content::WebUIDataSource* source =
155       content::WebUIDataSource::Create(chrome::kChromeUIPrintHost);
156 #if defined(OS_CHROMEOS)
157   source->AddLocalizedString("title",
158                              IDS_PRINT_PREVIEW_GOOGLE_CLOUD_PRINT_TITLE);
159 #else
160   source->AddLocalizedString("title", IDS_PRINT_PREVIEW_TITLE);
161 #endif
162   source->AddLocalizedString("loading", IDS_PRINT_PREVIEW_LOADING);
163   source->AddLocalizedString("noPlugin", IDS_PRINT_PREVIEW_NO_PLUGIN);
164   source->AddLocalizedString("launchNativeDialog",
165                              IDS_PRINT_PREVIEW_NATIVE_DIALOG);
166   source->AddLocalizedString("previewFailed", IDS_PRINT_PREVIEW_FAILED);
167   source->AddLocalizedString("invalidPrinterSettings",
168                              IDS_PRINT_INVALID_PRINTER_SETTINGS);
169   source->AddLocalizedString("printButton", IDS_PRINT_PREVIEW_PRINT_BUTTON);
170   source->AddLocalizedString("saveButton", IDS_PRINT_PREVIEW_SAVE_BUTTON);
171   source->AddLocalizedString("printing", IDS_PRINT_PREVIEW_PRINTING);
172   source->AddLocalizedString("printingToPDFInProgress",
173                              IDS_PRINT_PREVIEW_PRINTING_TO_PDF_IN_PROGRESS);
174 #if defined(OS_MACOSX)
175   source->AddLocalizedString("openingPDFInPreview",
176                              IDS_PRINT_PREVIEW_OPENING_PDF_IN_PREVIEW);
177 #endif
178   source->AddLocalizedString("destinationLabel",
179                              IDS_PRINT_PREVIEW_DESTINATION_LABEL);
180   source->AddLocalizedString("copiesLabel", IDS_PRINT_PREVIEW_COPIES_LABEL);
181   source->AddLocalizedString("examplePageRangeText",
182                              IDS_PRINT_PREVIEW_EXAMPLE_PAGE_RANGE_TEXT);
183   source->AddLocalizedString("layoutLabel", IDS_PRINT_PREVIEW_LAYOUT_LABEL);
184   source->AddLocalizedString("optionAllPages",
185                              IDS_PRINT_PREVIEW_OPTION_ALL_PAGES);
186   source->AddLocalizedString("optionBw", IDS_PRINT_PREVIEW_OPTION_BW);
187   source->AddLocalizedString("optionCollate", IDS_PRINT_PREVIEW_OPTION_COLLATE);
188   source->AddLocalizedString("optionColor", IDS_PRINT_PREVIEW_OPTION_COLOR);
189   source->AddLocalizedString("optionLandscape",
190                              IDS_PRINT_PREVIEW_OPTION_LANDSCAPE);
191   source->AddLocalizedString("optionPortrait",
192                              IDS_PRINT_PREVIEW_OPTION_PORTRAIT);
193   source->AddLocalizedString("optionTwoSided",
194                              IDS_PRINT_PREVIEW_OPTION_TWO_SIDED);
195   source->AddLocalizedString("pagesLabel", IDS_PRINT_PREVIEW_PAGES_LABEL);
196   source->AddLocalizedString("pageRangeTextBox",
197                              IDS_PRINT_PREVIEW_PAGE_RANGE_TEXT);
198   source->AddLocalizedString("pageRangeRadio",
199                              IDS_PRINT_PREVIEW_PAGE_RANGE_RADIO);
200   source->AddLocalizedString("printToPDF", IDS_PRINT_PREVIEW_PRINT_TO_PDF);
201   source->AddLocalizedString("printPreviewSummaryFormatShort",
202                              IDS_PRINT_PREVIEW_SUMMARY_FORMAT_SHORT);
203   source->AddLocalizedString("printPreviewSummaryFormatLong",
204                              IDS_PRINT_PREVIEW_SUMMARY_FORMAT_LONG);
205   source->AddLocalizedString("printPreviewSheetsLabelSingular",
206                              IDS_PRINT_PREVIEW_SHEETS_LABEL_SINGULAR);
207   source->AddLocalizedString("printPreviewSheetsLabelPlural",
208                              IDS_PRINT_PREVIEW_SHEETS_LABEL_PLURAL);
209   source->AddLocalizedString("printPreviewPageLabelSingular",
210                              IDS_PRINT_PREVIEW_PAGE_LABEL_SINGULAR);
211   source->AddLocalizedString("printPreviewPageLabelPlural",
212                              IDS_PRINT_PREVIEW_PAGE_LABEL_PLURAL);
213   const base::string16 shortcut_text(base::UTF8ToUTF16(kAdvancedPrintShortcut));
214 #if defined(OS_CHROMEOS)
215   source->AddString(
216       "systemDialogOption",
217       l10n_util::GetStringFUTF16(
218           IDS_PRINT_PREVIEW_CLOUD_DIALOG_OPTION,
219           l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT),
220           shortcut_text));
221 #else
222   source->AddString(
223       "systemDialogOption",
224       l10n_util::GetStringFUTF16(
225           IDS_PRINT_PREVIEW_SYSTEM_DIALOG_OPTION,
226           shortcut_text));
227 #endif
228   source->AddString(
229       "cloudPrintDialogOption",
230       l10n_util::GetStringFUTF16(
231           IDS_PRINT_PREVIEW_CLOUD_DIALOG_OPTION_NO_SHORTCUT,
232           l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT)));
233 #if defined(OS_MACOSX)
234   source->AddLocalizedString("openPdfInPreviewOption",
235                              IDS_PRINT_PREVIEW_OPEN_PDF_IN_PREVIEW_APP);
236 #endif
237   source->AddString(
238       "printWithCloudPrintWait",
239       l10n_util::GetStringFUTF16(
240           IDS_PRINT_PREVIEW_PRINT_WITH_CLOUD_PRINT_WAIT,
241           l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT)));
242   source->AddString(
243       "noDestsPromoLearnMoreUrl",
244       chrome::kCloudPrintNoDestinationsLearnMoreURL);
245   source->AddLocalizedString("pageRangeInstruction",
246                              IDS_PRINT_PREVIEW_PAGE_RANGE_INSTRUCTION);
247   source->AddLocalizedString("copiesInstruction",
248                              IDS_PRINT_PREVIEW_COPIES_INSTRUCTION);
249   source->AddLocalizedString("incrementTitle",
250                              IDS_PRINT_PREVIEW_INCREMENT_TITLE);
251   source->AddLocalizedString("decrementTitle",
252                              IDS_PRINT_PREVIEW_DECREMENT_TITLE);
253   source->AddLocalizedString("printPagesLabel",
254                              IDS_PRINT_PREVIEW_PRINT_PAGES_LABEL);
255   source->AddLocalizedString("optionsLabel", IDS_PRINT_PREVIEW_OPTIONS_LABEL);
256   source->AddLocalizedString("optionHeaderFooter",
257                              IDS_PRINT_PREVIEW_OPTION_HEADER_FOOTER);
258   source->AddLocalizedString("optionFitToPage",
259                              IDS_PRINT_PREVIEW_OPTION_FIT_TO_PAGE);
260   source->AddLocalizedString(
261       "optionBackgroundColorsAndImages",
262       IDS_PRINT_PREVIEW_OPTION_BACKGROUND_COLORS_AND_IMAGES);
263   source->AddLocalizedString("optionSelectionOnly",
264                              IDS_PRINT_PREVIEW_OPTION_SELECTION_ONLY);
265   source->AddLocalizedString("marginsLabel", IDS_PRINT_PREVIEW_MARGINS_LABEL);
266   source->AddLocalizedString("defaultMargins",
267                              IDS_PRINT_PREVIEW_DEFAULT_MARGINS);
268   source->AddLocalizedString("noMargins", IDS_PRINT_PREVIEW_NO_MARGINS);
269   source->AddLocalizedString("customMargins", IDS_PRINT_PREVIEW_CUSTOM_MARGINS);
270   source->AddLocalizedString("minimumMargins",
271                              IDS_PRINT_PREVIEW_MINIMUM_MARGINS);
272   source->AddLocalizedString("top", IDS_PRINT_PREVIEW_TOP_MARGIN_LABEL);
273   source->AddLocalizedString("bottom", IDS_PRINT_PREVIEW_BOTTOM_MARGIN_LABEL);
274   source->AddLocalizedString("left", IDS_PRINT_PREVIEW_LEFT_MARGIN_LABEL);
275   source->AddLocalizedString("right", IDS_PRINT_PREVIEW_RIGHT_MARGIN_LABEL);
276   source->AddLocalizedString("mediaSizeLabel",
277                              IDS_PRINT_PREVIEW_MEDIA_SIZE_LABEL);
278   source->AddLocalizedString("destinationSearchTitle",
279                              IDS_PRINT_PREVIEW_DESTINATION_SEARCH_TITLE);
280   source->AddLocalizedString("accountSelectTitle",
281                              IDS_PRINT_PREVIEW_ACCOUNT_SELECT_TITLE);
282   source->AddLocalizedString("addAccountTitle",
283                              IDS_PRINT_PREVIEW_ADD_ACCOUNT_TITLE);
284   source->AddLocalizedString("cloudPrintPromotion",
285                              IDS_PRINT_PREVIEW_CLOUD_PRINT_PROMOTION);
286   source->AddLocalizedString("searchBoxPlaceholder",
287                              IDS_PRINT_PREVIEW_SEARCH_BOX_PLACEHOLDER);
288   source->AddLocalizedString("noDestinationsMessage",
289                              IDS_PRINT_PREVIEW_NO_DESTINATIONS_MESSAGE);
290   source->AddLocalizedString("showAllButtonText",
291                              IDS_PRINT_PREVIEW_SHOW_ALL_BUTTON_TEXT);
292   source->AddLocalizedString("destinationCount",
293                              IDS_PRINT_PREVIEW_DESTINATION_COUNT);
294   source->AddLocalizedString("recentDestinationsTitle",
295                              IDS_PRINT_PREVIEW_RECENT_DESTINATIONS_TITLE);
296   source->AddLocalizedString("localDestinationsTitle",
297                              IDS_PRINT_PREVIEW_LOCAL_DESTINATIONS_TITLE);
298   source->AddLocalizedString("cloudDestinationsTitle",
299                              IDS_PRINT_PREVIEW_CLOUD_DESTINATIONS_TITLE);
300   source->AddLocalizedString("manage", IDS_PRINT_PREVIEW_MANAGE);
301   source->AddLocalizedString("setupCloudPrinters",
302                              IDS_PRINT_PREVIEW_SETUP_CLOUD_PRINTERS);
303   source->AddLocalizedString("changeDestination",
304                              IDS_PRINT_PREVIEW_CHANGE_DESTINATION);
305   source->AddLocalizedString("offlineForYear",
306                              IDS_PRINT_PREVIEW_OFFLINE_FOR_YEAR);
307   source->AddLocalizedString("offlineForMonth",
308                              IDS_PRINT_PREVIEW_OFFLINE_FOR_MONTH);
309   source->AddLocalizedString("offlineForWeek",
310                              IDS_PRINT_PREVIEW_OFFLINE_FOR_WEEK);
311   source->AddLocalizedString("offline", IDS_PRINT_PREVIEW_OFFLINE);
312   source->AddLocalizedString("fedexTos", IDS_PRINT_PREVIEW_FEDEX_TOS);
313   source->AddLocalizedString("tosCheckboxLabel",
314                              IDS_PRINT_PREVIEW_TOS_CHECKBOX_LABEL);
315   source->AddLocalizedString("noDestsPromoTitle",
316                              IDS_PRINT_PREVIEW_NO_DESTS_PROMO_TITLE);
317   source->AddLocalizedString("noDestsPromoBody",
318                              IDS_PRINT_PREVIEW_NO_DESTS_PROMO_BODY);
319   source->AddLocalizedString("noDestsPromoGcpDesc",
320                              IDS_PRINT_PREVIEW_NO_DESTS_GCP_DESC);
321   source->AddLocalizedString("learnMore",
322                              IDS_LEARN_MORE);
323   source->AddLocalizedString(
324       "noDestsPromoAddPrinterButtonLabel",
325       IDS_PRINT_PREVIEW_NO_DESTS_PROMO_ADD_PRINTER_BUTTON_LABEL);
326   source->AddLocalizedString(
327       "noDestsPromoNotNowButtonLabel",
328       IDS_PRINT_PREVIEW_NO_DESTS_PROMO_NOT_NOW_BUTTON_LABEL);
329   source->AddLocalizedString("couldNotPrint",
330                              IDS_PRINT_PREVIEW_COULD_NOT_PRINT);
331   source->AddLocalizedString("registerPromoButtonText",
332                              IDS_PRINT_PREVIEW_REGISTER_PROMO_BUTTON_TEXT);
333   source->AddLocalizedString(
334       "advancedSettingsSearchBoxPlaceholder",
335       IDS_PRINT_PREVIEW_ADVANCED_SETTINGS_SEARCH_BOX_PLACEHOLDER);
336   source->AddLocalizedString("advancedSettingsDialogTitle",
337                              IDS_PRINT_PREVIEW_ADVANCED_SETTINGS_DIALOG_TITLE);
338   source->AddLocalizedString(
339       "advancedSettingsDialogConfirm",
340       IDS_PRINT_PREVIEW_ADVANCED_SETTINGS_DIALOG_CONFIRM);
341   source->AddLocalizedString("cancel", IDS_CANCEL);
342   source->AddLocalizedString("advancedOptionsLabel",
343                              IDS_PRINT_PREVIEW_ADVANCED_OPTIONS_LABEL);
344   source->AddLocalizedString("showAdvancedOptions",
345                              IDS_PRINT_PREVIEW_SHOW_ADVANCED_OPTIONS);
346
347   source->SetJsonPath("strings.js");
348   source->AddResourcePath("print_preview.js", IDR_PRINT_PREVIEW_JS);
349   source->AddResourcePath("images/printer.png",
350                           IDR_PRINT_PREVIEW_IMAGES_PRINTER);
351   source->AddResourcePath("images/printer_shared.png",
352                           IDR_PRINT_PREVIEW_IMAGES_PRINTER_SHARED);
353   source->AddResourcePath("images/third_party.png",
354                           IDR_PRINT_PREVIEW_IMAGES_THIRD_PARTY);
355   source->AddResourcePath("images/third_party_fedex.png",
356                           IDR_PRINT_PREVIEW_IMAGES_THIRD_PARTY_FEDEX);
357   source->AddResourcePath("images/google_doc.png",
358                           IDR_PRINT_PREVIEW_IMAGES_GOOGLE_DOC);
359   source->AddResourcePath("images/pdf.png", IDR_PRINT_PREVIEW_IMAGES_PDF);
360   source->AddResourcePath("images/mobile.png", IDR_PRINT_PREVIEW_IMAGES_MOBILE);
361   source->AddResourcePath("images/mobile_shared.png",
362                           IDR_PRINT_PREVIEW_IMAGES_MOBILE_SHARED);
363   source->SetDefaultResource(IDR_PRINT_PREVIEW_HTML);
364   source->SetRequestFilter(base::Bind(&HandleRequestCallback));
365   source->OverrideContentSecurityPolicyObjectSrc("object-src 'self';");
366   return source;
367 }
368
369 PrintPreviewUI::TestingDelegate* g_testing_delegate = NULL;
370
371 }  // namespace
372
373 PrintPreviewUI::PrintPreviewUI(content::WebUI* web_ui)
374     : ConstrainedWebDialogUI(web_ui),
375       initial_preview_start_time_(base::TimeTicks::Now()),
376       id_(g_print_preview_ui_id_map.Get().Add(this)),
377       handler_(NULL),
378       source_is_modifiable_(true),
379       source_has_selection_(false),
380       dialog_closed_(false) {
381   // Set up the chrome://print/ data source.
382   Profile* profile = Profile::FromWebUI(web_ui);
383   content::WebUIDataSource::Add(profile, CreatePrintPreviewUISource());
384
385   // Set up the chrome://theme/ source.
386   content::URLDataSource::Add(profile, new ThemeSource(profile));
387
388   // WebUI owns |handler_|.
389   handler_ = new PrintPreviewHandler();
390   web_ui->AddMessageHandler(handler_);
391
392   web_ui->AddMessageHandler(new MetricsHandler());
393
394   g_print_preview_request_id_map.Get().Set(id_, -1);
395 }
396
397 PrintPreviewUI::~PrintPreviewUI() {
398   print_preview_data_service()->RemoveEntry(id_);
399   g_print_preview_request_id_map.Get().Erase(id_);
400   g_print_preview_ui_id_map.Get().Remove(id_);
401 }
402
403 void PrintPreviewUI::GetPrintPreviewDataForIndex(
404     int index,
405     scoped_refptr<base::RefCountedBytes>* data) {
406   print_preview_data_service()->GetDataEntry(id_, index, data);
407 }
408
409 void PrintPreviewUI::SetPrintPreviewDataForIndex(
410     int index,
411     const base::RefCountedBytes* data) {
412   print_preview_data_service()->SetDataEntry(id_, index, data);
413 }
414
415 void PrintPreviewUI::ClearAllPreviewData() {
416   print_preview_data_service()->RemoveEntry(id_);
417 }
418
419 int PrintPreviewUI::GetAvailableDraftPageCount() {
420   return print_preview_data_service()->GetAvailableDraftPageCount(id_);
421 }
422
423 void PrintPreviewUI::SetInitiatorTitle(
424     const base::string16& job_title) {
425   initiator_title_ = job_title;
426 }
427
428 // static
429 void PrintPreviewUI::SetInitialParams(
430     content::WebContents* print_preview_dialog,
431     const PrintHostMsg_RequestPrintPreview_Params& params) {
432   if (!print_preview_dialog || !print_preview_dialog->GetWebUI())
433     return;
434   PrintPreviewUI* print_preview_ui = static_cast<PrintPreviewUI*>(
435       print_preview_dialog->GetWebUI()->GetController());
436   print_preview_ui->source_is_modifiable_ = params.is_modifiable;
437   print_preview_ui->source_has_selection_ = params.has_selection;
438   print_preview_ui->print_selection_only_ = params.selection_only;
439 }
440
441 // static
442 void PrintPreviewUI::GetCurrentPrintPreviewStatus(int32 preview_ui_id,
443                                                   int request_id,
444                                                   bool* cancel) {
445   int current_id = -1;
446   if (!g_print_preview_request_id_map.Get().Get(preview_ui_id, &current_id)) {
447     *cancel = true;
448     return;
449   }
450   *cancel = (request_id != current_id);
451 }
452
453 int32 PrintPreviewUI::GetIDForPrintPreviewUI() const {
454   return id_;
455 }
456
457 void PrintPreviewUI::OnPrintPreviewDialogClosed() {
458   WebContents* preview_dialog = web_ui()->GetWebContents();
459   printing::BackgroundPrintingManager* background_printing_manager =
460       g_browser_process->background_printing_manager();
461   if (background_printing_manager->HasPrintPreviewDialog(preview_dialog))
462     return;
463   OnClosePrintPreviewDialog();
464 }
465
466 void PrintPreviewUI::OnInitiatorClosed() {
467   WebContents* preview_dialog = web_ui()->GetWebContents();
468   printing::BackgroundPrintingManager* background_printing_manager =
469       g_browser_process->background_printing_manager();
470   if (background_printing_manager->HasPrintPreviewDialog(preview_dialog))
471     web_ui()->CallJavascriptFunction("cancelPendingPrintRequest");
472   else
473     OnClosePrintPreviewDialog();
474 }
475
476 void PrintPreviewUI::OnPrintPreviewRequest(int request_id) {
477   if (!initial_preview_start_time_.is_null()) {
478     UMA_HISTOGRAM_TIMES("PrintPreview.InitializationTime",
479                         base::TimeTicks::Now() - initial_preview_start_time_);
480   }
481   g_print_preview_request_id_map.Get().Set(id_, request_id);
482 }
483
484 void PrintPreviewUI::OnShowSystemDialog() {
485   web_ui()->CallJavascriptFunction("onSystemDialogLinkClicked");
486 }
487
488 void PrintPreviewUI::OnDidGetPreviewPageCount(
489     const PrintHostMsg_DidGetPreviewPageCount_Params& params) {
490   DCHECK_GT(params.page_count, 0);
491   if (g_testing_delegate)
492     g_testing_delegate->DidGetPreviewPageCount(params.page_count);
493   base::FundamentalValue count(params.page_count);
494   base::FundamentalValue request_id(params.preview_request_id);
495   web_ui()->CallJavascriptFunction("onDidGetPreviewPageCount",
496                                    count,
497                                    request_id);
498 }
499
500 void PrintPreviewUI::OnDidGetDefaultPageLayout(
501     const PageSizeMargins& page_layout, const gfx::Rect& printable_area,
502     bool has_custom_page_size_style) {
503   if (page_layout.margin_top < 0 || page_layout.margin_left < 0 ||
504       page_layout.margin_bottom < 0 || page_layout.margin_right < 0 ||
505       page_layout.content_width < 0 || page_layout.content_height < 0 ||
506       printable_area.width() <= 0 || printable_area.height() <= 0) {
507     NOTREACHED();
508     return;
509   }
510
511   base::DictionaryValue layout;
512   layout.SetDouble(printing::kSettingMarginTop, page_layout.margin_top);
513   layout.SetDouble(printing::kSettingMarginLeft, page_layout.margin_left);
514   layout.SetDouble(printing::kSettingMarginBottom, page_layout.margin_bottom);
515   layout.SetDouble(printing::kSettingMarginRight, page_layout.margin_right);
516   layout.SetDouble(printing::kSettingContentWidth, page_layout.content_width);
517   layout.SetDouble(printing::kSettingContentHeight, page_layout.content_height);
518   layout.SetInteger(printing::kSettingPrintableAreaX, printable_area.x());
519   layout.SetInteger(printing::kSettingPrintableAreaY, printable_area.y());
520   layout.SetInteger(printing::kSettingPrintableAreaWidth,
521                     printable_area.width());
522   layout.SetInteger(printing::kSettingPrintableAreaHeight,
523                     printable_area.height());
524
525   base::FundamentalValue has_page_size_style(has_custom_page_size_style);
526   web_ui()->CallJavascriptFunction("onDidGetDefaultPageLayout", layout,
527                                    has_page_size_style);
528 }
529
530 void PrintPreviewUI::OnDidPreviewPage(int page_number,
531                                       int preview_request_id) {
532   DCHECK_GE(page_number, 0);
533   base::FundamentalValue number(page_number);
534   base::FundamentalValue ui_identifier(id_);
535   base::FundamentalValue request_id(preview_request_id);
536   if (g_testing_delegate)
537     g_testing_delegate->DidRenderPreviewPage(web_ui()->GetWebContents());
538   web_ui()->CallJavascriptFunction(
539       "onDidPreviewPage", number, ui_identifier, request_id);
540   if (g_testing_delegate && g_testing_delegate->IsAutoCancelEnabled())
541     web_ui()->CallJavascriptFunction("autoCancelForTesting");
542 }
543
544 void PrintPreviewUI::OnPreviewDataIsAvailable(int expected_pages_count,
545                                               int preview_request_id) {
546   VLOG(1) << "Print preview request finished with "
547           << expected_pages_count << " pages";
548
549   if (!initial_preview_start_time_.is_null()) {
550     UMA_HISTOGRAM_TIMES("PrintPreview.InitialDisplayTime",
551                         base::TimeTicks::Now() - initial_preview_start_time_);
552     UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.Initial",
553                          expected_pages_count);
554     UMA_HISTOGRAM_COUNTS(
555         "PrintPreview.RegeneratePreviewRequest.BeforeFirstData",
556         handler_->regenerate_preview_request_count());
557     initial_preview_start_time_ = base::TimeTicks();
558   }
559   base::FundamentalValue ui_identifier(id_);
560   base::FundamentalValue ui_preview_request_id(preview_request_id);
561   web_ui()->CallJavascriptFunction("updatePrintPreview", ui_identifier,
562                                    ui_preview_request_id);
563 }
564
565 void PrintPreviewUI::OnPrintPreviewDialogDestroyed() {
566   handler_->OnPrintPreviewDialogDestroyed();
567 }
568
569 void PrintPreviewUI::OnFileSelectionCancelled() {
570   web_ui()->CallJavascriptFunction("fileSelectionCancelled");
571 }
572
573 void PrintPreviewUI::OnCancelPendingPreviewRequest() {
574   g_print_preview_request_id_map.Get().Set(id_, -1);
575 }
576
577 void PrintPreviewUI::OnPrintPreviewFailed() {
578   handler_->OnPrintPreviewFailed();
579   web_ui()->CallJavascriptFunction("printPreviewFailed");
580 }
581
582 void PrintPreviewUI::OnInvalidPrinterSettings() {
583   web_ui()->CallJavascriptFunction("invalidPrinterSettings");
584 }
585
586 PrintPreviewDataService* PrintPreviewUI::print_preview_data_service() {
587   return PrintPreviewDataService::GetInstance();
588 }
589
590 void PrintPreviewUI::OnHidePreviewDialog() {
591   WebContents* preview_dialog = web_ui()->GetWebContents();
592   printing::BackgroundPrintingManager* background_printing_manager =
593       g_browser_process->background_printing_manager();
594   if (background_printing_manager->HasPrintPreviewDialog(preview_dialog))
595     return;
596
597   ConstrainedWebDialogDelegate* delegate = GetConstrainedDelegate();
598   if (!delegate)
599     return;
600   delegate->ReleaseWebContentsOnDialogClose();
601   background_printing_manager->OwnPrintPreviewDialog(preview_dialog);
602   OnClosePrintPreviewDialog();
603 }
604
605 void PrintPreviewUI::OnClosePrintPreviewDialog() {
606   if (dialog_closed_)
607     return;
608   dialog_closed_ = true;
609   ConstrainedWebDialogDelegate* delegate = GetConstrainedDelegate();
610   if (!delegate)
611     return;
612   delegate->GetWebDialogDelegate()->OnDialogClosed(std::string());
613   delegate->OnDialogCloseFromWebUI();
614 }
615
616 void PrintPreviewUI::OnReloadPrintersList() {
617   web_ui()->CallJavascriptFunction("reloadPrintersList");
618 }
619
620 void PrintPreviewUI::OnSetOptionsFromDocument(
621     const PrintHostMsg_SetOptionsFromDocument_Params& params) {
622   // Notify WebUI that print scaling is disabled
623   if (params.is_scaling_disabled)
624     web_ui()->CallJavascriptFunction("printScalingDisabledForSourcePDF");
625 }
626
627 // static
628 void PrintPreviewUI::SetDelegateForTesting(TestingDelegate* delegate) {
629   g_testing_delegate = delegate;
630 }
631
632 void PrintPreviewUI::SetSelectedFileForTesting(const base::FilePath& path) {
633   handler_->FileSelected(path, 0, NULL);
634 }
635
636 void PrintPreviewUI::SetPdfSavedClosureForTesting(
637     const base::Closure& closure) {
638   handler_->SetPdfSavedClosureForTesting(closure);
639 }