~hleinone/nuvola-player/nuvola-player

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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
/*
 * Copyright 2011-2012 Jiří Janoušek <janousek.jiri@gmail.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met: 
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer. 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution. 
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
using JS;
using Nuvola.JSTools;
using Diorite.Logger;

namespace Nuvola{

/**
 * Errors thrown from Nuvola Palyer JavaScript API
 */
public errordomain JSError{
	/**
	 * An object has not been found
	 */
	NOT_FOUND,
	/**
	 * A value has wrong type
	 */
	WRONG_TYPE,
	/**
	 * Call of a JavaScript function failed.
	 */
	FUNC_FAILED,
	/**
	 * Unable to load script from file
	 */
	READ_ERROR,
	/**
	 * JavaScript API does not have any context yet.
	 */
	NO_CONTEXT,
	/**
	 * Execution of a script caused an exception.
	 */
	EXCEPTION;
}


/**
 * Nuvola JavaScript API provides interface for service integrations to communicate
 * with Nuvola Player runtime. Practically, it is a bridge between Service object
 * and JavaScript environment of WebKit WebView.
 * 
 * Main method of the main Nuvola Player JavaScript object are implemented here,
 * other helper functions and tools are loaded from a JavaScript file.
 */
public class JSApi: GLib.Object{
	/**
	 * Major version of the JavaScript API
	 */
	public static const int API_VERSION = 2;
	public static const int API_VERSION_MINOR = 0;
	private static const int COMPAT_API_MAJOR = 1;
	private static const string MESSAGE_RECEIVER = "onMessageReceived";
	private static const string MAIN_SCRIPT_FILENAME = "js/main.js";
	private static const string COMPAT_SCRIPT_FILENAME = "js/compat-1.x.js";
	public static const string CONFIG_CHANGED_MESSAGE = "config-changed";
	private static const string CONFIG_OBJECT = "config";
	private static unowned JS.Class klass;
	private Service service;
	private Diorite.Actions actions;
	private Nuvola.WebView view;
	private unowned JS.Object? main_object = null;
	private bool main_object_ready = false;
	private Diorite.Storage storage;
	private HashTable<string, bool?> changed_actions;
	private bool alternate_injection = false;
	
	private unowned JS.Context? ctx{
		get{
			if(view == null) return null;
			var frame = view.get_main_frame();
			if(frame == null) return null;
			return JS.Context.for_frame(frame);
		}
	}
	
	/**
	 * Emitted when configuration of a service has been changed from a script.
	 */
	public signal void config_changed();
	/**
	 * Emitted when Nuvola Player JavaScript API is loaded.
	 */
	public signal void load_finished();
	/**
	 * Emitted by script when song details have been changed.
	 * @param song				song name
	 * @param artist			artist name
	 * @param album				album name
	 * @param art_uri			URI of album art
	 * @param playback_state	state of playback
	 */
	public signal void song_changed(string? song, string? artist, string? album, string? art_uri, string playback_state);
	
		
	/**
	 * Updates information about a current song and state. Implementation of a method Nuvola.updateSong()
	 */
	static unowned JS.Value update_song_func(Context ctx, JS.Object function, JS.Object self, JS.Value[] args, out unowned JS.Value exception){
		unowned JS.Value undefined = JS.Value.undefined(ctx);
		exception = null;
		
		/* Check number of arguments */
		if(args.length != 5){
			critical("Nuvola.updateSong(): Wrong number of arguments: 4 required, %d provided", args.length);
			ctx.collect_garbage();
			return undefined;
		}
		
		/* Check type of arguments */
		// song
		if(!args[0].is_string(ctx) && !args[0].is_null(ctx)){
			critical("Nuvola.updateSong(): Arg 0 must be a string or null");
			ctx.collect_garbage();
			return undefined;
		}
		// artist
		if(!args[1].is_string(ctx) && !args[1].is_null(ctx)){
			critical("Nuvola.updateSong(): Arg 1 must be a string or null");
			ctx.collect_garbage();
			return undefined;
		}
		// album
		if(!args[2].is_string(ctx) && !args[2].is_null(ctx)){
			critical("Nuvola.updateSong(): Arg 2 must be a string or null");
			ctx.collect_garbage();
			return undefined;
		}
		// album art
		if(!args[3].is_string(ctx) && !args[3].is_null(ctx)){
			critical("Nuvola.updateSong(): Arg 3 must be a string or null");
			ctx.collect_garbage();
			return undefined;
		}
		// state
		if(!args[4].is_string(ctx)){
			critical("Nuvola.updateSong(): Arg 4 must be a string");
			ctx.collect_garbage();
			return undefined;
		}
		
		/* Check if private data is not null */
		JSApi? js_api = (self.get_private() as JSApi);
		if(js_api == null){
			debug("Nuvola.updateSong(): JSApi is null");
			exception = create_exception(ctx, "JSApi is null");
			return undefined;
		}
		else{
			js_api.song_changed(string_or_null(ctx, args[0]),
				string_or_null(ctx, args[1]),
				string_or_null(ctx, args[2]),
				string_or_null(ctx, args[3]),
				string_or_null(ctx, args[4]) ?? STATE_NONE);
		}
		
		ctx.collect_garbage();
		return undefined;
	}
	
	/**
	 * Updates 'sensitivity' of Nuvola Player action. Implementation of a method Nuvola.updateAction().
	 */
	static unowned JS.Value update_action_func(Context ctx, JS.Object function, JS.Object self, JS.Value[] args, out unowned JS.Value exception){
		exception = null;
		
		/* Check number of arguments */
		if(args.length != 2){
			critical("Nuvola.updateAction(): Wrong number of arguments: 1 required, %d provided", args.length);
			ctx.collect_garbage();
			return JS.Value.boolean(ctx, false);
		}
		
		/* Check type of arguments */
		// name
		if(!args[0].is_string(ctx)){
			critical("Nuvola.updateAction(): Arg 0 must be a string");
			ctx.collect_garbage();
			return JS.Value.boolean(ctx, false);
		}
		// sensitive
		if(!args[1].is_boolean(ctx)){
			critical("Nuvola.updateAction(): Arg 1 must be a boolean");
			ctx.collect_garbage();
			return JS.Value.boolean(ctx, false);
		}
		
		/* Check if private data is not null */
		JSApi? js_api = (self.get_private() as JSApi);
		if(js_api == null){
			debug("Nuvola.updateAction():  JSApi is null");
			exception = create_exception(ctx, "JSApi is null");
			return JS.Value.boolean(ctx, false);
		}
		
		var name = utf8_string(args[0].to_jsstring(ctx));
		var action = js_api.actions.get_action(name);
		if(action != null){
			if(!js_api.changed_actions.lookup(name) == null){
				js_api.changed_actions.insert(name, action.sensitive);
			}
			action.sensitive = args[1].to_boolean(ctx);
//~ 			debug("Nuvola.updateAction(): action '%s' = %s", name, action.sensitive.to_string());
		}
		else{
			debug("Nuvola.updateAction(): unknown action '%s'", name);
			ctx.collect_garbage();
			return JS.Value.boolean(ctx, false);
		}
		
		ctx.collect_garbage();
		return JS.Value.boolean(ctx, true);
	}
	
	/**
	 * Default implementation of Nuvola.onMessageReceived callback
	 */
	static unowned JS.Value default_command_func(Context ctx, JS.Object function, JS.Object self, JS.Value[] args, out unowned JS.Value exception){
		exception = null;
		string cmd = null;
		if(args.length > 0){
			cmd = string_or_null(ctx, args[0]);
		}
		warning("Called default Nuvola.onMessageReceived() function for command : %s", cmd ?? null);
		ctx.collect_garbage();
		return JS.Value.undefined(ctx);
	}
	
