summaryrefslogtreecommitdiffstats
path: root/content/renderer/mhtml_generator.cc
blob: 6b641d56bd670fefb8a3ea9ee00f5bce3f9c32f1 (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
// 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.

#include "content/renderer/mhtml_generator.h"

#include "base/platform_file.h"
#include "content/common/view_messages.h"
#include "content/renderer/render_view_impl.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebCString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPageSerializer.h"

MHTMLGenerator::MHTMLGenerator(RenderViewImpl* render_view)
    : content::RenderViewObserver(render_view),
      file_(base::kInvalidPlatformFileValue) {
}

MHTMLGenerator::~MHTMLGenerator() {
}

// RenderViewObserver implementation:
bool MHTMLGenerator::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(MHTMLGenerator, message)
      IPC_MESSAGE_HANDLER(ViewMsg_SavePageAsMHTML, OnSavePageAsMHTML)
      IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void MHTMLGenerator::OnSavePageAsMHTML(
    int job_id, IPC::PlatformFileForTransit file_for_transit) {
  base::PlatformFile file =
      IPC::PlatformFileForTransitToPlatformFile(file_for_transit);
  file_ = file;
  int64 size = GenerateMHTML();
  base::ClosePlatformFile(file);
  NotifyBrowser(job_id, size);
}

void MHTMLGenerator::NotifyBrowser(int job_id, int64 data_size) {
  render_view()->Send(new ViewHostMsg_SavedPageAsMHTML(job_id, data_size));
  file_ = base::kInvalidPlatformFileValue;
}

// TODO(jcivelli): write the chunks in deferred tasks to give a chance to the
//                 message loop to process other events.
int64 MHTMLGenerator::GenerateMHTML() {
  WebKit::WebCString mhtml =
      WebKit::WebPageSerializer::serializeToMHTML(render_view()->GetWebView());
  const size_t chunk_size = 1024;
  const char* data = mhtml.data();
  size_t total_bytes_written = 0;
  while (total_bytes_written < mhtml.length()) {
    size_t copy_size =
        std::min(mhtml.length() - total_bytes_written, chunk_size);
    int bytes_written = base::WritePlatformFile(file_, total_bytes_written,
                                                data + total_bytes_written,
                                                copy_size);
    if (bytes_written == -1)
      return -1;
    total_bytes_written += bytes_written;
  }
  return total_bytes_written;
}