-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfile_io.cc
396 lines (343 loc) · 12.7 KB
/
file_io.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
// Copyright (c) 2012 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.
/// @file file_io.cc
/// This example demonstrates the use of persistent file I/O
#define __STDC_LIMIT_MACROS
#include <sstream>
#include <string>
#include "ppapi/c/pp_stdint.h"
#include "ppapi/c/ppb_file_io.h"
#include "ppapi/cpp/directory_entry.h"
#include "ppapi/cpp/file_io.h"
#include "ppapi/cpp/file_ref.h"
#include "ppapi/cpp/file_system.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/message_loop.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var.h"
#include "ppapi/cpp/url_loader.h"
#include "ppapi/cpp/url_request_info.h"
#include "ppapi/cpp/url_response_info.h"
#include "ppapi/utility/completion_callback_factory.h"
#include "ppapi/utility/threading/simple_thread.h"
#include "downloader.h"
#define READ_BUFFER_SIZE 32768
#ifndef INT32_MAX
#define INT32_MAX (0x7FFFFFFF)
#endif
#ifdef WIN32
#undef min
#undef max
#undef PostMessage
// Allow 'this' in initializer list
#pragma warning(disable : 4355)
#endif
namespace {
/// Used for our simple protocol to communicate with Javascript
const char* const kLoadPrefix = "ld";
const char* const kSavePrefix = "sv";
const char* const kDeletePrefix = "de";
const char* const kListPrefix = "ls";
const char* const kMakeDirPrefix = "md";
//const char* const faceCascade = "haarcascades/haarcascade_frontalface_alt.xml";
std::string files[] = {
"/haarcascades/haarcascade_frontalface_alt.xml",
"/haarcascades/haarcascade_eye.xml"
};
//int filesc = sizeof(files)/sizeof(files[0]) ;
//int kBufSize = 1024*1024;
}
class FileIoInstance : public pp::Instance {
public:
/// The constructor creates the plugin-side instance.
/// @param[in] instance the handle to the browser-side plugin instance.
explicit FileIoInstance(PP_Instance instance)
: pp::Instance(instance),
callback_factory_(this),
file_system_(this, PP_FILESYSTEMTYPE_LOCALPERSISTENT),
//downloader(this, files, filesc, kBufSize),
file_system_ready_(false),
file_thread_(this) {
}
virtual ~FileIoInstance() { file_thread_.Join(); }
virtual bool Init(uint32_t /*argc*/,
const char * /*argn*/ [],
const char * /*argv*/ []) {
file_thread_.Start();
// Open the file system on the file_thread_. Since this is the first
// operation we perform there, and because we do everything on the
// file_thread_ synchronously, this ensures that the FileSystem is open
// before any FileIO operations execute.
file_thread_.message_loop().PostWork(
callback_factory_.NewCallback(&FileIoInstance::OpenFileSystem));
return true;
}
void DownloadDone() {
printf("Downloaded completed\n");
}
private:
pp::CompletionCallbackFactory<FileIoInstance> callback_factory_;
pp::FileSystem file_system_;
pp::URLLoader loader_;
pp::URLResponseInfo response_;
std::string content_;
//Downloader downloader;
// Indicates whether file_system_ was opened successfully. We only read/write
// this on the file_thread_.
bool file_system_ready_;
// We do all our file operations on the file_thread_.
pp::SimpleThread file_thread_;
/// Handler for messages coming in from the browser via postMessage(). The
/// @a var_message can contain anything: a JSON string; a string that encodes
/// method names and arguments; etc.
///
/// Here we use messages to communicate with the user interface
///
/// @param[in] var_message The message posted by the browser.
virtual void HandleMessage(const pp::Var& var_message) {
if (!var_message.is_string())
return;
// Parse message into: instruction file_name_length file_name [file_text]
std::string message = var_message.AsString();
std::string instruction;
std::string file_name;
std::stringstream reader(message);
int file_name_length;
reader >> instruction >> file_name_length;
file_name.resize(file_name_length);
reader.ignore(1); // Eat the delimiter
reader.read(&file_name[0], file_name_length);
if (file_name.length() == 0 || file_name[0] != '/') {
ShowStatusMessage("File name must begin with /");
return;
}
// Dispatch the instruction
if (instruction == kLoadPrefix) {
file_thread_.message_loop().PostWork(
callback_factory_.NewCallback(&FileIoInstance::Load, file_name));
} else if (instruction == kSavePrefix) {
// Read the rest of the message as the file text
//downloader.Start();
reader.ignore(1); // Eat the delimiter
std::string file_text = message.substr(reader.tellg());
file_thread_.message_loop().PostWork(callback_factory_.NewCallback(
&FileIoInstance::Save, file_name, file_text));
} else if (instruction == kDeletePrefix) {
file_thread_.message_loop().PostWork(
callback_factory_.NewCallback(&FileIoInstance::Delete, file_name));
} else if (instruction == kListPrefix) {
const std::string& dir_name = file_name;
file_thread_.message_loop().PostWork(
callback_factory_.NewCallback(&FileIoInstance::List, dir_name));
} else if (instruction == kMakeDirPrefix) {
const std::string& dir_name = file_name;
file_thread_.message_loop().PostWork(
callback_factory_.NewCallback(&FileIoInstance::MakeDir, dir_name));
}
}
void OpenFileSystem(int32_t /* result */) {
int32_t rv = file_system_.Open(1024 * 1024, pp::BlockUntilComplete());
if (rv == PP_OK) {
file_system_ready_ = true;
// Notify the user interface that we're ready
PostMessage("READY|");
} else {
ShowErrorMessage("Failed to open file system", rv);
}
}
void Save(int32_t /* result */,
const std::string& file_name,
const std::string& file_contents) {
if (!file_system_ready_) {
ShowErrorMessage("File system is not open", PP_ERROR_FAILED);
return;
}
printf("%s\n", file_name.c_str());
pp::FileRef ref(file_system_, file_name.c_str());
pp::FileIO file(this);
int32_t open_result =
file.Open(ref,
PP_FILEOPENFLAG_WRITE | PP_FILEOPENFLAG_CREATE |
PP_FILEOPENFLAG_TRUNCATE,
pp::BlockUntilComplete());
if (open_result != PP_OK) {
ShowErrorMessage("File open for write failed", open_result);
return;
}
// We have truncated the file to 0 bytes. So we need only write if
// file_contents is non-empty.
if (!file_contents.empty()) {
if (file_contents.length() > INT32_MAX) {
ShowErrorMessage("File too big", PP_ERROR_FILETOOBIG);
return;
}
int64_t offset = 0;
int32_t bytes_written = 0;
do {
bytes_written = file.Write(offset,
file_contents.data() + offset,
file_contents.length(),
pp::BlockUntilComplete());
if (bytes_written > 0) {
offset += bytes_written;
} else {
ShowErrorMessage("File write failed", bytes_written);
return;
}
} while (bytes_written < static_cast<int64_t>(file_contents.length()));
}
// All bytes have been written, flush the write buffer to complete
int32_t flush_result = file.Flush(pp::BlockUntilComplete());
if (flush_result != PP_OK) {
ShowErrorMessage("File fail to flush", flush_result);
return;
}
ShowStatusMessage("Save success");
}
void Load(int32_t /* result */, const std::string& file_name) {
if (!file_system_ready_) {
ShowErrorMessage("File system is not open", PP_ERROR_FAILED);
return;
}
pp::FileRef ref(file_system_, file_name.c_str());
pp::FileIO file(this);
int32_t open_result =
file.Open(ref, PP_FILEOPENFLAG_READ, pp::BlockUntilComplete());
if (open_result == PP_ERROR_FILENOTFOUND) {
ShowErrorMessage("File not found", open_result);
return;
} else if (open_result != PP_OK) {
ShowErrorMessage("File open for read failed", open_result);
return;
}
PP_FileInfo info;
int32_t query_result = file.Query(&info, pp::BlockUntilComplete());
if (query_result != PP_OK) {
ShowErrorMessage("File query failed", query_result);
return;
}
// FileIO.Read() can only handle int32 sizes
if (info.size > INT32_MAX) {
ShowErrorMessage("File too big", PP_ERROR_FILETOOBIG);
return;
}
std::vector<char> data(info.size);
int64_t offset = 0;
int32_t bytes_read = 0;
int32_t bytes_to_read = info.size;
while (bytes_to_read > 0) {
bytes_read = file.Read(offset,
&data[offset],
data.size() - offset,
pp::BlockUntilComplete());
if (bytes_read > 0) {
offset += bytes_read;
bytes_to_read -= bytes_read;
} else if (bytes_read < 0) {
// If bytes_read < PP_OK then it indicates the error code.
ShowErrorMessage("File read failed", bytes_read);
return;
}
}
// Done reading, send content to the user interface
std::string string_data(data.begin(), data.end());
PostMessage("DISP|" + string_data);
ShowStatusMessage("Load success");
}
void Delete(int32_t /* result */, const std::string& file_name) {
if (!file_system_ready_) {
ShowErrorMessage("File system is not open", PP_ERROR_FAILED);
return;
}
pp::FileRef ref(file_system_, file_name.c_str());
int32_t result = ref.Delete(pp::BlockUntilComplete());
if (result == PP_ERROR_FILENOTFOUND) {
ShowStatusMessage("File/Directory not found");
return;
} else if (result != PP_OK) {
ShowErrorMessage("Deletion failed", result);
return;
}
ShowStatusMessage("Delete success");
}
void List(int32_t /* result */, const std::string& dir_name) {
if (!file_system_ready_) {
ShowErrorMessage("File system is not open", PP_ERROR_FAILED);
return;
}
pp::FileRef ref(file_system_, dir_name.c_str());
// Pass ref along to keep it alive.
ref.ReadDirectoryEntries(callback_factory_.NewCallbackWithOutput(
&FileIoInstance::ListCallback, ref));
}
void ListCallback(int32_t result,
const std::vector<pp::DirectoryEntry>& entries,
pp::FileRef /* unused_ref */) {
if (result != PP_OK) {
ShowErrorMessage("List failed", result);
return;
}
std::stringstream ss;
ss << "LIST";
for (size_t i = 0; i < entries.size(); ++i) {
pp::Var name = entries[i].file_ref().GetName();
if (name.is_string()) {
ss << "|" << name.AsString();
}
}
PostMessage(ss.str());
ShowStatusMessage("List success");
}
void MakeDir(int32_t /* result */, const std::string& dir_name) {
if (!file_system_ready_) {
ShowErrorMessage("File system is not open", PP_ERROR_FAILED);
return;
}
pp::FileRef ref(file_system_, dir_name.c_str());
int32_t result = ref.MakeDirectory(
PP_MAKEDIRECTORYFLAG_NONE, pp::BlockUntilComplete());
if (result != PP_OK) {
ShowErrorMessage("Make directory failed", result);
return;
}
ShowStatusMessage("Make directory success");
}
/// Encapsulates our simple javascript communication protocol
void ShowErrorMessage(const std::string& message, int32_t result) {
std::stringstream ss;
ss << "ERR|" << message << " -- Error #: " << result;
PostMessage(ss.str());
}
/// Encapsulates our simple javascript communication protocol
void ShowStatusMessage(const std::string& message) {
std::stringstream ss;
ss << "STAT|" << message;
PostMessage(ss.str());
}
void logmsg(const char* pMsg){
fprintf(stdout,"logmsg: %s\n",pMsg);
}
};
/// The Module class. The browser calls the CreateInstance() method to create
/// an instance of your NaCl module on the web page. The browser creates a new
/// instance for each <embed> tag with type="application/x-nacl".
class FileIoModule : public pp::Module {
public:
FileIoModule() : pp::Module() {}
virtual ~FileIoModule() {}
/// Create and return a FileIoInstance object.
/// @param[in] instance The browser-side instance.
/// @return the plugin-side instance.
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new FileIoInstance(instance);
}
};
namespace pp {
/// Factory function called by the browser when the module is first loaded.
/// The browser keeps a singleton of this module. It calls the
/// CreateInstance() method on the object you return to make instances. There
/// is one instance per <embed> tag on the page. This is the main binding
/// point for your NaCl module with the browser.
Module* CreateModule() { return new FileIoModule(); }
} // namespace pp