1 // Copyright (c) 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.
7 #include "ppapi/c/pp_errors.h"
8 #include "ppapi/c/ppb_file_io.h"
9 #include "ppapi/cpp/file_io.h"
10 #include "ppapi/cpp/file_ref.h"
11 #include "ppapi/cpp/file_system.h"
12 #include "ppapi/cpp/instance.h"
13 #include "ppapi/cpp/module.h"
14 #include "ppapi/cpp/var.h"
15 #include "ppapi/cpp/var_dictionary.h"
16 #include "ppapi/utility/completion_callback_factory.h"
17 #include "ppapi/utility/threading/simple_thread.h"
21 // Allow 'this' in initializer list
22 #pragma warning(disable : 4355)
25 class Instance
: public pp::Instance
{
27 explicit Instance(PP_Instance instance
)
28 : pp::Instance(instance
),
29 callback_factory_(this),
33 virtual bool Init(uint32_t /*argc*/,
34 const char* /*argn*/ [],
35 const char* /*argv*/ []) {
40 virtual void HandleMessage(const pp::Var
& var_message
) {
41 // Got a message from JavaScript. We're assuming it is a dictionary with
44 // filesystem: <A Filesystem var>,
45 // fullPath: <A string>
47 pp::VarDictionary
var_dict(var_message
);
48 pp::Resource filesystem_resource
= var_dict
.Get("filesystem").AsResource();
49 pp::FileSystem
filesystem(filesystem_resource
);
50 std::string full_path
= var_dict
.Get("fullPath").AsString();
52 std::string save_path
= full_path
+ "/hello_from_nacl.txt";
53 std::string contents
= "Hello, from Native Client!\n";
55 thread_
.message_loop().PostWork(callback_factory_
.NewCallback(
56 &Instance::WriteFile
, filesystem
, save_path
, contents
));
59 void WriteFile(int32_t /* result */,
60 const pp::FileSystem
& filesystem
,
61 const std::string
& path
,
62 const std::string
& contents
) {
63 pp::FileRef
ref(filesystem
, path
.c_str());
64 pp::FileIO
file(this);
67 file
.Open(ref
, PP_FILEOPENFLAG_WRITE
| PP_FILEOPENFLAG_CREATE
|
68 PP_FILEOPENFLAG_TRUNCATE
,
69 pp::BlockUntilComplete());
70 if (open_result
!= PP_OK
) {
71 PostMessage("Failed to open file.");
76 int32_t bytes_written
= 0;
78 bytes_written
= file
.Write(offset
, contents
.data() + offset
,
79 contents
.length(), pp::BlockUntilComplete());
80 if (bytes_written
> 0) {
81 offset
+= bytes_written
;
83 PostMessage("Failed to write file.");
86 } while (bytes_written
< static_cast<int64_t>(contents
.length()));
88 // All bytes have been written, flush the write buffer to complete
89 int32_t flush_result
= file
.Flush(pp::BlockUntilComplete());
90 if (flush_result
!= PP_OK
) {
91 PostMessage("Failed to flush file.");
94 PostMessage(std::string("Wrote file ") + path
+ ".");
98 pp::CompletionCallbackFactory
<Instance
> callback_factory_
;
99 pp::SimpleThread thread_
;
102 class Module
: public pp::Module
{
104 Module() : pp::Module() {}
107 virtual pp::Instance
* CreateInstance(PP_Instance instance
) {
108 return new Instance(instance
);
113 Module
* CreateModule() { return new ::Module(); }