// Copyright (c) 2012 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. #include "components/printing/renderer/print_web_view_helper.h" #include #include #include #include #include "base/auto_reset.h" #include "base/json/json_writer.h" #include "base/location.h" #include "base/logging.h" #include "base/macros.h" #include "base/metrics/histogram_macros.h" #include "base/process/process_handle.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/thread_task_runner_handle.h" #include "build/build_config.h" #include "components/printing/common/print_messages.h" #include "content/public/common/web_preferences.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_thread.h" #include "content/public/renderer/render_view.h" #include "grit/components_resources.h" #include "net/base/escape.h" #include "printing/metafile_skia_wrapper.h" #include "printing/pdf_metafile_skia.h" #include "printing/units.h" #include "third_party/WebKit/public/platform/WebSize.h" #include "third_party/WebKit/public/platform/WebURLRequest.h" #include "third_party/WebKit/public/web/WebConsoleMessage.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebElement.h" #include "third_party/WebKit/public/web/WebFrameClient.h" #include "third_party/WebKit/public/web/WebFrameOwnerProperties.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebPlugin.h" #include "third_party/WebKit/public/web/WebPluginDocument.h" #include "third_party/WebKit/public/web/WebPrintParams.h" #include "third_party/WebKit/public/web/WebPrintPresetOptions.h" #include "third_party/WebKit/public/web/WebSandboxFlags.h" #include "third_party/WebKit/public/web/WebScriptSource.h" #include "third_party/WebKit/public/web/WebSettings.h" #include "third_party/WebKit/public/web/WebView.h" #include "third_party/WebKit/public/web/WebViewClient.h" #include "third_party/skia/include/core/SkCanvas.h" #include "ui/base/resource/resource_bundle.h" using content::WebPreferences; namespace printing { namespace { #define STATIC_ASSERT_ENUM(a, b) \ static_assert(static_cast(a) == static_cast(b), \ "mismatching enums: " #a) // Check blink and printing enums are kept in sync. STATIC_ASSERT_ENUM(blink::WebUnknownDuplexMode, UNKNOWN_DUPLEX_MODE); STATIC_ASSERT_ENUM(blink::WebSimplex, SIMPLEX); STATIC_ASSERT_ENUM(blink::WebLongEdge, LONG_EDGE); STATIC_ASSERT_ENUM(blink::WebShortEdge, SHORT_EDGE); enum PrintPreviewHelperEvents { PREVIEW_EVENT_REQUESTED, PREVIEW_EVENT_CACHE_HIT, // Unused PREVIEW_EVENT_CREATE_DOCUMENT, PREVIEW_EVENT_NEW_SETTINGS, // Unused PREVIEW_EVENT_MAX, }; const double kMinDpi = 1.0; #if defined(ENABLE_PRINT_PREVIEW) bool g_is_preview_enabled = true; const char kPageLoadScriptFormat[] = "document.open(); document.write(%s); document.close();"; const char kPageSetupScriptFormat[] = "setup(%s);"; void ExecuteScript(blink::WebFrame* frame, const char* script_format, const base::Value& parameters) { std::string json; base::JSONWriter::Write(parameters, &json); std::string script = base::StringPrintf(script_format, json.c_str()); frame->executeScript(blink::WebString(base::UTF8ToUTF16(script))); } #else bool g_is_preview_enabled = false; #endif // defined(ENABLE_PRINT_PREVIEW) int GetDPI(const PrintMsg_Print_Params* print_params) { #if defined(OS_MACOSX) // On the Mac, the printable area is in points, don't do any scaling based // on dpi. return kPointsPerInch; #else return static_cast(print_params->dpi); #endif // defined(OS_MACOSX) } bool PrintMsg_Print_Params_IsValid(const PrintMsg_Print_Params& params) { return !params.content_size.IsEmpty() && !params.page_size.IsEmpty() && !params.printable_area.IsEmpty() && params.document_cookie && params.desired_dpi && params.dpi && params.margin_top >= 0 && params.margin_left >= 0 && params.dpi > kMinDpi && params.document_cookie != 0; } PrintMsg_Print_Params GetCssPrintParams( blink::WebFrame* frame, int page_index, const PrintMsg_Print_Params& page_params) { PrintMsg_Print_Params page_css_params = page_params; int dpi = GetDPI(&page_params); blink::WebSize page_size_in_pixels( ConvertUnit(page_params.page_size.width(), dpi, kPixelsPerInch), ConvertUnit(page_params.page_size.height(), dpi, kPixelsPerInch)); int margin_top_in_pixels = ConvertUnit(page_params.margin_top, dpi, kPixelsPerInch); int margin_right_in_pixels = ConvertUnit( page_params.page_size.width() - page_params.content_size.width() - page_params.margin_left, dpi, kPixelsPerInch); int margin_bottom_in_pixels = ConvertUnit( page_params.page_size.height() - page_params.content_size.height() - page_params.margin_top, dpi, kPixelsPerInch); int margin_left_in_pixels = ConvertUnit( page_params.margin_left, dpi, kPixelsPerInch); blink::WebSize original_page_size_in_pixels = page_size_in_pixels; if (frame) { frame->pageSizeAndMarginsInPixels(page_index, page_size_in_pixels, margin_top_in_pixels, margin_right_in_pixels, margin_bottom_in_pixels, margin_left_in_pixels); } int new_content_width = page_size_in_pixels.width - margin_left_in_pixels - margin_right_in_pixels; int new_content_height = page_size_in_pixels.height - margin_top_in_pixels - margin_bottom_in_pixels; // Invalid page size and/or margins. We just use the default setting. if (new_content_width < 1 || new_content_height < 1) { CHECK(frame != NULL); page_css_params = GetCssPrintParams(NULL, page_index, page_params); return page_css_params; } page_css_params.content_size = gfx::Size(ConvertUnit(new_content_width, kPixelsPerInch, dpi), ConvertUnit(new_content_height, kPixelsPerInch, dpi)); if (original_page_size_in_pixels != page_size_in_pixels) { page_css_params.page_size = gfx::Size(ConvertUnit(page_size_in_pixels.width, kPixelsPerInch, dpi), ConvertUnit(page_size_in_pixels.height, kPixelsPerInch, dpi)); } else { // Printing frame doesn't have any page size css. Pixels to dpi conversion // causes rounding off errors. Therefore use the default page size values // directly. page_css_params.page_size = page_params.page_size; } page_css_params.margin_top = ConvertUnit(margin_top_in_pixels, kPixelsPerInch, dpi); page_css_params.margin_left = ConvertUnit(margin_left_in_pixels, kPixelsPerInch, dpi); return page_css_params; } double FitPrintParamsToPage(const PrintMsg_Print_Params& page_params, PrintMsg_Print_Params* params_to_fit) { double content_width = static_cast(params_to_fit->content_size.width()); double content_height = static_cast(params_to_fit->content_size.height()); int default_page_size_height = page_params.page_size.height(); int default_page_size_width = page_params.page_size.width(); int css_page_size_height = params_to_fit->page_size.height(); int css_page_size_width = params_to_fit->page_size.width(); double scale_factor = 1.0f; if (page_params.page_size == params_to_fit->page_size) return scale_factor; if (default_page_size_width < css_page_size_width || default_page_size_height < css_page_size_height) { double ratio_width = static_cast(default_page_size_width) / css_page_size_width; double ratio_height = static_cast(default_page_size_height) / css_page_size_height; scale_factor = ratio_width < ratio_height ? ratio_width : ratio_height; content_width *= scale_factor; content_height *= scale_factor; } params_to_fit->margin_top = static_cast( (default_page_size_height - css_page_size_height * scale_factor) / 2 + (params_to_fit->margin_top * scale_factor)); params_to_fit->margin_left = static_cast( (default_page_size_width - css_page_size_width * scale_factor) / 2 + (params_to_fit->margin_left * scale_factor)); params_to_fit->content_size = gfx::Size(static_cast(content_width), static_cast(content_height)); params_to_fit->page_size = page_params.page_size; return scale_factor; } void CalculatePageLayoutFromPrintParams( const PrintMsg_Print_Params& params, PageSizeMargins* page_layout_in_points) { int dpi = GetDPI(¶ms); int content_width = params.content_size.width(); int content_height = params.content_size.height(); int margin_bottom = params.page_size.height() - content_height - params.margin_top; int margin_right = params.page_size.width() - content_width - params.margin_left; page_layout_in_points->content_width = ConvertUnit(content_width, dpi, kPointsPerInch); page_layout_in_points->content_height = ConvertUnit(content_height, dpi, kPointsPerInch); page_layout_in_points->margin_top = ConvertUnit(params.margin_top, dpi, kPointsPerInch); page_layout_in_points->margin_right = ConvertUnit(margin_right, dpi, kPointsPerInch); page_layout_in_points->margin_bottom = ConvertUnit(margin_bottom, dpi, kPointsPerInch); page_layout_in_points->margin_left = ConvertUnit(params.margin_left, dpi, kPointsPerInch); } void EnsureOrientationMatches(const PrintMsg_Print_Params& css_params, PrintMsg_Print_Params* page_params) { if ((page_params->page_size.width() > page_params->page_size.height()) == (css_params.page_size.width() > css_params.page_size.height())) { return; } // Swap the |width| and |height| values. page_params->page_size.SetSize(page_params->page_size.height(), page_params->page_size.width()); page_params->content_size.SetSize(page_params->content_size.height(), page_params->content_size.width()); page_params->printable_area.set_size( gfx::Size(page_params->printable_area.height(), page_params->printable_area.width())); } void ComputeWebKitPrintParamsInDesiredDpi( const PrintMsg_Print_Params& print_params, blink::WebPrintParams* webkit_print_params) { int dpi = GetDPI(&print_params); webkit_print_params->printerDPI = dpi; webkit_print_params->printScalingOption = print_params.print_scaling_option; webkit_print_params->printContentArea.width = ConvertUnit( print_params.content_size.width(), dpi, print_params.desired_dpi); webkit_print_params->printContentArea.height = ConvertUnit( print_params.content_size.height(), dpi, print_params.desired_dpi); webkit_print_params->printableArea.x = ConvertUnit( print_params.printable_area.x(), dpi, print_params.desired_dpi); webkit_print_params->printableArea.y = ConvertUnit( print_params.printable_area.y(), dpi, print_params.desired_dpi); webkit_print_params->printableArea.width = ConvertUnit( print_params.printable_area.width(), dpi, print_params.desired_dpi); webkit_print_params->printableArea.height = ConvertUnit( print_params.printable_area.height(), dpi, print_params.desired_dpi); webkit_print_params->paperSize.width = ConvertUnit( print_params.page_size.width(), dpi, print_params.desired_dpi); webkit_print_params->paperSize.height = ConvertUnit( print_params.page_size.height(), dpi, print_params.desired_dpi); } blink::WebPlugin* GetPlugin(const blink::WebLocalFrame* frame) { return frame->document().isPluginDocument() ? frame->document().to().plugin() : NULL; } bool PrintingNodeOrPdfFrame(const blink::WebLocalFrame* frame, const blink::WebNode& node) { if (!node.isNull()) return true; blink::WebPlugin* plugin = GetPlugin(frame); return plugin && plugin->supportsPaginatedPrint(); } #if defined(ENABLE_PRINT_PREVIEW) // Returns true if the current destination printer is PRINT_TO_PDF. bool IsPrintToPdfRequested(const base::DictionaryValue& job_settings) { bool print_to_pdf = false; if (!job_settings.GetBoolean(kSettingPrintToPDF, &print_to_pdf)) NOTREACHED(); return print_to_pdf; } bool PrintingFrameHasPageSizeStyle(blink::WebFrame* frame, int total_page_count) { if (!frame) return false; bool frame_has_custom_page_size_style = false; for (int i = 0; i < total_page_count; ++i) { if (frame->hasCustomPageSizeStyle(i)) { frame_has_custom_page_size_style = true; break; } } return frame_has_custom_page_size_style; } #endif // defined(ENABLE_PRINT_PREVIEW) // Disable scaling when either: // - The PDF specifies disabling scaling. // - All the pages in the PDF are the same size, and that size is the same as // the paper size. bool PDFShouldDisableScalingBasedOnPreset( const blink::WebPrintPresetOptions& options, const PrintMsg_Print_Params& params) { if (options.isScalingDisabled) return true; if (!options.isPageSizeUniform) return false; int dpi = GetDPI(¶ms); if (!dpi) { // Likely |params| is invalid, in which case the return result does not // matter. Check for this so ConvertUnit() does not divide by zero. return true; } blink::WebSize page_size( ConvertUnit(params.page_size.width(), dpi, kPointsPerInch), ConvertUnit(params.page_size.height(), dpi, kPointsPerInch)); return options.uniformPageSize == page_size; } bool PDFShouldDisableScaling(blink::WebLocalFrame* frame, const blink::WebNode& node, const PrintMsg_Print_Params& params) { const bool kDefaultPDFShouldDisableScalingSetting = true; blink::WebPrintPresetOptions preset_options; if (!frame->getPrintPresetOptionsForPlugin(node, &preset_options)) return kDefaultPDFShouldDisableScalingSetting; return PDFShouldDisableScalingBasedOnPreset(preset_options, params); } #if defined(ENABLE_BASIC_PRINTING) MarginType GetMarginsForPdf(blink::WebLocalFrame* frame, const blink::WebNode& node, const PrintMsg_Print_Params& params) { return PDFShouldDisableScaling(frame, node, params) ? NO_MARGINS : PRINTABLE_AREA_MARGINS; } #endif #if defined(ENABLE_PRINT_PREVIEW) bool FitToPageEnabled(const base::DictionaryValue& job_settings) { bool fit_to_paper_size = false; if (!job_settings.GetBoolean(kSettingFitToPageEnabled, &fit_to_paper_size)) { NOTREACHED(); } return fit_to_paper_size; } // Returns the print scaling option to retain/scale/crop the source page size // to fit the printable area of the paper. // // We retain the source page size when the current destination printer is // SAVE_AS_PDF. // // We crop the source page size to fit the printable area or we print only the // left top page contents when // (1) Source is PDF and the user has requested not to fit to printable area // via |job_settings|. // (2) Source is PDF. This is the first preview request and print scaling // option is disabled for initiator renderer plugin. // // In all other cases, we scale the source page to fit the printable area. blink::WebPrintScalingOption GetPrintScalingOption( blink::WebLocalFrame* frame, const blink::WebNode& node, bool source_is_html, const base::DictionaryValue& job_settings, const PrintMsg_Print_Params& params) { if (params.print_to_pdf) return blink::WebPrintScalingOptionSourceSize; if (!source_is_html) { if (!FitToPageEnabled(job_settings)) return blink::WebPrintScalingOptionNone; bool no_plugin_scaling = PDFShouldDisableScaling(frame, node, params); if (params.is_first_request && no_plugin_scaling) return blink::WebPrintScalingOptionNone; } return blink::WebPrintScalingOptionFitToPrintableArea; } #endif // defined(ENABLE_PRINT_PREVIEW) PrintMsg_Print_Params CalculatePrintParamsForCss( blink::WebFrame* frame, int page_index, const PrintMsg_Print_Params& page_params, bool ignore_css_margins, bool fit_to_page, double* scale_factor) { PrintMsg_Print_Params css_params = GetCssPrintParams(frame, page_index, page_params); PrintMsg_Print_Params params = page_params; EnsureOrientationMatches(css_params, ¶ms); if (ignore_css_margins && fit_to_page) return params; PrintMsg_Print_Params result_params = css_params; if (ignore_css_margins) { result_params.margin_top = params.margin_top; result_params.margin_left = params.margin_left; DCHECK(!fit_to_page); // Since we are ignoring the margins, the css page size is no longer // valid. int default_margin_right = params.page_size.width() - params.content_size.width() - params.margin_left; int default_margin_bottom = params.page_size.height() - params.content_size.height() - params.margin_top; result_params.content_size = gfx::Size(result_params.page_size.width() - result_params.margin_left - default_margin_right, result_params.page_size.height() - result_params.margin_top - default_margin_bottom); } if (fit_to_page) { double factor = FitPrintParamsToPage(params, &result_params); if (scale_factor) *scale_factor = factor; } return result_params; } } // namespace FrameReference::FrameReference(blink::WebLocalFrame* frame) { Reset(frame); } FrameReference::FrameReference() { Reset(NULL); } FrameReference::~FrameReference() { } void FrameReference::Reset(blink::WebLocalFrame* frame) { if (frame) { view_ = frame->view(); frame_ = frame; } else { view_ = NULL; frame_ = NULL; } } blink::WebLocalFrame* FrameReference::GetFrame() { if (view_ == NULL || frame_ == NULL) return NULL; for (blink::WebFrame* frame = view_->mainFrame(); frame != NULL; frame = frame->traverseNext(false)) { if (frame == frame_) return frame_; } return NULL; } blink::WebView* FrameReference::view() { return view_; } #if defined(ENABLE_PRINT_PREVIEW) // static - Not anonymous so that platform implementations can use it. void PrintWebViewHelper::PrintHeaderAndFooter( blink::WebCanvas* canvas, int page_number, int total_pages, const blink::WebFrame& source_frame, float webkit_scale_factor, const PageSizeMargins& page_layout, const PrintMsg_Print_Params& params) { SkAutoCanvasRestore auto_restore(canvas, true); canvas->scale(1 / webkit_scale_factor, 1 / webkit_scale_factor); blink::WebSize page_size(page_layout.margin_left + page_layout.margin_right + page_layout.content_width, page_layout.margin_top + page_layout.margin_bottom + page_layout.content_height); blink::WebView* web_view = blink::WebView::create(NULL); web_view->settings()->setJavaScriptEnabled(true); blink::WebLocalFrame* frame = blink::WebLocalFrame::create(blink::WebTreeScopeType::Document, NULL); web_view->setMainFrame(frame); base::StringValue html(ResourceBundle::GetSharedInstance().GetLocalizedString( IDR_PRINT_PREVIEW_PAGE)); // Load page with script to avoid async operations. ExecuteScript(frame, kPageLoadScriptFormat, html); scoped_ptr options(new base::DictionaryValue()); options.reset(new base::DictionaryValue()); options->SetDouble(kSettingHeaderFooterDate, base::Time::Now().ToJsTime()); options->SetDouble("width", page_size.width); options->SetDouble("height", page_size.height); options->SetDouble("topMargin", page_layout.margin_top); options->SetDouble("bottomMargin", page_layout.margin_bottom); options->SetString("pageNumber", base::StringPrintf("%d/%d", page_number, total_pages)); options->SetString("url", params.url); base::string16 title = source_frame.document().title(); options->SetString("title", title.empty() ? params.title : title); ExecuteScript(frame, kPageSetupScriptFormat, *options); blink::WebPrintParams webkit_params(page_size); webkit_params.printerDPI = GetDPI(¶ms); frame->printBegin(webkit_params); frame->printPage(0, canvas); frame->printEnd(); web_view->close(); frame->close(); } #endif // defined(ENABLE_PRINT_PREVIEW) // static - Not anonymous so that platform implementations can use it. float PrintWebViewHelper::RenderPageContent(blink::WebFrame* frame, int page_number, const gfx::Rect& canvas_area, const gfx::Rect& content_area, double scale_factor, blink::WebCanvas* canvas) { SkAutoCanvasRestore auto_restore(canvas, true); canvas->translate((content_area.x() - canvas_area.x()) / scale_factor, (content_area.y() - canvas_area.y()) / scale_factor); return frame->printPage(page_number, canvas); } // Class that calls the Begin and End print functions on the frame and changes // the size of the view temporarily to support full page printing.. class PrepareFrameAndViewForPrint : public blink::WebViewClient, public blink::WebFrameClient { public: PrepareFrameAndViewForPrint(const PrintMsg_Print_Params& params, blink::WebLocalFrame* frame, const blink::WebNode& node, bool ignore_css_margins); ~PrepareFrameAndViewForPrint() override; // Optional. Replaces |frame_| with selection if needed. Will call |on_ready| // when completed. void CopySelectionIfNeeded(const WebPreferences& preferences, const base::Closure& on_ready); // Prepares frame for printing. void StartPrinting(); blink::WebLocalFrame* frame() { return frame_.GetFrame(); } const blink::WebNode& node() const { return node_to_print_; } int GetExpectedPageCount() const { return expected_pages_count_; } void FinishPrinting(); bool IsLoadingSelection() { // It's not selection if not |owns_web_view_|. return owns_web_view_ && frame() && frame()->isLoading(); } private: // blink::WebViewClient: void didStopLoading() override; // TODO(ojan): Remove this override and have this class use a non-null // layerTreeView. bool allowsBrokenNullLayerTreeView() const override; // blink::WebFrameClient: blink::WebFrame* createChildFrame( blink::WebLocalFrame* parent, blink::WebTreeScopeType scope, const blink::WebString& name, const blink::WebString& unique_name, blink::WebSandboxFlags sandbox_flags, const blink::WebFrameOwnerProperties& frame_owner_properties) override; void frameDetached(blink::WebFrame* frame, DetachType type) override; void CallOnReady(); void ResizeForPrinting(); void RestoreSize(); void CopySelection(const WebPreferences& preferences); FrameReference frame_; blink::WebNode node_to_print_; bool owns_web_view_; blink::WebPrintParams web_print_params_; gfx::Size prev_view_size_; gfx::Size prev_scroll_offset_; int expected_pages_count_; base::Closure on_ready_; bool should_print_backgrounds_; bool should_print_selection_only_; bool is_printing_started_; base::WeakPtrFactory weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(PrepareFrameAndViewForPrint); }; PrepareFrameAndViewForPrint::PrepareFrameAndViewForPrint( const PrintMsg_Print_Params& params, blink::WebLocalFrame* frame, const blink::WebNode& node, bool ignore_css_margins) : frame_(frame), node_to_print_(node), owns_web_view_(false), expected_pages_count_(0), should_print_backgrounds_(params.should_print_backgrounds), should_print_selection_only_(params.selection_only), is_printing_started_(false), weak_ptr_factory_(this) { PrintMsg_Print_Params print_params = params; if (!should_print_selection_only_ || !PrintingNodeOrPdfFrame(frame, node_to_print_)) { bool fit_to_page = ignore_css_margins && print_params.print_scaling_option == blink::WebPrintScalingOptionFitToPrintableArea; ComputeWebKitPrintParamsInDesiredDpi(params, &web_print_params_); frame->printBegin(web_print_params_, node_to_print_); print_params = CalculatePrintParamsForCss( frame, 0, print_params, ignore_css_margins, fit_to_page, NULL); frame->printEnd(); } ComputeWebKitPrintParamsInDesiredDpi(print_params, &web_print_params_); } PrepareFrameAndViewForPrint::~PrepareFrameAndViewForPrint() { FinishPrinting(); } void PrepareFrameAndViewForPrint::ResizeForPrinting() { // Layout page according to printer page size. Since WebKit shrinks the // size of the page automatically (from 125% to 200%) we trick it to // think the page is 125% larger so the size of the page is correct for // minimum (default) scaling. // This is important for sites that try to fill the page. // The 1.25 value is |printingMinimumShrinkFactor|. gfx::Size print_layout_size(web_print_params_.printContentArea.width, web_print_params_.printContentArea.height); print_layout_size.set_height( static_cast(static_cast(print_layout_size.height()) * 1.25)); if (!frame()) return; blink::WebView* web_view = frame_.view(); // Backup size and offset. if (blink::WebFrame* web_frame = web_view->mainFrame()) prev_scroll_offset_ = web_frame->scrollOffset(); prev_view_size_ = web_view->size(); web_view->resize(print_layout_size); } void PrepareFrameAndViewForPrint::StartPrinting() { ResizeForPrinting(); blink::WebView* web_view = frame_.view(); web_view->settings()->setShouldPrintBackgrounds(should_print_backgrounds_); expected_pages_count_ = frame()->printBegin(web_print_params_, node_to_print_); is_printing_started_ = true; } void PrepareFrameAndViewForPrint::CopySelectionIfNeeded( const WebPreferences& preferences, const base::Closure& on_ready) { on_ready_ = on_ready; if (should_print_selection_only_) { CopySelection(preferences); } else { // Call immediately, async call crashes scripting printing. CallOnReady(); } } void PrepareFrameAndViewForPrint::CopySelection( const WebPreferences& preferences) { ResizeForPrinting(); std::string url_str = "data:text/html;charset=utf-8,"; url_str.append( net::EscapeQueryParamValue(frame()->selectionAsMarkup().utf8(), false)); RestoreSize(); // Create a new WebView with the same settings as the current display one. // Except that we disable javascript (don't want any active content running // on the page). WebPreferences prefs = preferences; prefs.javascript_enabled = false; blink::WebView* web_view = blink::WebView::create(this); owns_web_view_ = true; content::RenderView::ApplyWebPreferences(prefs, web_view); web_view->setMainFrame( blink::WebLocalFrame::create(blink::WebTreeScopeType::Document, this)); frame_.Reset(web_view->mainFrame()->toWebLocalFrame()); node_to_print_.reset(); // When loading is done this will call didStopLoading() and that will do the // actual printing. frame()->loadRequest(blink::WebURLRequest(GURL(url_str))); } bool PrepareFrameAndViewForPrint::allowsBrokenNullLayerTreeView() const { return true; } void PrepareFrameAndViewForPrint::didStopLoading() { DCHECK(!on_ready_.is_null()); // Don't call callback here, because it can delete |this| and WebView that is // called didStopLoading. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&PrepareFrameAndViewForPrint::CallOnReady, weak_ptr_factory_.GetWeakPtr())); } blink::WebFrame* PrepareFrameAndViewForPrint::createChildFrame( blink::WebLocalFrame* parent, blink::WebTreeScopeType scope, const blink::WebString& name, const blink::WebString& unique_name, blink::WebSandboxFlags sandbox_flags, const blink::WebFrameOwnerProperties& frame_owner_properties) { blink::WebFrame* frame = blink::WebLocalFrame::create(scope, this); parent->appendChild(frame); return frame; } void PrepareFrameAndViewForPrint::frameDetached(blink::WebFrame* frame, DetachType type) { DCHECK(type == DetachType::Remove); if (frame->parent()) frame->parent()->removeChild(frame); frame->close(); } void PrepareFrameAndViewForPrint::CallOnReady() { return on_ready_.Run(); // Can delete |this|. } void PrepareFrameAndViewForPrint::RestoreSize() { if (frame()) { blink::WebView* web_view = frame_.GetFrame()->view(); web_view->resize(prev_view_size_); if (blink::WebFrame* web_frame = web_view->mainFrame()) web_frame->setScrollOffset(prev_scroll_offset_); } } void PrepareFrameAndViewForPrint::FinishPrinting() { blink::WebLocalFrame* frame = frame_.GetFrame(); if (frame) { blink::WebView* web_view = frame->view(); if (is_printing_started_) { is_printing_started_ = false; frame->printEnd(); if (!owns_web_view_) { web_view->settings()->setShouldPrintBackgrounds(false); RestoreSize(); } } if (owns_web_view_) { DCHECK(!frame->isLoading()); owns_web_view_ = false; web_view->close(); } } frame_.Reset(NULL); on_ready_.Reset(); } bool PrintWebViewHelper::Delegate::IsAskPrintSettingsEnabled() { return true; } bool PrintWebViewHelper::Delegate::IsScriptedPrintEnabled() { return true; } PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view, scoped_ptr delegate) : content::RenderViewObserver(render_view), content::RenderViewObserverTracker(render_view), reset_prep_frame_view_(false), is_print_ready_metafile_sent_(false), ignore_css_margins_(false), is_scripted_printing_blocked_(false), notify_browser_of_print_failure_(true), print_for_preview_(false), delegate_(std::move(delegate)), print_node_in_progress_(false), is_loading_(false), is_scripted_preview_delayed_(false), ipc_nesting_level_(0), weak_ptr_factory_(this) { if (!delegate_->IsPrintPreviewEnabled()) DisablePreview(); } PrintWebViewHelper::~PrintWebViewHelper() { } // static void PrintWebViewHelper::DisablePreview() { g_is_preview_enabled = false; } bool PrintWebViewHelper::IsScriptInitiatedPrintAllowed(blink::WebFrame* frame, bool user_initiated) { if (!delegate_->IsScriptedPrintEnabled()) return false; // If preview is enabled, then the print dialog is tab modal, and the user // can always close the tab on a mis-behaving page (the system print dialog // is app modal). If the print was initiated through user action, don't // throttle. Or, if the command line flag to skip throttling has been set. return !is_scripted_printing_blocked_ && (user_initiated || g_is_preview_enabled || scripting_throttler_.IsAllowed(frame)); } void PrintWebViewHelper::DidStartLoading() { is_loading_ = true; } void PrintWebViewHelper::DidStopLoading() { is_loading_ = false; if (!on_stop_loading_closure_.is_null()) { on_stop_loading_closure_.Run(); on_stop_loading_closure_.Reset(); } } // Prints |frame| which called window.print(). void PrintWebViewHelper::PrintPage(blink::WebLocalFrame* frame, bool user_initiated) { DCHECK(frame); // Allow Prerendering to cancel this print request if necessary. if (delegate_->CancelPrerender(render_view(), routing_id())) return; if (!IsScriptInitiatedPrintAllowed(frame, user_initiated)) return; if (delegate_->OverridePrint(frame)) return; if (g_is_preview_enabled) { #if defined(ENABLE_PRINT_PREVIEW) print_preview_context_.InitWithFrame(frame); RequestPrintPreview(PRINT_PREVIEW_SCRIPTED); #endif } else { #if defined(ENABLE_BASIC_PRINTING) Print(frame, blink::WebNode(), true); #endif } } bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) { // The class is not designed to handle recursive messages. This is not // expected during regular flow. However, during rendering of content for // printing, lower level code may run nested message loop. E.g. PDF may has // script to show message box http://crbug.com/502562. In that moment browser // may receive updated printer capabilities and decide to restart print // preview generation. When this happened message handling function may // choose to ignore message or safely crash process. ++ipc_nesting_level_; bool handled = true; IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message) #if defined(ENABLE_BASIC_PRINTING) IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages) IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog) #endif // defined(ENABLE_BASIC_PRINTING) #if defined(ENABLE_BASIC_PRINTING) && defined(ENABLE_PRINT_PREVIEW) IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview) #endif #if defined(ENABLE_PRINT_PREVIEW) IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone) #endif // defined(ENABLE_PRINT_PREVIEW) IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked, SetScriptedPrintBlocked) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() --ipc_nesting_level_; return handled; } bool PrintWebViewHelper::GetPrintFrame(blink::WebLocalFrame** frame) { DCHECK(frame); blink::WebView* webView = render_view()->GetWebView(); DCHECK(webView); if (!webView) return false; // If the user has selected text in the currently focused frame we print // only that frame (this makes print selection work for multiple frames). blink::WebLocalFrame* focusedFrame = webView->focusedFrame()->toWebLocalFrame(); *frame = focusedFrame->hasSelection() ? focusedFrame : webView->mainFrame()->toWebLocalFrame(); return true; } #if defined(ENABLE_BASIC_PRINTING) void PrintWebViewHelper::OnPrintPages() { if (ipc_nesting_level_> 1) return; blink::WebLocalFrame* frame; if (!GetPrintFrame(&frame)) return; // If we are printing a PDF extension frame, find the plugin node and print // that instead. auto plugin = delegate_->GetPdfElement(frame); Print(frame, plugin, false); } void PrintWebViewHelper::OnPrintForSystemDialog() { if (ipc_nesting_level_> 1) return; blink::WebLocalFrame* frame = print_preview_context_.source_frame(); if (!frame) { NOTREACHED(); return; } Print(frame, print_preview_context_.source_node(), false); } #endif // defined(ENABLE_BASIC_PRINTING) #if defined(ENABLE_BASIC_PRINTING) && defined(ENABLE_PRINT_PREVIEW) void PrintWebViewHelper::OnPrintForPrintPreview( const base::DictionaryValue& job_settings) { CHECK_LE(ipc_nesting_level_, 1); // If still not finished with earlier print request simply ignore. if (prep_frame_view_) return; if (!render_view()->GetWebView()) return; blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame(); if (!main_frame) return; blink::WebDocument document = main_frame->document(); // /