Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / native_client_sdk / src / examples / api / messaging / messaging.cc
bloba6415f0a37cb36acae3e908e8a6373beb6093985
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"
13 #ifdef WIN32
14 #undef PostMessage
15 // Allow 'this' in initializer list
16 #pragma warning(disable : 4355)
17 #endif
19 class MessageHandler : public pp::MessageHandler {
20 public:
21 virtual void HandleMessage(pp::InstanceHandle instance,
22 const pp::Var& message_data) {
23 if (!message_data.is_array()) {
24 return;
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.
38 return pp::Var();
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) {
50 int32_t result = 0;
51 for (uint32_t i = 0, length = array.GetLength(); i < length; ++i) {
52 if (!array.Get(i).is_int()) {
53 continue;
56 result += array.Get(i).AsInt();
59 return pp::Var(result);
63 class Instance : public pp::Instance {
64 public:
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*/ []) {
71 thread_.Start();
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());
76 return true;
79 private:
80 pp::SimpleThread thread_;
81 MessageHandler message_handler_;
84 class Module : public pp::Module {
85 public:
86 Module() : pp::Module() {}
87 virtual ~Module() {}
89 virtual pp::Instance* CreateInstance(PP_Instance instance) {
90 return new Instance(instance);
94 namespace pp {
95 Module* CreateModule() { return new ::Module(); }
96 } // namespace pp