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.
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
{
52 void LostContext(void*) {
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
{
61 explicit BitmapUploader(mojo::View
* view
)
63 color_(g_transparent_color
),
67 next_resource_id_(1u),
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
) {
105 RGBA
, // Pixel layout on Android.
106 BGRA
, // Pixel layout everywhere else.
110 void SetBitmap(int width
,
112 scoped_ptr
<std::vector
<unsigned char>> data
,
116 bitmap_
= data
.Pass();
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_
);
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
,
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_
;
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
;
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.
243 glGenTextures(1, &texture
);
244 glBindTexture(GL_TEXTURE_2D
, texture
);
245 glTexImage2D(GL_TEXTURE_2D
,
254 glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MIN_FILTER
, GL_LINEAR
);
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())
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
);
285 mojo::GpuPtr gpu_service_
;
286 scoped_ptr
<mojo::ViewSurface
> surface_
;
287 MojoGLES2Context gles2_context_
;
294 scoped_ptr
<std::vector
<unsigned char>> bitmap_
;
295 uint32_t next_resource_id_
;
296 uint32_t id_namespace_
;
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
);
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_
; }
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
> {
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
{
334 FPDF_CloseDocument(doc_
);
335 for (auto& roots
: embedder_for_roots_
) {
336 roots
.first
->RemoveObserver(this);
342 // Overridden from ApplicationDelegate:
343 bool ConfigureIncomingConnection(
344 mojo::ApplicationConnection
* connection
) override
{
345 connection
->AddService
<mojo::ViewTreeClient
>(this);
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
)) {
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)) {
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) {
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());
400 embedder_for_roots_
.erase(it
);
401 if (embedder_for_roots_
.size() == 0)
405 // Overridden from mojo::InterfaceFactory<mojo::ViewTreeClient>:
407 mojo::ApplicationConnection
* connection
,
408 mojo::InterfaceRequest
<mojo::ViewTreeClient
> request
) override
{
409 mojo::ViewTreeConnection::Create(this, request
.Pass());
412 void DrawBitmap(EmbedderData
* embedder_data
) {
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
) {
438 mojo::common::BlockingCopyToString(response
->body
.Pass(), &data_
);
439 if (data_
.length() >= static_cast<size_t>(std::numeric_limits
<int>::max()))
441 doc_
= FPDF_LoadMemDocument(data_
.data(), static_cast<int>(data_
.length()),
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).
453 mojo::ApplicationImpl app_
;
458 std::map
<mojo::View
*, EmbedderData
*> embedder_for_roots_
;
460 DISALLOW_COPY_AND_ASSIGN(PDFView
);
463 class ContentHandlerImpl
: public mojo::ContentHandler
{
465 ContentHandlerImpl(mojo::InterfaceRequest
<ContentHandler
> request
)
466 : binding_(this, request
.Pass()) {}
467 ~ContentHandlerImpl() override
{}
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
> {
485 v8::V8::InitializeICU();
489 ~PDFViewer() override
{
490 FPDF_DestroyLibrary();
494 // Overridden from ApplicationDelegate:
495 bool ConfigureIncomingConnection(
496 mojo::ApplicationConnection
* connection
) override
{
497 connection
->AddService(this);
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
);
511 } // namespace pdf_viewer
513 MojoResult
MojoMain(MojoHandle application_request
) {
514 mojo::ApplicationRunner
runner(new pdf_viewer::PDFViewer());
515 return runner
.Run(application_request
);