File: mod_w2t.spl

package info (click to toggle)
spl 1.0~pre6-2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 2,352 kB
  • ctags: 2,070
  • sloc: ansic: 16,614; yacc: 3,182; sh: 299; makefile: 165; xml: 156
file content (644 lines) | stat: -rw-r--r-- 15,914 bytes parent folder | download | duplicates (4)
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
/*
 *  SPL - The SPL Programming Language
 *  Copyright (C) 2006  Clifford Wolf <clifford@clifford.at>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *  mod_w2t.spl: The SPL Web 2.0 Toolkit
 */

/**
 * The SPL Web 2.0 Toolkit
 *
 * This module is EXPERIMENTAL and not so well document yet.
 * Expect more to come..
 */

load "task";
load "cgi";

load "xml";
load "encode_xml";

/**
 * The core w2t browser-side scripts.
 *
 * This JavaScript code block defines the following functions:
 *
 *	function w2t_encode_xml(text)
 *
 *		XML-encode the parameter and return the encoded text
 *
 *	function w2t_console_open()
 *
 *		Open a W2T console window (for debug purposes).
 *		Usually one adds a little button or link to the development
 *		versions of an application which calls this function.
 *
 *	function w2t_console(title, text)
 *
 *		This function can be used to write a message to all open
 *		W2T console windows.
 *
 *	function w2t_proccess_dom(n)
 *	function w2t_proccess(xmldata)
 *	function w2t_update_status()
 *	function w2t_gc()
 *
 *		Some functions used internally by w2t_send() for creating the
 *		XML requests and processing the XML responses.
 *
 *	function w2t_send(xmldata, onfinish)
 *
 *		Send a request specified in 'xmldata' to the server and call
 *		'onfinish' after the response has been processed. Usually
 *		one is calling w2t_callback() instead of using w2t_send()
 *		directly.
 *
 *	function w2t_callback(callback_name, arguments)
 *
 *		Call a callback on the server.
 *		The second argument is an array of arguments.
 *
 *	function w2t_animate(finish, workers, seconds, fps)
 *
 *		A generic helper function for animations. The animation runs
 *		for the specified number of seconds with the specified number
 *		of frames per second. Frames are automatically skipped when
 *		rendering becomes too slow. For each frame all functions in
 *		the 'workers' array are called with a floating point value
 *		as parameter (0 for the first frame up to 1 for the last one).
 *
 *	function w2t_animate_fade(id, attr, newval)
 *	function w2t_animate_svgmove(id, newx, newy)
 *
 *		Helper functions which do return function pointers to
 *		dynamically created worker functions for w2t_animate().
 *
 */
var w2t_core_scripts = <>

/*** core w2t functions ***/

var w2t_console_windows = [ ];
var w2t_last_gc_data = "";
var w2t_running_requests = 0;
var w2t_gc_rev = 0;

