Roll src/third_party/WebKit 3aea697:d9c6159 (svn 201973:201974)
[chromium-blink-merge.git] / components / pdf_viewer / pdf_viewer.cc
blobfbdd506a6f38552af9e92be819c58403b14ca964
1 // Copyright 2015 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.
5 #include "base/bind.h"
6 #include "base/callback.h"
7 #include "base/containers/hash_tables.h"
8 #include "base/memory/scoped_ptr.h"
9 #include "components/view_manager/public/cpp/types.h"
10 #include "components/view_manager/public/cpp/view.h"
11 #include "components/view_manager/public/cpp/view_observer.h"
12 #include "components/view_manager/public/cpp/view_surface.h"
13 #include "components/view_manager/public/cpp/view_tree_connection.h"
14 #include "components/view_manager/public/cpp/view_tree_delegate.h"
15 #include "components/view_manager/public/interfaces/compositor_frame.mojom.h"
16 #include "components/view_manager/public/interfaces/gpu.mojom.h"
17 #include "components/view_manager/public/interfaces/surface_id.mojom.h"
18 #include "gpu/GLES2/gl2chromium.h"
19 #include "gpu/GLES2/gl2extchromium.h"
20 #include "mojo/application/public/cpp/application_connection.h"
21 #include "mojo/application/public/cpp/application_delegate.h"
22 #include "mojo/application/public/cpp/application_impl.h"
23 #include "mojo/application/public/cpp/application_runner.h"
24 #include "mojo/application/public/cpp/connect.h"
25 #include "mojo/application/public/cpp/content_handler_factory.h"
26 #include "mojo/application/public/cpp/interface_factory_impl.h"
27 #include "mojo/application/public/cpp/service_provider_impl.h"
28 #include "mojo/application/public/interfaces/content_handler.mojom.h"
29 #include "mojo/application/public/interfaces/shell.mojom.h"
30 #include "mojo/common/data_pipe_utils.h"
31 #include "mojo/converters/geometry/geometry_type_converters.h"
32 #include "mojo/converters/surfaces/surfaces_type_converters.h"
33 #include "mojo/converters/surfaces/surfaces_utils.h"
34 #include "mojo/public/c/gles2/gles2.h"
35 #include "mojo/public/c/system/main.h"
36 #include "mojo/public/cpp/bindings/binding.h"
37 #include "third_party/pdfium/public/fpdf_ext.h"
38 #include "third_party/pdfium/public/fpdfview.h"
39 #include "ui/gfx/geometry/rect.h"
40 #include "ui/mojo/events/input_events.mojom.h"
41 #include "ui/mojo/events/input_key_codes.mojom.h"
42 #include "ui/mojo/geometry/geometry.mojom.h"
43 #include "ui/mojo/geometry/geometry_util.h"
44 #include "v8/include/v8.h"
46 const uint32_t g_background_color = 0xFF888888;
47 const uint32_t g_transparent_color = 0x00000000;
49 namespace pdf_viewer {
50 namespace {
52 void LostContext(void*) {
53 DCHECK(false);
56 void OnGotContentHandlerID(uint32_t content_handler_id) {}
58 // BitmapUploader is useful if you want to draw a bitmap or color in a View.
59 class BitmapUploader : public mojo::SurfaceClient {
60 public:
61 explicit BitmapUploader(mojo::View* view)
62 : view_(view),
63 color_(g_transparent_color),
64 width_(0),
65 height_(0),
66 format_(BGRA),
67 next_resource_id_(1u),
68 id_namespace_(0u),
69 local_id_(0u),
70 returner_binding_(this) {
72 ~BitmapUploader() override {
73 MojoGLES2DestroyContext(gles2_context_);
76 void Init(mojo::Shell* shell) {
77 surface_ = view_->RequestSurface();
79 mojo::ServiceProviderPtr gpu_service_provider;
80 mojo::URLRequestPtr request2(mojo::URLRequest::New());
81 request2->url = mojo::String::From("mojo:view_manager");
82 shell->ConnectToApplication(request2.Pass(),
83 mojo::GetProxy(&gpu_service_provider), nullptr,
84 nullptr, base::Bind(&OnGotContentHandlerID));
85 ConnectToService(gpu_service_provider.get(), &gpu_service_);
87 mojo::CommandBufferPtr gles2_client;
88 gpu_service_->CreateOffscreenGLES2Context(GetProxy(&gles2_client));
89 gles2_context_ = MojoGLES2CreateContext(
90 gles2_client.PassInterface().PassHandle().release().value(),
91 &LostContext, NULL, mojo::Environment::GetDefaultAsyncWaiter());
92 MojoGLES2MakeCurrent(gles2_context_);
95 // Sets the color which is RGBA.
96 void SetColor(uint32_t color) {
97 if (color_ == color)
98 return;
99 color_ = color;
100 if (surface_)
101 Upload();
104 enum Format {
105 RGBA, // Pixel layout on Android.
106 BGRA, // Pixel layout everywhere else.
109 // Sets a bitmap.
110 void SetBitmap(int width,
111 int height,
112 scoped_ptr<std::vector<unsigned char>> data,
113 Format format) {
114 width_ = width;
115 height_ = height;
116 bitmap_ = data.Pass();
117 format_ = format;
118 if (surface_)
119 Upload();
122 private:
123 void Upload() {
124 gfx::Rect bounds(view_->bounds().To<gfx::Rect>());
125 mojo::PassPtr pass = mojo::CreateDefaultPass(1, bounds);
126 mojo::CompositorFramePtr frame = mojo::CompositorFrame::New();
127 frame->resources.resize(0u);
129 pass->quads.resize(0u);
130 pass->shared_quad_states.push_back(
131 mojo::CreateDefaultSQS(bounds.size()));
133 MojoGLES2MakeCurrent(gles2_context_);
134 if (bitmap_.get()) {
135 mojo::Size bitmap_size;
136 bitmap_size.width = width_;
137 bitmap_size.height = height_;
138 GLuint texture_id = BindTextureForSize(bitmap_size);
139 glTexSubImage2D(GL_TEXTURE_2D,
143 bitmap_size.width,
144 bitmap_size.height,
145 TextureFormat(),
146 GL_UNSIGNED_BYTE,
147 &((*bitmap_)[0]));
149 GLbyte mailbox[GL_MAILBOX_SIZE_CHROMIUM];
150 glGenMailboxCHROMIUM(mailbox);
151 glProduceTextureCHROMIUM(GL_TEXTURE_2D, mailbox);
152 GLuint sync_point = glInsertSyncPointCHROMIUM();
154 mojo::TransferableResourcePtr resource =
155 mojo::TransferableResource::New();
156 resource->id = next_resource_id_++;
157 resource_to_texture_id_map_[resource->id] = texture_id;
158 resource->format = mojo::RESOURCE_FORMAT_RGBA_8888;
159 resource->filter = GL_LINEAR;
160 resource->size = bitmap_size.Clone();
161 mojo::MailboxHolderPtr mailbox_holder = mojo::MailboxHolder::New();
162 mailbox_holder->mailbox = mojo::Mailbox::New();
163 for (int i = 0; i < GL_MAILBOX_SIZE_CHROMIUM; ++i)
164 mailbox_holder->mailbox->name.push_back(mailbox[i]);
165 mailbox_holder->texture_target = GL_TEXTURE_2D;
166 mailbox_holder->sync_point = sync_point;
167 resource->mailbox_holder = mailbox_holder.Pass();
168 resource->is_repeated = false;
169 resource->is_software = false;
171 mojo::QuadPtr quad = mojo::Quad::New();
172 quad->material = mojo::MATERIAL_TEXTURE_CONTENT;
174 mojo::RectPtr rect = mojo::Rect::New();
175 if (width_ <= bounds.width() && height_ <= bounds.height()) {
176 rect->width = width_;
177 rect->height = height_;
178 } else {
179 // The source bitmap is larger than the viewport. Resize it while
180 // maintaining the aspect ratio.
181 float width_ratio = static_cast<float>(width_) / bounds.width();
182 float height_ratio = static_cast<float>(height_) / bounds.height();
183 if (width_ratio > height_ratio) {
184 rect->width = bounds.width();
185 rect->height = height_ / width_ratio;
186 } else {
187 rect->height = bounds.height();
188 rect->width = width_ / height_ratio;
191 quad->rect = rect.Clone();
192 quad->opaque_rect = rect.Clone();
193 quad->visible_rect = rect.Clone();
194 quad->needs_blending = true;
195 quad->shared_quad_state_index = 0u;
197 mojo::TextureQuadStatePtr texture_state = mojo::TextureQuadState::New();
198 texture_state->resource_id = resource->id;
199 texture_state->premultiplied_alpha = true;
200 texture_state->uv_top_left = mojo::PointF::New();
201 texture_state->uv_bottom_right = mojo::PointF::New();
202 texture_state->uv_bottom_right->x = 1.f;
203 texture_state->uv_bottom_right->y = 1.f;
204 texture_state->background_color = mojo::Color::New();
205 texture_state->background_color->rgba = g_transparent_color;
206 for (int i = 0; i < 4; ++i)
207 texture_state->vertex_opacity.push_back(1.f);
208 texture_state->y_flipped = false;
210 frame->resources.push_back(resource.Pass());
211 quad->texture_quad_state = texture_state.Pass();
212 pass->quads.push_back(quad.Pass());
215 if (color_ != g_transparent_color) {
216 mojo::QuadPtr quad = mojo::Quad::New();
217 quad->material = mojo::MATERIAL_SOLID_COLOR;
218 quad->rect = mojo::Rect::From(bounds);
219 quad->opaque_rect = mojo::Rect::New();
220 quad->visible_rect = mojo::Rect::From(bounds);
221 quad->needs_blending = true;
222 quad->shared_quad_state_index = 0u;
224 mojo::SolidColorQuadStatePtr color_state =
225 mojo::SolidColorQuadState::New();
226 color_state->color = mojo::Color::New();
227 color_state->color->rgba = color_;
228 color_state->force_anti_aliasing_off = false;
230 quad->solid_color_quad_state = color_state.Pass();
231 pass->quads.push_back(quad.Pass());
234 frame->passes.push_back(pass.Pass());
236 // TODO(rjkroege, fsamuel): We should throttle frames.
237 surface_->SubmitCompositorFrame(frame.Pass());
240 uint32_t BindTextureForSize(const mojo::Size size) {
241 // TODO(jamesr): Recycle textures.
242 GLuint texture = 0u;
243 glGenTextures(1, &texture);
244 glBindTexture(GL_TEXTURE_2D, texture);
245 glTexImage2D(GL_TEXTURE_2D,
247 TextureFormat(),
248 size.width,
249 size.height,
251 TextureFormat(),
252 GL_UNSIGNED_BYTE,
254 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
255 return texture;
258 uint32_t TextureFormat() {
259 return format_ == BGRA ? GL_BGRA_EXT : GL_RGBA;
262 void SetIdNamespace(uint32_t id_namespace) {
263 id_namespace_ = id_namespace;
264 if (color_ != g_transparent_color || bitmap_.get())
265 Upload();
268 // SurfaceClient implementation.
269 void ReturnResources(
270 mojo::Array<mojo::ReturnedResourcePtr> resources) override {
271 MojoGLES2MakeCurrent(gles2_context_);
272 // TODO(jamesr): Recycle.
273 for (size_t i = 0; i < resources.size(); ++i) {
274 mojo::ReturnedResourcePtr resource = resources[i].Pass();
275 DCHECK_EQ(1, resource->count);
276 glWaitSyncPointCHROMIUM(resource->sync_point);
277 uint32_t texture_id = resource_to_texture_id_map_[resource->id];
278 DCHECK_NE(0u, texture_id);
279 resource_to_texture_id_map_.erase(resource->id);
280 glDeleteTextures(1, &texture_id);
284 mojo::View* view_;
285 mojo::GpuPtr gpu_service_;
286 scoped_ptr<mojo::ViewSurface> surface_;
287 MojoGLES2Context gles2_context_;
289 mojo::Size size_;
290 uint32_t color_;
291 int width_;
292 int height_;
293 Format format_;
294 scoped_ptr<std::vector<unsigned char>> bitmap_;
295 uint32_t next_resource_id_;
296 uint32_t id_namespace_;
297 uint32_t local_id_;
298 base::hash_map<uint32_t, uint32_t> resource_to_texture_id_map_;
299 mojo::Binding<mojo::SurfaceClient> returner_binding_;
301 DISALLOW_COPY_AND_ASSIGN(BitmapUploader);
304 class EmbedderData {
305 public:
306 EmbedderData(mojo::Shell* shell, mojo::View* root) : bitmap_uploader_(root) {
307 bitmap_uploader_.Init(shell);
308 bitmap_uploader_.SetColor(g_background_color);
311 BitmapUploader& bitmap_uploader() { return bitmap_uploader_; }
313 private:
314 BitmapUploader bitmap_uploader_;
316 DISALLOW_COPY_AND_ASSIGN(EmbedderData);
319 class PDFView : public mojo::ApplicationDelegate,
320 public mojo::ViewTreeDelegate,
321 public mojo::ViewObserver,
322 public mojo::InterfaceFactory<mojo::ViewTreeClient> {
323 public:
324 PDFView(mojo::InterfaceRequest<mojo::Application> request,
325 mojo::URLResponsePtr response)
326 : app_(this, request.Pass(), base::Bind(&PDFView::OnTerminate,
327 base::Unretained(this))),
328 current_page_(0), page_count_(0), doc_(nullptr) {
329 FetchPDF(response.Pass());
332 ~PDFView() override {
333 if (doc_)
334 FPDF_CloseDocument(doc_);
335 for (auto& roots : embedder_for_roots_) {
336 roots.first->RemoveObserver(this);
337 delete roots.second;
341 private:
342 // Overridden from ApplicationDelegate:
343 bool ConfigureIncomingConnection(
344 mojo::ApplicationConnection* connection) override {
345 connection->AddService<mojo::ViewTreeClient>(this);
346 return true;
349 // Overridden from ViewTreeDelegate:
350 void OnEmbed(mojo::View* root) override {
351 DCHECK(embedder_for_roots_.find(root) == embedder_for_roots_.end());
352 root->AddObserver(this);
353 EmbedderData* embedder_data = new EmbedderData(app_.shell(), root);
354 embedder_for_roots_[root] = embedder_data;
355 DrawBitmap(embedder_data);
358 void OnConnectionLost(mojo::ViewTreeConnection* connection) override {}
360 // Overridden from ViewObserver:
361 void OnViewBoundsChanged(mojo::View* view,
362 const mojo::Rect& old_bounds,
363 const mojo::Rect& new_bounds) override {
364 DCHECK(embedder_for_roots_.find(view) != embedder_for_roots_.end());
365 DrawBitmap(embedder_for_roots_[view]);
368 void OnViewInputEvent(mojo::View* view,
369 const mojo::EventPtr& event) override {
370 DCHECK(embedder_for_roots_.find(view) != embedder_for_roots_.end());
371 if (event->key_data &&
372 (event->action != mojo::EVENT_TYPE_KEY_PRESSED ||
373 event->key_data->is_char)) {
374 return;
377 if ((event->key_data &&
378 event->key_data->windows_key_code == mojo::KEYBOARD_CODE_DOWN) ||
379 (event->pointer_data && event->pointer_data->vertical_wheel < 0)) {
380 if (current_page_ < (page_count_ - 1)) {
381 current_page_++;
382 DrawBitmap(embedder_for_roots_[view]);
384 } else if ((event->key_data &&
385 event->key_data->windows_key_code == mojo::KEYBOARD_CODE_UP) ||
386 (event->pointer_data &&
387 event->pointer_data->vertical_wheel > 0)) {
388 if (current_page_ > 0) {
389 current_page_--;
390 DrawBitmap(embedder_for_roots_[view]);
395 void OnViewDestroyed(mojo::View* view) override {
396 DCHECK(embedder_for_roots_.find(view) != embedder_for_roots_.end());
397 const auto& it = embedder_for_roots_.find(view);
398 DCHECK(it != embedder_for_roots_.end());
399 delete it->second;
400 embedder_for_roots_.erase(it);
401 if (embedder_for_roots_.size() == 0)
402 app_.Quit();
405 // Overridden from mojo::InterfaceFactory<mojo::ViewTreeClient>:
406 void Create(
407 mojo::ApplicationConnection* connection,
408 mojo::InterfaceRequest<mojo::ViewTreeClient> request) override {
409 mojo::ViewTreeConnection::Create(this, request.Pass());
412 void DrawBitmap(EmbedderData* embedder_data) {
413 if (!doc_)
414 return;
416 FPDF_PAGE page = FPDF_LoadPage(doc_, current_page_);
417 int width = static_cast<int>(FPDF_GetPageWidth(page));
418 int height = static_cast<int>(FPDF_GetPageHeight(page));
420 scoped_ptr<std::vector<unsigned char>> bitmap;
421 bitmap.reset(new std::vector<unsigned char>);
422 bitmap->resize(width * height * 4);
424 FPDF_BITMAP f_bitmap = FPDFBitmap_CreateEx(width, height, FPDFBitmap_BGRA,
425 &(*bitmap)[0], width * 4);
426 FPDFBitmap_FillRect(f_bitmap, 0, 0, width, height, 0xFFFFFFFF);
427 FPDF_RenderPageBitmap(f_bitmap, page, 0, 0, width, height, 0, 0);
428 FPDFBitmap_Destroy(f_bitmap);
430 FPDF_ClosePage(page);
432 embedder_data->bitmap_uploader().SetBitmap(width, height, bitmap.Pass(),
433 BitmapUploader::BGRA);
436 void FetchPDF(mojo::URLResponsePtr response) {
437 data_.clear();
438 mojo::common::BlockingCopyToString(response->body.Pass(), &data_);
439 if (data_.length() >= static_cast<size_t>(std::numeric_limits<int>::max()))
440 return;
441 doc_ = FPDF_LoadMemDocument(data_.data(), static_cast<int>(data_.length()),
442 nullptr);
443 page_count_ = FPDF_GetPageCount(doc_);
446 // Callback from the quit closure. We key off this rather than
447 // ApplicationDelegate::Quit() as we don't want to shut down the messageloop
448 // when we quit (the messageloop is shared among multiple PDFViews).
449 void OnTerminate() {
450 delete this;
453 mojo::ApplicationImpl app_;
454 std::string data_;
455 int current_page_;
456 int page_count_;
457 FPDF_DOCUMENT doc_;
458 std::map<mojo::View*, EmbedderData*> embedder_for_roots_;
460 DISALLOW_COPY_AND_ASSIGN(PDFView);
463 class ContentHandlerImpl : public mojo::ContentHandler {
464 public:
465 ContentHandlerImpl(mojo::InterfaceRequest<ContentHandler> request)
466 : binding_(this, request.Pass()) {}
467 ~ContentHandlerImpl() override {}
469 private:
470 // Overridden from ContentHandler:
471 void StartApplication(mojo::InterfaceRequest<mojo::Application> request,
472 mojo::URLResponsePtr response) override {
473 new PDFView(request.Pass(), response.Pass());
476 mojo::StrongBinding<mojo::ContentHandler> binding_;
478 DISALLOW_COPY_AND_ASSIGN(ContentHandlerImpl);
481 class PDFViewer : public mojo::ApplicationDelegate,
482 public mojo::InterfaceFactory<mojo::ContentHandler> {
483 public:
484 PDFViewer() {
485 v8::V8::InitializeICU();
486 FPDF_InitLibrary();
489 ~PDFViewer() override {
490 FPDF_DestroyLibrary();
493 private:
494 // Overridden from ApplicationDelegate:
495 bool ConfigureIncomingConnection(
496 mojo::ApplicationConnection* connection) override {
497 connection->AddService(this);
498 return true;
501 // Overridden from InterfaceFactory<ContentHandler>:
502 void Create(mojo::ApplicationConnection* connection,
503 mojo::InterfaceRequest<mojo::ContentHandler> request) override {
504 new ContentHandlerImpl(request.Pass());
507 DISALLOW_COPY_AND_ASSIGN(PDFViewer);
510 } // namespace
511 } // namespace pdf_viewer
513 MojoResult MojoMain(MojoHandle application_request) {
514 mojo::ApplicationRunner runner(new pdf_viewer::PDFViewer());
515 return runner.Run(application_request);