	/**
	 * Triggers Nuvola Player action, implementation of Nuvola.triggerAction()
	 */
	static unowned JS.Value trigger_action_func(Context ctx, JS.Object function, JS.Object self, JS.Value[] args, out unowned JS.Value exception){
		exception = null;
		string cmd = null;
		if(args.length > 0){
			cmd = string_or_null(ctx, args[0]);
		}
		/* Check if private data is not null */
		JSApi? js_api = (self.get_private() as JSApi);
		if(cmd == null){
			debug("Nuvola.triggerAction(): Action not specified");
		}
		else if(js_api == null){
			debug("Nuvola.triggerAction(): JSApi is null");
			exception = create_exception(ctx, "JSApi is null");
		}
		else{
			var action = js_api.actions.get_action(cmd);
			action.activate();
		}
		
		ctx.collect_garbage();
		return JS.Value.undefined(ctx);
	}
	
	/**
	 * Loads service's own configuration to the main object, implementation of Nuvola.loadConfig()
	 */
	static unowned JS.Value load_config_func(Context ctx, JS.Object function, JS.Object self, JS.Value[] args, out unowned JS.Value exception){
		exception = null;
		
		/* Check if private data is not null */
		JSApi? js_api = (self.get_private() as JSApi);
		if(js_api == null){
			debug("Nuvola.loadConfig(): JSApi is null");
			exception = create_exception(ctx, "JSApi is null");
		}
		else{
			self.set_property(ctx, new JS.String(CONFIG_OBJECT),
				object_from_JSON(ctx, js_api.service.config_json));
		}
		ctx.collect_garbage();
		return JS.Value.undefined(ctx);
	}
	
	
	/**
	 * Saves service's own configuration stored in the main object, implementation of Nuvola.saveConfig()
	 */
	static unowned JS.Value save_config_func(Context ctx, JS.Object function, JS.Object self, JS.Value[] args, out unowned JS.Value exception){
		exception = null;
		unowned JS.Value undefined = JS.Value.undefined(ctx);
		
		/* Check if private data is not null */
		JSApi? js_api = (self.get_private() as JSApi);
		if(js_api == null){
			debug("Nuvola.saveConfig(): JSApi is null");
			exception = create_exception(ctx, "JSApi is null");
		}
		else{
			var service = js_api.service;
			string json;
			unowned JS.Object? config = o_get_object(ctx, self, CONFIG_OBJECT);
			if(config == null){
				json = "";
			}
			else{
				json = utf8_string(value_to_JSON(ctx, config, 4, null)); 
			}
			service.config_json = json;
			js_api.config_changed();
		}
		ctx.collect_garbage();
		return undefined;
	}
	
	/**
	 * Calls gettext(), implementation of Nuvola.gettext()
	 */
	static unowned JS.Value gettext_func(Context ctx, JS.Object function, JS.Object self, JS.Value[] args, out unowned JS.Value exception){
		exception = null;
		unowned JS.Value undefined = JS.Value.undefined(ctx);
		/* Check number of arguments */
		if(args.length != 1){
			critical("Nuvola.gettext(): Wrong number of arguments: 1 required, %d provided", args.length);
			return undefined;
		}
		
		/* Check type of arguments */
		if(!args[0].is_string(ctx)){
			critical("Nuvola.gettext(): Arg 0 must be a string");
			return undefined;
		}
		
		var value = _(utf8_string(args[0].to_jsstring(ctx)));
		return JS.Value.string(ctx, new JS.String(value));
	}
	
	/**
	 * Default methods of the main object. Other functions are implemented in JavaScript,
	 * see file main.js
	 */
	private static const JS.StaticFunction[] static_functions = {
		{"updateSong", update_song_func, 0},
		{"updateAction", update_action_func, 0},
		{"reloadConfig", load_config_func, 0},
		{"saveConfig", save_config_func, 0},
		{"gettext", gettext_func, 0},
		{"triggerAction", trigger_action_func, 0},
		{MESSAGE_RECEIVER, default_command_func, 0},
		{null, null, 0}
	};
	
	/**
	 * Creates Nuvola Player main object class description
	 */
	private static void create_class(){
		unowned ClassDefinition class_def = {
		    1,                                        
		    JS.ClassAttribute.None,                      
		    "Nuvola JavaScript API",               
		    null,                                       
		    null,            
		    static_functions,         
		    null, 
		    null, 
		    null, 
		    null,
		    null, 
		    null, 
		    null, 
		    null, 
		    null, 
		    null, 
		    null  
		};
		klass = JS.create_class(class_def);
	}
	
	/**
	 * Creates new Nuvola JavaScript API bridge between service and web view.
	 * 
	 * @param storage				storage fon application
	 * @param view					web view whose JavaScript environment will host the API
	 * @param service				service that will be bound to that API
	 * @param actions				Nuvola Player actions
	 * @param late_injection	if true, JSApi will be injected when page is loaded
	 */
	public JSApi(Diorite.Storage storage, Nuvola.WebView view, Service service,
	Diorite.Actions actions, bool late_injection=false)
	{
		this.storage = storage;
		this.service = service;
		this.view = view;
		this.actions = actions;
		changed_actions = new HashTable<string, bool?>(str_hash, str_equal);
		view.notify["load-status"].connect(on_load_status_changed);
		this.alternate_injection = late_injection;
		if(!late_injection){
			view.window_object_cleared.connect(on_window_object_cleared);
		}
		view.document_load_finished.connect_after(on_document_loaded);
		view.console_message.connect(console_handler);
	}
	
	~JSApi(){
		main_object = null;
		changed_actions.@foreach(reset_action);
	}
	
	/**
	 * Called when load status of a web view has changed.
	 */
	private void on_load_status_changed(GLib.Object o, ParamSpec p){
//~ 		debug(@"load status $(view.load_status)");
		if(view.load_status == WebKit.LoadStatus.PROVISIONAL){
			reset_main_object();
		}
	}
	
	/**
	 * Unprotects and removes main object.
	 */
	private void reset_main_object(){
		debug("Reset main object");
		lock(main_object_ready){
			main_object_ready = false;
			if(main_object != null){
				main_object.unprotect(ctx);
				main_object = null;
			}
		}
	}
	
	/**
	 * Sets actions to original state.
	 */
	private void reset_action(string name, bool? value){
		var action = actions.get_action(name);
		if(action != null && value != null){
			action.sensitive = value;
		}
	}
	
	/**
	 * JavaScript console handler
	 */
	private bool console_handler(string message, int line_number, string source_id){
		if(view.developer_mode){
			debug("%s:%d: %s", source_id, line_number, message);
		}
		return true;
	}
	
	/**
	 * Called when a web document is loaded.
	 */
	private void on_document_loaded(WebKit.WebFrame frame){
		if(frame != view.get_main_frame()) return;
		var status_code = frame.get_network_response().message.status_code;
		if(status_code >= 400){
			message("Load error: %u", status_code);
			lock(main_object_ready){
				/* Just to be sure no JavaScript API method is executed,
				 * because it causes SIGSEGV in JavaScriptCore. */
				main_object_ready = false;
			}
		}
		else{
			unowned JS.Context ctx = JS.Context.for_frame(frame);
			
			if(alternate_injection){
				inject_js_api(ctx);
			}
			
			load_finished();
		}
	}
	
	private void on_window_object_cleared(WebKit.WebFrame frame, void* context, void* window_object){
		if(frame != view.get_main_frame()) return;
		debug("Window object cleared");
		unowned JS.Context ctx = (JS.Context) 	context;
		inject_js_api(ctx);
	}
	
	/**
	 * Creates the main object and injects it to the JavaScript context
	 * 
	 * @param ctx	hosting JavaScript context
	 * @return true if the main object has been successfully created
	 */
	private bool inject_js_api(JS.Context ctx){
			lock(main_object_ready){
				main_object_ready = false;
				main_object = null;
			}

			if(klass == null) create_class();
			main_object = ctx.make_object(klass, this);
			o_set_string(ctx, main_object, "STATE_PLAYING", STATE_PLAYING);
			o_set_string(ctx, main_object, "STATE_NONE", STATE_NONE);
			o_set_string(ctx, main_object, "STATE_PAUSED", STATE_PAUSED);
			o_set_string(ctx, main_object, "ACTION_PLAY", Actions.PLAY);
			o_set_string(ctx, main_object, "ACTION_PAUSE", Actions.PAUSE);
			o_set_string(ctx, main_object, "ACTION_TOGGLE_PLAY", Actions.TOGGLE_PLAY);
			o_set_string(ctx, main_object, "ACTION_PREV_SONG", Actions.PREV_SONG);
			o_set_string(ctx, main_object, "ACTION_NEXT_SONG",Actions.NEXT_SONG);
			o_set_string(ctx, main_object, "ACTION_THUMBS_UP", Actions.THUMBS_UP);
			o_set_string(ctx, main_object, "ACTION_THUMBS_DOWN", Actions.THUMBS_DOWN);
			o_set_string(ctx, main_object, "ACTION_FAVORITE", Actions.FAVORITE);
			o_set_string(ctx, main_object, "CONFIG_CHANGED", CONFIG_CHANGED_MESSAGE);
			o_set_number(ctx, main_object, "API_VERSION", (double)API_VERSION);
			o_set_number(ctx, main_object, "API_VERSION_MINOR", (double)API_VERSION_MINOR);
			o_set_number(ctx, main_object, "VERSION_MAJOR", (double)Config.VERSION_MAJOR);
			o_set_number(ctx, main_object, "VERSION_MINOR", (double)Config.VERSION_MINOR);
			o_set_number(ctx, main_object, "VERSION_BUGFIX", (double)Config.VERSION_BUGFIX);
			o_set_string(ctx, main_object, "VERSION_SUFFIX", Config.VERSION_SUFFIX);
			main_object.set_property(ctx, new JS.String(CONFIG_OBJECT),
				object_from_JSON(ctx, service.config_json));
			
			/* Functions not bound to this.service are written in pure JavaScript.
			 * It is easier than implement them via JavaScriptCore API. */
			var file = storage.get_data_file(MAIN_SCRIPT_FILENAME);
			if(file != null){
				try{
					execute_script_from_file_internal(file, false);
					if(service.api_major == 1){
						debug("JS API: API 1.x compatibility layer");
						file = storage.get_data_file(COMPAT_SCRIPT_FILENAME);
						if(file != null){
							execute_script_from_file_internal(file, false);
						}
					}
					else{
						file = storage.get_data_file("js/forms.js");
						if(file != null){
							execute_script_from_file_internal(file, false);
						}
					}
				}
				catch(JSError e){
					critical("Unable to execute Nuvola JS API file: %s: %s",
						file.get_uri(), e.message);
					main_object = null;
					ctx.collect_garbage();
					return false;
				}
				main_object.protect(ctx);
				lock(main_object_ready){
					main_object_ready = true;
				}
				ctx.collect_garbage();
				debug("JSAPI injected successfully");
				return true;
			}
			else{
				critical("Unable to find Nuvola JS API file.");
				main_object = null;
				ctx.collect_garbage();
				return false;
			}
	}
	
	/**
	 * Executes script from file.
	 * 
	 * The context "this" will be set to the main object of Nuvola JS API.
	 * 
	 * @param file	script to execute
	 * @throw JSError on failure
	 */
	public void execute_script_from_file(File file) throws JSError{
		execute_script_from_file_internal(file, false);
		
	}
	
	/**
	 * Executes script from file.
	 * 
	 * The context "this" will be set to the main object of Nuvola JS API.
	 * 
	 * @param file	script to execute
	 * @param check_redy	Check whether the main object is ready (i.e. all external methods have been loaded.)
	 * @throw JSError on failure
	 */
	private void execute_script_from_file_internal(File file, bool check_ready=true) throws JSError{
		string code;
		try{
			code = Diorite.System.read_file(file);
		}
		catch(Error e){
			throw new JSError.READ_ERROR("Unable to read script %s: %s",
				file.get_path(), e.message);
		}
		execute_script_internal(code, file.get_uri(), 1, check_ready);
	}
	
	/**
	 * Executes script.
	 * 
	 * The context "this" will be set to the main object of Nuvola JS API.
	 * 
	 * @param script	script to execute
	 * @throw JSError on failure
	 */
	public void execute_script(string script, string path = "about:blank", int line=1) throws JSError{
		execute_script_internal(script, path, line);
	}
	
	/**
	 * Executes script.
	 * 
	 * The context "this" will be set to the main object of Nuvola JS API.
	 * 
	 * @param script		script to execute
	 * @param check_redy	Check whether the main object is ready (i.e. all external methods have been loaded.)
	 * @throw JSError on failure
	 */
	private void execute_script_internal(string script, string path = "about:blank", int line=1, bool check_ready=true) throws JSError{
		unowned JS.Context ctx = get_valid_context(check_ready); 
		JS.Value exception = null;
		ctx.evaluate_script(new JS.String(script), main_object, new JS.String(path), line=0, out exception);
		if(exception != null){
			throw new JSError.EXCEPTION(exception_to_string(ctx, exception));
		}
	}
	
	/**
	 * Returns current JavaScript context
	 * 
	 * @param check_main_object	if true, the main object must be fully initialized
	 * @return	JavaScript context
	 * @throw JSError					when context or main object are not ready
	 */
	private unowned JS.Context get_valid_context(bool check_main_object=true) throws JSError{
		unowned JS.Context? ctx = this.ctx;
		
		if(ctx == null){
			throw new JSError.NO_CONTEXT("JSApi currently does not have any context.");
		}
		
		if(main_object == null || !main_object_ready && check_main_object){
			throw new JSError.NOT_FOUND("JS API object not found.");
		}
		
		return ctx;
	}
	
	/**
	 * Sends message through JavaScript API
	 * 
	 * @param string	message to send
	 * @throw JSError on failure
	 */
	public void send_message(string message) throws JSError{
		unowned JS.Context ctx = get_valid_context();
		
		unowned JS.Object? command_obj = o_get_object(ctx, main_object, MESSAGE_RECEIVER);
		if(command_obj == null){
			command_obj = o_get_object(ctx, main_object, MESSAGE_RECEIVER);
			ctx.collect_garbage();
			throw new JSError.NOT_FOUND("MessageReceiver object '%s' not found.'".printf(MESSAGE_RECEIVER));
		}
		
		if(!command_obj.is_function(ctx)){
			ctx.collect_garbage();
			throw new JSError.WRONG_TYPE(
				"MessageReceiver object '%s' is not a function.'".printf(MESSAGE_RECEIVER));
		}
		
		void* args[1];
		args[0] = (void*) JS.Value.string(ctx, new JS.String(message));
		JS.Value? exception;
		command_obj.call_as_function(ctx, main_object, (JS.Value[]) args,  out exception);
		if(exception != null){
			ctx.collect_garbage();
			throw new JSError.FUNC_FAILED(
				"Frame command %s failed: %s".printf(message ?? "(null)",
				string_or_null(ctx, exception) ?? "(null)"));
		}
		ctx.collect_garbage();
	}
	
	public static bool is_supported(int api_major, int api_minor){
		return (api_major >= COMPAT_API_MAJOR && api_major < API_VERSION) 
		|| (api_major == API_VERSION && api_minor <= API_VERSION_MINOR);
	}
}

} // namespace Nuvola