function w2t_encode_xml(text)
{
	text = text.replace(/&/g, "&amp;");
	text = text.replace(/</g, "&lt;");
	text = text.replace(/>/g, "&gt;");
	text = text.replace(/"/g, "&quot;");
	text = text.replace(/'/g, "&apos;");
	return text;
}

function w2t_console_open()
{
	var w = window.open("about:blank", "_blank", "width=600,height=500,resizable=yes,scrollbars=yes");
	w.document.write("<title>SPL Web 2.0 Toolkit - Console</title>\n");
	w.document.write("<body bgcolor='#ff8888'>\n");
	w.document.write("<h1>SPL Web 2.0 Toolkit - Console</h1>\n");
	w.document.write("<hr/>\n");
	w2t_console_windows.push(w);
}

function w2t_console(title, text)
{
	var htmlcode = "<h3>" + w2t_encode_xml(title) + "</h3><pre>" + w2t_encode_xml(text) + "</pre>\n";

	for (var i=0; i<w2t_console_windows.length; ) {
		if (w2t_console_windows[i].closed)
			w2t_console_windows.splice(i, 1);
		else
			i++;
	}

	for (var i=0; i<w2t_console_windows.length; i++) {
		var w = w2t_console_windows[i];
		w.document.write(htmlcode);
		w.scrollBy(0, 1000000);
	}
}

function w2t_proccess_dom(n)
{
	var method = n.getAttribute("method");
	var on = document.getElementById(n.getAttribute("on"));

	var frag = document.createDocumentFragment();
	for (var c = n.firstChild; c; c = c.nextSibling)
		frag.appendChild(document.importNode(c, true));
	
	if (!on) {
		w2t_console("w2t_proccess_dom()", 'Element addressed using on="' +
				n.getAttribute("on") + '" does not exist.');
		return;
	}
	
	switch (method)
	{
	case "appendchild":
		on.appendChild(frag);
		break;
	case "remove":
		on.parentNode.removeChild(on);
		break;
	case "replaceinner":
		while (on.firstChild)
			on.removeChild(on.firstChild);
		on.appendChild(frag);
		break;
	case "setattr":
		alert(n.getAttribute("name") + " => " + n.textContent);
		on.setAttribute(n.getAttribute("name"), n.textContent);
		break;
	default:
		w2t_console("w2t_proccess_dom()", 'Unknown method: ' + method);
	}
}

function w2t_proccess(xmldata)
{
	var dom_list = xmldata.evaluate("/response/*", xmldata, null, XPathResult.ANY_TYPE, null);
	for (var i = dom_list.iterateNext(); i; i = dom_list.iterateNext()) {
		switch (i.nodeName)
		{
		case "dom":
			w2t_proccess_dom(i);
			break;
		case "script":
			eval(i.textContent);
			break;
		case "callbacksrev":
			if (parseInt(w2t_gc_rev) < parseInt(i.textContent)) {
				if (w2t_running_requests == 1)
					w2t_gc_rev = i.textContent;
				else
					w2t_console("w2t_proccess()", 'Ignoring gc_rev updated to avoid race conditions: ' + w2t_running_requests + ' parallel active requests.');
			}
			
			break;
		default:
			w2t_console("w2t_proccess()", 'I do not know what to do with a ' + i.nodeName + ' element.');
		}
	}
}

function w2t_update_status()
{
	var message;
	if (w2t_running_requests <= 0)
		message = "READY.";
	else
	if (w2t_running_requests == 1)
		message = "Waiting for server ...";
	else
		message = "Waiting for server (" + w2t_running_requests + ")...";
	window.defaultStatus = message;
}

function w2t_gc()
{
	var callback_list = "";

	var gctags = document.evaluate("//@w2t:callbacks", document, w2t_nsresolver, XPathResult.ANY_TYPE, null);
	for (var i = gctags.iterateNext(); i; i = gctags.iterateNext()) {
		if (callback_list != "") callback_list += ",";
		callback_list += i.textContent;
	}

	return "<gccallbacks rev=\"" + w2t_gc_rev + "\">" + callback_list + "</gccallbacks>\n";
}

function w2t_send(xmldata, onfinish)
{
	var postdata = "<?xml version=\"1.0\" ?>\n<request>\n" + xmldata + w2t_gc() + "</request>\n";
	var request;

	w2t_console("XML Request", postdata);

	function processReqChange()
	{
		// only if req shows "complete"
		if (request.readyState == 4) {
			// only if "OK"
			if (request.status == 200) {
				w2t_console("XML Response", request.getAllResponseHeaders() + "\n" + request.responseText);

				if (request.responseXML)
					w2t_proccess(request.responseXML);
				else
					alert("There was a problem parsing the XML response:\n\n" + request.responseText);
			} else {
				alert("There was a problem retrieving the XML response:\n" + request.statusText);
			}

			if (onfinish)
				onfinish();

			w2t_running_requests--;
			w2t_update_status();
		}
	}

	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest) {
		request = new XMLHttpRequest();
	} else
	// branch for IE/Windows ActiveX version
	if (window.ActiveXObject) {
		request = new ActiveXObject("Microsoft.XMLHTTP");
	}

	if (request) {
		w2t_running_requests++;
		w2t_update_status();

		request.overrideMimeType('text/xml');
		request.onreadystatechange = processReqChange;
		request.open("POST", w2t_url, true);
		request.setRequestHeader('Content-Type', 'text/xml');
		request.setRequestHeader('Cache-Control', 'no-cache');
		request.send(postdata);
	} else {
		alert("Can not create an XMLHttpRequest object!\n");
	}
}

function w2t_callback(callback_name, arguments)
{
	var reqdata = "<callback callbackname=\"" + callback_name + "\">\n";

	if (arguments) {
		while (arguments.length > 0)
			reqdata += "<argument>" + arguments.shift() + "</argument>\n";
	}

	reqdata += "</callback>\n";

	w2t_send(reqdata);
}

function w2t_animate(finish, workers, seconds, fps)
{
	var steps = seconds * fps;
	var interval = 1000 / fps;
	var start = new Date();
	var step = 0;

	function update()
	{
		var now = new Date();
		var currentms = now.getTime() - start.getTime();

		while (step > 0 && step < steps && currentms >= ((step+1) * interval))
			step++;

		for (i in workers)
			workers[i](step/steps);

		if (step < steps) {
			step++;
			window.setTimeout(update, interval);
		} else {
			if (finish)
				finish();
		}
	}

	update();
}

function w2t_animate_fade(id, attr, newval)
{
	var element = document.getElementById(id);
	var oldval = parseFloat(element.getAttribute(attr));

	function worker(scale) {
		var current = oldval * (1-scale) + newval * scale;
		element.setAttribute(attr, current);
	}

	return worker;
}

function w2t_animate_svgmove(id, newx, newy)
{
	var element = document.getElementById(id);
	var oldx = parseFloat(element.getAttribute("x"));
	var oldy = parseFloat(element.getAttribute("y"));

	function worker(scale) {
		var current_x = oldx * (1-scale) + newx * scale;
		var current_y = oldy * (1-scale) + newy * scale;
		element.setAttribute("x", current_x);
		element.setAttribute("y", current_y);
	}

	return worker;
}

w2t_update_status();

</>;

/**
 * The W2t object.
 */
object W2t
{
	/**
	 * An array with JavaScript fragments. Other modules can push their
	 * own script fragments to this array when loaded. This scripts are
	 * then automatically included in the application startup page.
	 */
	static scripts = [ w2t_core_scripts ];

	/**
	 * An array with CSS stylesheet fragments. Other modules can push
	 * their own css fragments to this array when loaded. This scripts
	 * are then automatically included in the application startup page.
	 */
	static styles = [ ];

	/**
	 * The namespace URI for the "w2t" namespace prefix.
	 */
	static w2t_ns = "http://www.spl-scripting.org/xml/w2t";

	/**
	 * A hash of namespace declarations one usually wants to use for Web
	 * 2.0 applications (prefix as key and URI as value). Other modules
	 * (and w2t applications) may add additional namespaces. Per default
	 * the following namespaces are defined:
	 *
	 *	w2t     [[.w2t_ns]]
	 *	svg     http://www.w3.org/2000/svg
	 *	xhtml   http://www.w3.org/1999/xhtml
	 *	xlink   http://www.w3.org/1999/xlink
	 *
	 * This hash is used by [[.getxmlnsdecls()]].
	 */
	static xmlns;

	xmlns["w2t"] = w2t_ns;
	xmlns["svg"] = "http://www.w3.org/2000/svg";
	xmlns["xhtml"] = "http://www.w3.org/1999/xhtml";
	xmlns["xlink"] = "http://www.w3.org/1999/xlink";

	/**
	 * The startup page content. This variable must be set before calling
	 * [[.run()]].
	 */
	var startup;

	/**
	 * The mime type of the startup page.
	 */
	var mime_type = "text/xml";

	/**
	 * A hash with all callbacks.
	 *
	 * Use [[.register_callback()]] to add entries.
	 */
	var callbacks;

	/**
	 * A hash with oncleanup event handlers for the callbacks. When the
	 * callback garbage collector cleans up a callback, it also executes
	 * the oncleanup handler if there is one.
	 *
	 * Use [[.register_callback()]] to add entries.
	 */
	var callbacks_oncleanup;

	/**
	 * A revision counter for the callbacks list. It is automatically
	 * incremented by [[.register_callback()]]. This counter is needed
	 * to work arround possible race conditions in the client-side
	 * garbage collection algorithm.
	 */
	var callbacks_rev = 0;

	/**
	 * The current request (when [[.run()]] is active). This is an XML
	 * document handler.
	 */
	var request;

	/**
	 * The current response (when [[.run()]] is active). This is an XML
	 * document handler.
	 */
	var response;

	/**
	 * Register a new callback.
	 */
	method register_callback(id, handler, oncleanup)
	{
		callbacks[id] = handler;
		if (defined oncleanup)
			callbacks_oncleanup[id] = oncleanup;
		callbacks_rev++;
	}

	/**
	 * Add a new XML snippet to the [[.response]] document.
	 */
	method response_add(xmltext)
	{
		page.response["/response"].add_xml_bottom = xmltext;
	}

	/**
	 * Append a child node in the client DOM tree.
	 */
	method dom_appendchild(id, xmltext)
	{
		response_add('<dom method="appendchild" on="$id">$xmltext</dom>');
	}

	/**
	 * Remove a node from the client DOM tree.
	 */
	method dom_remove(id)
	{
		response_add('<dom method="remove" on="$id"/>');
	}

	/**
	 * Replace the inner XML text of node in the client DOM tree.
	 */
	method dom_replaceinner(id, xmltext)
	{
		response_add('<dom method="replaceinner" on="$id">$xmltext</dom>');
	}

	/**
	 * Set (and create if needed) an attribute.
	 */
	method dom_setattr(id, name, value)
	{
		response_add('<dom method="setattr" on="$id" name="$name">${xml::value}</dom>');
	}

	/**
	 * Execute the javascript fragment passed as argument in the client.
	 */
	method execute(script)
	{
		response_add('<script>${xml::script}</script>');
	}

	/**
	 * Return the concatenated contents of [[.scripts]] with an additional
	 * header. This must be included in a <script><![CDATA[ .. ]]></script>
	 * block within the [[.startup]] document.
	 */
	method getscripts()
	{
		var data = <:>
			:
			: // This application is using the SPL Web 2.0 Toolkit
			: // http://www.clifford.at/spl/
			:
			: /*** dynamic stuff from w2t.getscripts() ***/
			:
			: var w2t_url = '${cgi.url}?sid=${cgi.sid}';
			: var w2t_ns = "$w2t_ns";
			: var w2t_xmlns = '$xmlns';
			:
			: function w2t_nsresolver(nsprefix) {
			<spl:foreach var="ns" list="xmlns">
			:	if (nsprefix == "$ns")
			:		return "${xmlns[ns]}";
			</spl:foreach>
			:	return null;
			: }
			:
		</>;
		foreach[] d (scripts)
			data ~= d;
		return data;
	}

	/**
	 * Return the concatenated contents of [[.styles]]. This must be
	 * included in a <style type="text/css"><![CDATA[ .. ]]></style>
	 * block within the [[.startup]] document.
	 */
	method getstyles()
	{
		var data;
		foreach[] d (styles)
			data ~= d;
		return data;
	}

	/**
	 * Return a string with 'xmlns:PREFIX="URI"' xml namespace declarations
	 * built using the [[.xmlns]] hash described above.
	 */
	method getxmlnsdecls()
	{
		var decls = "";
		foreach ns (xmlns)
			decls ~= ($[ ? "" : " ") ~ 'xmlns:$ns="${xmlns[ns]}"';
		return decls;
	}

	// the counter for getid()
	static __w2t_getid_counter = 1;

	/**
	 * Get a unique id, e.g. for the id="" attribute of auto-generated
	 * XML elements and for callback names.
	 */
	method getid()
	{
		return "w2tid${__w2t_getid_counter++}";
	}

	/**
	 * Main runloop. This function never returns. It just calls prior
	 * registered callback functions.
	 */
	method run()
	{
		cgi.content_type = mime_type;
		write(startup);

		while (1) {
			task_pause();
			cgi.silent_debug = 1;

			request = xml_parse(cgi.post_data);
			response = xml_parse(<:>
				: <?xml version="1.0" ?>
				: <response ${getxmlnsdecls()}>
				: </response>
			</>);

			var gc_callbacks = request["/request/gc/callbacks"];
			var gc_callbacks_rev = request["/request/gc/callbacks/@rev"];

			if (defined gc_callbacks and gc_callbacks_rev == callbacks_rev)
			{
				var h;

				foreach[] c (gc_callbacks =~ /[^,]+/Ag)
					h[c] = undef;

				foreach c (callbacks)
					if (not declared h[c]) {
						if (declared callbacks_oncleanup[c]) {
							callbacks_oncleanup[c](c);
							delete callbacks_oncleanup[c];
						}
						delete callbacks[c];
					}
			}

			foreach[] c (request["/request/callback"].nodes) {
				var args = [ c ];
				foreach[] n (c["argument"].nodes)
					push args, c[n];
				callbacks[c["@callbackname"]](@args);
			}

			page.response_add('<callbacksrev>$callbacks_rev</callbacksrev>\n');

			cgi.content_type = "text/xml";
			write(xml_dump(response));

			request = undef;
			response = undef;
		}
	}

	/**
	 * Constructor.
	 */
	method init()
	{
		return this;
	}
}