Skip to content

Instantly share code, notes, and snippets.

@martinsik
Created July 2, 2014 23:03
Show Gist options
  • Save martinsik/4055608ab996f7e0e697 to your computer and use it in GitHub Desktop.
Save martinsik/4055608ab996f7e0e697 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<!--
Copyright (c) 2013 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.
-->
<head>
<title>hello_tutorial</title>
<script type="text/javascript">
var JsonTutorialModule = null; // Global application object.
var msg = {
'action': 'sum',
'data': [2,4,11,13,23]
}
statusText = 'NO-STATUS';
function moduleDidLoad() {
JsonTutorialModule = document.getElementById('json_tutorial');
updateStatus('SUCCESS');
JsonTutorialModule.postMessage(JSON.stringify(msg));
}
function handleMessage(message_event) {
alert(message_event.data);
console.log(JSON.parse(message_event.data));
}
function pageDidLoad() {
if (JsonTutorialModule == null) {
updateStatus('LOADING...');
} else {
updateStatus();
}
}
function updateStatus(opt_message) {
if (opt_message)
statusText = opt_message;
var statusField = document.getElementById('statusField');
if (statusField) {
statusField.innerHTML = statusText;
}
}
</script>
</head>
<body onload="pageDidLoad()">
<h1>NaCl C++ Tutorial: Getting Started</h1>
<p>
<div id="listener">
<script type="text/javascript">
var listener = document.getElementById('listener');
listener.addEventListener('load', moduleDidLoad, true);
listener.addEventListener('message', handleMessage, true);
</script>
<embed id="json_tutorial"
width=0 height=0
src="json_tutorial.nmf"
type="application/x-pnacl" />
</div>
</p>
<h2>Status <code id="statusField">NO-STATUS</code></h2>
</body>
</html>
// Copyright (c) 2013 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 "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var.h"
#include <sstream>
#include "json/json.h"
class JsonTutorialInstance : public pp::Instance {
public:
explicit JsonTutorialInstance(PP_Instance instance) : pp::Instance(instance)
{}
virtual ~JsonTutorialInstance() {}
virtual void HandleMessage(const pp::Var& var_message) {
Json::Value root; // will contains the root value after parsing.
Json::Reader reader;
// try to parse message
if (!reader.parse(var_message.AsString(), root)) {
// report to the user that it failed and where it failed
std::stringstream error_message_stream("Failed to parse JSON: ");
error_message_stream << reader.getFormatedErrorMessages();
send_json("error", error_message_stream.str());
return;
}
// our root has to be an object (like JavaScript object or associative array in other languages)
if (!root.isObject()) {
send_json("error", "invalid data structure");
return;
}
// second parameter is default value
const std::string action = root.get("action", "unknown").asString();
Json::Value data = root["data"];
if (action == "sum" && data.isArray()) {
int sum = 0;
for (uint32_t i=0; i < data.size(); i++) {
sum += data[i].asInt();
}
send_json("ok", Json::Int(sum));
} else {
send_json("error", "unknown action");
}
}
void send_json(const char *status, Json::Value response_data) {
// Json::Value is wrapper structure around any data (object, array, number, string)
// we're passing to its constructor Json::objectValue which creates basically a JavaScript object
// or associative array if you want
Json::Value response = Json::Value(Json::objectValue);
response["status"] = status; // like in any other language, create key and assign in value
response["response"] = response_data;
Json::FastWriter writer; // object that converts Json::Value into it's JSON string representation
std::string json_output = writer.write(response);
// wrap C++ string with Var object used by ppapi and send it to JavaScript
// https://developer.chrome.com/native-client/pepper_stable/cpp/classpp_1_1_var
PostMessage(pp::Var(json_output));
}
};
class JsonTutorialModule : public pp::Module {
public:
JsonTutorialModule() : pp::Module() {}
virtual ~JsonTutorialModule() {}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new JsonTutorialInstance(instance);
}
};
namespace pp {
Module* CreateModule() {
return new JsonTutorialModule();
}
} // namespace pp
# Copyright (c) 2013 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# GNU Make based build file.  For details on GNU Make see:
# http://www.gnu.org/software/make/manual/make.html
#
#
# Get pepper directory for toolchain and includes.
#
# If NACL_SDK_ROOT is not set, then assume it can be found three directories up.
#
THIS_MAKEFILE := $(abspath $(lastword $(MAKEFILE_LIST)))
NACL_SDK_ROOT ?= $(abspath $(dir $(THIS_MAKEFILE))../..)
# Project Build flags
WARNINGS := -Wno-long-long -Wall -Wswitch-enum -pedantic -Werror
CXXFLAGS := -pthread -std=gnu++98 $(WARNINGS)
#
# Compute tool paths
#
GETOS := python $(NACL_SDK_ROOT)/tools/getos.py
OSHELPERS = python $(NACL_SDK_ROOT)/tools/oshelpers.py
OSNAME := $(shell $(GETOS))
RM := $(OSHELPERS) rm
PNACL_TC_PATH := $(abspath $(NACL_SDK_ROOT)/toolchain/$(OSNAME)_pnacl)
PNACL_CXX := $(PNACL_TC_PATH)/bin/pnacl-clang++
PNACL_FINALIZE := $(PNACL_TC_PATH)/bin/pnacl-finalize
CXXFLAGS := -I$(NACL_SDK_ROOT)/include
LDFLAGS := -L$(NACL_SDK_ROOT)/lib/pnacl/Release -lppapi_cpp -lppapi -ljsoncpp
#
# Disable DOS PATH warning when using Cygwin based tools Windows
#
CYGWIN ?= nodosfilewarning
export CYGWIN
# Declare the ALL target first, to make the 'all' target the default build
all: json_tutorial.pexe
clean:
$(RM) json_tutorial.pexe json_tutorial.bc
json_tutorial.bc: json_tutorial.cc
$(PNACL_CXX) -o $@ $< -O2 $(CXXFLAGS) $(LDFLAGS)
json_tutorial.pexe: json_tutorial.bc
$(PNACL_FINALIZE) -o $@ $<
#
# Makefile target to run the SDK's simple HTTP server and serve this example.
#
HTTPD_PY := python $(NACL_SDK_ROOT)/tools/httpd.py
.PHONY: serve
serve: all
$(HTTPD_PY) -C $(CURDIR)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment