1 // Copyright 2014 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 "ppapi/cpp/instance.h"
6 #include "ppapi/cpp/instance_handle.h"
7 #include "ppapi/cpp/message_handler.h"
8 #include "ppapi/cpp/module.h"
9 #include "ppapi/cpp/var.h"
10 #include "ppapi/cpp/var_array.h"
11 #include "ppapi/utility/threading/simple_thread.h"
15 // Allow 'this' in initializer list
16 #pragma warning(disable : 4355)
19 class MessageHandler
: public pp::MessageHandler
{
21 virtual void HandleMessage(pp::InstanceHandle instance
,
22 const pp::Var
& message_data
) {
23 if (!message_data
.is_array()) {
27 pp::VarArray
array(message_data
);
28 pp::Var response
= SumArray(array
);
30 // Send the response back to JavaScript asynchronously.
31 pp::Instance(instance
.pp_instance()).PostMessage(response
);
34 virtual pp::Var
HandleBlockingMessage(pp::InstanceHandle instance
,
35 const pp::Var
& message_data
) {
36 if (!message_data
.is_array()) {
37 // Return an undefined value.
41 pp::VarArray
array(message_data
);
43 // Send the response back to JavaScript synchronously.
44 return SumArray(array
);
47 virtual void WasUnregistered(pp::InstanceHandle instance
) {}
49 pp::Var
SumArray(const pp::VarArray
& array
) {
51 for (uint32_t i
= 0, length
= array
.GetLength(); i
< length
; ++i
) {
52 if (!array
.Get(i
).is_int()) {
56 result
+= array
.Get(i
).AsInt();
59 return pp::Var(result
);
63 class Instance
: public pp::Instance
{
65 explicit Instance(PP_Instance instance
)
66 : pp::Instance(instance
), thread_(this) {}
68 virtual bool Init(uint32_t /*argc*/,
69 const char* /*argn*/ [],
70 const char* /*argv*/ []) {
73 // The message handler must be registered using a message loop that is not
74 // the main thread's messaging loop. This call will fail otherwise.
75 RegisterMessageHandler(&message_handler_
, thread_
.message_loop());
80 pp::SimpleThread thread_
;
81 MessageHandler message_handler_
;
84 class Module
: public pp::Module
{
86 Module() : pp::Module() {}
89 virtual pp::Instance
* CreateInstance(PP_Instance instance
) {
90 return new Instance(instance
);
95 Module
* CreateModule() { return new ::Module(); }