pnacl: make conditionnal file creation a "one liner" to fix indentation
[nit.git] / lib / pnacl.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2014 Johan Kayser <kayser.johan@gmail.com>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17 # Targets the PNaCl platform
18 #
19 # To use this module and compile for PNaCl, you must install the
20 # NaCl SDK (This file is based on Pepper 33).
21 # If NACL_SDK_ROOT is not set in your PATH, you have to work in
22 # 'nacl_sdk/pepper_your_pepper_version/getting_started/your_project_folder'.
23 #
24 # Provides PNaCl support for Nit
25 module pnacl is platform
26 `{
27 #include <unistd.h>
28 #include <stddef.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #include "ppapi/c/pp_errors.h"
32 #include "ppapi/c/ppp.h"
33 #include "ppapi/c/ppp_instance.h"
34 #include "ppapi/c/pp_bool.h"
35 #include "ppapi/c/ppb_var.h"
36 #include "ppapi/c/ppb_messaging.h"
37 #include "ppapi/c/ppp_messaging.h"
38 #include "ppapi/c/ppb_var_dictionary.h"
39 #include "ppapi/c/ppb_var_array.h"
40
41 extern int nit_main(int, char**);
42
43 const PPB_Messaging* g_varMessagingInterface;
44 const PPB_Var* g_varInterface;
45 const PPB_VarDictionary* g_varDictionaryInterface;
46 const PPB_VarArray* g_varArrayInterface;
47
48 PP_Instance g_instance;
49 PnaclApp app;
50
51 /* Posts a string message to JS. */
52 void PostMessage(char* message) {
53 /* Create PP_Var containing the message body. */
54 struct PP_Var varString = g_varInterface->VarFromUtf8(message, strlen(message));
55
56 /* Post message to the JavaScript layer. */
57 g_varMessagingInterface->PostMessage(g_instance, varString);
58 }
59
60 /* Posts a Dictionary (JS like object) to JS. */
61 void PostDictionary(struct PP_Var dictionary) {
62 g_varMessagingInterface->PostMessage(g_instance, dictionary);
63 }
64
65 /* Posts a Variable (aka PepperVar) to JS.
66 Should only be used for testing, conventional conversation is made
67 with Strings or Dictionaries. */
68 void PostVar(struct PP_Var v) {
69 g_varMessagingInterface->PostMessage(g_instance, v);
70 }
71
72 static PP_Bool Instance_DidCreate(PP_Instance instance, uint32_t argc, const char* argn[], const char* argv[]) {
73 g_instance = instance;
74 nit_main(0, NULL);
75 return PP_TRUE;
76 }
77
78 static void Instance_DidDestroy(PP_Instance instance) {
79 // TODO
80 }
81
82 static void Instance_DidChangeView(PP_Instance pp_instance, PP_Resource view) {
83 // TODO
84 }
85
86 static void Instance_DidChangeFocus(PP_Instance pp_instance, PP_Bool has_focus) {
87 // TODO
88 }
89
90 static PP_Bool Instance_HandleDocumentLoad(PP_Instance pp_instance, PP_Resource pp_url_loader) {
91 // TODO
92 return PP_FALSE;
93 }
94
95 /* char* to PP_Var. */
96 static struct PP_Var CStrToVar(const char* str) {
97 if (g_varInterface != NULL) {
98 return g_varInterface->VarFromUtf8(str, strlen(str));
99 }
100 return PP_MakeUndefined();
101 }
102
103 /* Called when JS sends something, is set to accept Strings or Dictionaries,
104 returns an error if received object is not a String or Dictionary. */
105 void Messaging_HandleMessage(PP_Instance instance, struct PP_Var varMessage) {
106 if(varMessage.type == PP_VARTYPE_DICTIONARY) {
107 PnaclApp_handle_dictionary(app, &varMessage);
108 }
109 else if(varMessage.type == PP_VARTYPE_STRING) {
110 uint32_t len;
111 char* message = (char*)g_varInterface->VarToUtf8(varMessage, &len);
112 PnaclApp_handle_message(app, NativeString_to_s_with_length(message, len));
113 }
114 else {
115 struct PP_Var errorMessage = CStrToVar("TypeError : only accepts JS objects or Strings");
116 g_varMessagingInterface->PostMessage(g_instance, errorMessage);
117 }
118 }
119
120 /* Entry point */
121 PP_EXPORT int32_t PPP_InitializeModule(PP_Module module_id, PPB_GetInterface get_browser_interface) {
122 /* Initializing global pointers */
123 g_varMessagingInterface = (const PPB_Messaging*) get_browser_interface(PPB_MESSAGING_INTERFACE);
124 g_varInterface = (const PPB_Var*) get_browser_interface(PPB_VAR_INTERFACE);
125 g_varDictionaryInterface = (const PPB_VarDictionary*) get_browser_interface(PPB_VAR_DICTIONARY_INTERFACE);
126 g_varArrayInterface = (const PPB_VarArray*) get_browser_interface(PPB_VAR_ARRAY_INTERFACE);
127 return PP_OK;
128 }
129
130 PP_EXPORT void PPP_ShutdownModule() {
131 // TODO
132 }
133
134 PP_EXPORT const void* PPP_GetInterface(const char* interface_name) {
135 if (strcmp(interface_name, PPP_INSTANCE_INTERFACE) == 0)
136 {
137 static PPP_Instance instance_interface = {
138 &Instance_DidCreate,
139 &Instance_DidDestroy,
140 &Instance_DidChangeView,
141 &Instance_DidChangeFocus,
142 &Instance_HandleDocumentLoad
143 };
144 return &instance_interface;
145 }
146 else if (strcmp(interface_name, PPP_MESSAGING_INTERFACE) == 0) {
147 static PPP_Messaging messaging_interface = {
148 &Messaging_HandleMessage
149 };
150 return &messaging_interface;
151 }
152 return NULL;
153 }
154 `}
155
156 # Nit class representing a Pepper C API PP_Var typed as a Dictionary.
157 extern class PepperDictionary `{ struct PP_Var* `}
158
159 new `{
160 struct PP_Var* recv = malloc( sizeof( struct PP_Var ) );
161 *recv = g_varDictionaryInterface->Create();
162 return recv;
163 `}
164
165 # Get fonction using PepperVars.
166 #
167 # Returns the value that is associated with 'key'.
168 # If 'key' is not a String typed PepperVar, or doesn't exist in the Dictionary, an undefined PepperVar is returned.
169 fun native_get(key: PepperVar): PepperVar `{
170 struct PP_Var* value = malloc( sizeof ( struct PP_Var ) );
171 *value = g_varDictionaryInterface->Get(*recv, *key);
172 return value;
173 `}
174
175 # Returns the value associated with 'key'.
176 #
177 # 'key' must be a String.
178 # If 'key' is not a String or doesn't exist in the Dictionary, 'null' is returned.
179 fun [](key: nullable Pepperable): nullable Pepperable
180 do
181 var native_key = key.to_pepper
182 var native_value = native_get(native_key)
183 return native_value.to_nit
184 end
185
186 # Set function using PepperVars.
187 #
188 # Sets the value associated with the specified key.
189 # 'key' must be a String typed PepperVar.
190 # If 'key' hasn't existed in the Dictionary, it is added and associated with 'value'.
191 # Otherwise, the previous value is replaced with 'value'.
192 # Returns a Boolean indicating whether the operation succeeds.
193 fun native_set(key: PepperVar, value: PepperVar): Bool `{
194 PP_Bool b;
195 b = g_varDictionaryInterface->Set(*recv, *key, *value);
196 return b;
197 `}
198
199 # Sets the value associated with the specified key.
200 #
201 # 'key' must be a String.
202 # If 'key' hasn't existed in the Dictionary, it is added and associated with 'value'.
203 # Otherwise, the previous value is replaced with 'value'.
204 # Returns a Boolean indicating whether the operation succeeds.
205 fun []=(key: nullable Pepperable, value: nullable Pepperable): Bool
206 do
207 var native_key = key.to_pepper
208 var native_value = value.to_pepper
209 return native_set(native_key, native_value)
210 end
211
212 # Deletes the specified key and its associated value, if the key exists.
213 #
214 # Takes a String typed PepperVar.
215 fun native_delete(key: PepperVar) `{
216 g_varDictionaryInterface->Delete(*recv, *key);
217 `}
218
219 # Deletes the specified key and its associated value, if the key exists.
220 #
221 # Takes a String.
222 fun delete(key: String)
223 do
224 var native_key = key.to_pepper
225 native_delete native_key
226 end
227
228 # Checks whether a key exists.
229 #
230 # Takes a String typed PepperVar.
231 fun native_has_key(key: PepperVar): Bool `{
232 PP_Bool b;
233 b = g_varDictionaryInterface->HasKey(*recv, *key);
234 return b;
235 `}
236
237 # Checks whether a key exists.
238 #
239 # Takes a String.
240 fun has_key(key: String): Bool
241 do
242 var native_key = key.to_pepper
243 return native_has_key(native_key)
244 end
245
246 # Gets all the keys in a dictionary.
247 #
248 # Returns a PepperArray which contains all the keys of the Dictionary. The elements are string vars.
249 fun get_keys: PepperArray `{
250 struct PP_Var* array = malloc( sizeof( struct PP_Var ) );
251 *array = g_varDictionaryInterface->GetKeys(*recv);
252 return array;
253 `}
254
255 # Use this function to copy a dictionary.
256 fun copy: PepperDictionary `{
257 struct PP_Var* varDictionary = malloc( sizeof( struct PP_Var ) );
258 *varDictionary = g_varDictionaryInterface->Create();
259 *varDictionary = *recv;
260 return varDictionary;
261 `}
262 end
263
264 # Nit class representing a Pepper C API PP_Var typed as an Array.
265 extern class PepperArray `{ struct PP_Var* `}
266
267 new `{
268 struct PP_Var* recv = malloc( sizeof( struct PP_Var ) );
269 *recv = g_varArrayInterface->Create();
270 return recv;
271 `}
272
273 # Returns the element at the specified position as a PepperVar.
274 #
275 # If 'index' is larger than or equal to the array length, an undefined PepperVar is returned.
276 fun native_get(index: Int): PepperVar `{
277 struct PP_Var* value = malloc( sizeof( struct PP_Var ) );
278 *value = g_varArrayInterface->Get(*recv, index);
279 return value;
280 `}
281
282 # Returns the element at the specified position.
283 #
284 # If 'index' is larger than or equal to the array length, 'null' is returned.
285 fun [](index: Int): nullable Pepperable
286 do
287 var native_value = native_get(index)
288 return native_value.to_nit
289 end
290
291 # Returns an int containing the length of the PepperArray.
292 fun length: Int `{
293 int length = g_varArrayInterface->GetLength(*recv);
294 return length;
295 `}
296
297 # Takes a PepperVar for the 'value' param.
298 #
299 # Sets the value of an element in the array at indicated index.
300 # If 'index' is larger than or equal to the array length, the length is updated to be 'index' + 1.
301 # Any position in the array that hasn't been set before is set to undefined, i.e., PepperVar of C type PP_VARTYPE_UNDEFINED.
302 # Returns a Boolean indicating whether the operation succeeds.
303 fun native_set(index: Int, value: PepperVar): Bool `{
304 PP_Bool b;
305 b = g_varArrayInterface->Set(*recv, index, *value);
306 return b;
307 `}
308
309 # Sets the value of an element in the array at indicated index.
310 #
311 # If 'index' is larger than or equal to the array length, the length is updated to be 'index' + 1.
312 # Any position in the array that hasn't been set before is set to undefined, i.e., PepperVar of C type PP_VARTYPE_UNDEFINED.
313 # Returns a Boolean indicating whether the operation succeeds.
314 fun []=(index: Int, value: nullable Pepperable): Bool
315 do
316 var native_value = value.to_pepper
317 return native_set(index, native_value)
318 end
319
320 # Sets the array length.
321 #
322 # If 'length' is smaller than its current value, the array is truncated to the new length.
323 # Any elements that no longer fit are removed and the references to them will be released.
324 # If 'length' is larger than its current value, undefined PepperVars are appended to increase the array to the specified length.
325 # Returns a Boolean indicating whether the operation succeeds.
326 fun length=(length: Int): Bool `{
327 PP_Bool b;
328 b = g_varArrayInterface->SetLength(*recv, length);
329 return b;
330 `}
331 end
332
333 # Nit class representing a Pepper C API PP_Var.
334 extern class PepperVar `{ struct PP_Var* `}
335
336 new `{
337 return malloc( sizeof( struct PP_Var ) );
338 `}
339
340 # Converts PepperVar to standard types.
341 #
342 # Actually supports bools, ints, floats, strings. To be used with 'isa'.
343 fun to_nit: nullable Pepperable
344 do
345 if isa_null then return null
346 if isa_bool then return as_bool
347 if isa_int then return as_int
348 if isa_float then return as_float
349 if isa_string then return as_string
350 if is_undefined then return null
351
352 return null
353 end
354
355 private fun isa_null: Bool `{ return recv->type == PP_VARTYPE_NULL; `}
356 private fun isa_bool: Bool `{ return recv->type == PP_VARTYPE_BOOL; `}
357 private fun isa_int: Bool `{ return recv->type == PP_VARTYPE_INT32; `}
358 private fun isa_float: Bool `{ return recv->type == PP_VARTYPE_DOUBLE; `}
359 private fun isa_string: Bool `{ return recv->type == PP_VARTYPE_STRING; `}
360 private fun is_undefined: Bool `{ return recv->type == PP_VARTYPE_UNDEFINED; `}
361
362 private fun as_bool: Bool `{ return recv->value.as_bool; `}
363 private fun as_int: Int `{ return recv->value.as_int; `}
364 private fun as_float: Float `{ return recv->value.as_double; `}
365 private fun as_string: String import NativeString.to_s_with_length `{
366 uint32_t len;
367 char* str = (char*)g_varInterface->VarToUtf8(*recv, &len);
368 return NativeString_to_s_with_length(str, len);
369 `}
370 end
371
372 # Provides a method to convert in PepperVars.
373 interface Pepperable
374 fun to_pepper: PepperVar is abstract
375 end
376
377 redef class Int
378 super Pepperable
379
380 # Converts a Int into a PepperVar with Int type.
381 redef fun to_pepper `{
382 struct PP_Var* var = malloc( sizeof( struct PP_Var ) );
383 *var = PP_MakeInt32(recv);
384 return var;
385 `}
386 end
387
388 redef class Float
389 super Pepperable
390
391 # Converts a Float into a PepperVar with Float type.
392 redef fun to_pepper `{
393 struct PP_Var* var = malloc( sizeof( struct PP_Var ) );
394 *var = PP_MakeDouble(recv);
395 return var;
396 `}
397 end
398
399 redef class Bool
400 super Pepperable
401
402 # Converts a Bool into a PepperVar with Bool type.
403 redef fun to_pepper `{
404 struct PP_Var* var = malloc( sizeof( struct PP_Var ) );
405 *var = PP_MakeBool(recv);
406 return var;
407 `}
408 end
409
410 redef class String
411 super Pepperable
412
413 # Converts a String into a PepperVar with String type.
414 redef fun to_pepper: PepperVar import String.to_cstring, String.length `{
415 char *str = String_to_cstring(recv);
416 struct PP_Var* var = malloc( sizeof( struct PP_Var ) );
417 *var = g_varInterface->VarFromUtf8(str, String_length(recv));
418 return var;
419 `}
420 end
421
422 # Class that provides the tools to interact with PNaCl.
423 class PnaclApp
424
425 # Sets everything up to work, need to be called at first.
426 fun initialize import PnaclApp.handle_message, PnaclApp.handle_dictionary, NativeString.to_s_with_length `{
427 app = recv;
428 `}
429
430 # Posts a message to JS.
431 fun post_message(message: String) import String.to_cstring `{
432 char* str = String_to_cstring(message);
433 PostMessage(str);
434 `}
435
436 # Posts a dictionary to JS.
437 fun post_dictionary(dictionary: PepperDictionary) `{
438 PostDictionary(*dictionary);
439 `}
440
441 # Posts a PepperVar to JS.
442 #
443 # Should be used for testing, not recommanded for conventional conversation.
444 private fun post_var(v: PepperVar) `{
445 PostVar(*v);
446 `}
447
448 # Is called when a message is received from JS.
449 #
450 # Is set to be redefined in your application to handle like you want.
451 fun handle_message(message: String)
452 do
453 # To be Implemented by user.
454 end
455
456 # Is called when a Dictionary is received from JS.
457 #
458 # Is set to be redefined in your application to handle like you want.
459 # The dictionary is freed after this method returns.
460 fun handle_dictionary(dictionary: PepperDictionary)
461 do
462 # To be Implemented by user.
463 end
464 end