miscell cosmetic
[myslice.git] / manifold / static / js / manifold.js
1 // utilities 
2 function debug_dict_keys (msg, o) {
3     var keys=[];
4     for (var k in o) keys.push(k);
5     messages.debug ("debug_dict_keys: " + msg + " keys= " + keys);
6 }
7 function debug_dict (msg, o) {
8     for (var k in o) messages.debug ("debug_dict: " + msg + " [" + k + "]=" + o[k]);
9 }
10 function debug_value (msg, value) {
11     messages.debug ("debug_value: " + msg + " " + value);
12 }
13 function debug_query (msg, query) {
14     if (query === undefined) messages.debug ("debug_query: " + msg + " -> undefined");
15     else if (query == null) messages.debug ("debug_query: " + msg + " -> null");
16     else if ('query_uuid' in query) messages.debug ("debug_query: " + msg + query.__repr());
17     else messages.debug ("debug_query: " + msg + " query= " + query);
18 }
19
20 // http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
21 Object.toType = (function toType(global) {
22   return function(obj) {
23     if (obj === global) {
24       return "global";
25     }
26     return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
27   }
28 })(this);
29
30 /* ------------------------------------------------------------ */
31
32 // Constants that should be somehow moved to a plugin.js file
33 var FILTER_ADDED   = 1;
34 var FILTER_REMOVED = 2;
35 var CLEAR_FILTERS  = 3;
36 var FIELD_ADDED    = 4;
37 var FIELD_REMOVED  = 5;
38 var CLEAR_FIELDS   = 6;
39 var NEW_RECORD     = 7;
40 var CLEAR_RECORDS  = 8;
41 var FIELD_STATE_CHANGED = 9;
42
43 var IN_PROGRESS    = 101;
44 var DONE           = 102;
45
46 /* Update requests related to subqueries */
47 var SET_ADD        = 201;
48 var SET_REMOVED    = 202;
49
50 // request
51 var FIELD_REQUEST_CHANGE  = 301;
52 var FIELD_REQUEST_ADD     = 302;
53 var FIELD_REQUEST_REMOVE  = 303;
54 var FIELD_REQUEST_ADD_RESET = 304;
55 var FIELD_REQUEST_REMOVE_RESET = 305;
56 // status
57 var FIELD_REQUEST_PENDING = 401;
58 var FIELD_REQUEST_SUCCESS = 402;
59 var FIELD_REQUEST_FAILURE = 403;
60
61 /* Query status */
62 var STATUS_NONE               = 500; // Query has not been started yet
63 var STATUS_GET_IN_PROGRESS    = 501; // Query has been sent, no result has been received
64 var STATUS_GET_RECEIVED       = 502; // Success
65 var STATUS_GET_ERROR          = 503; // Error
66 var STATUS_UPDATE_PENDING     = 504;
67 var STATUS_UPDATE_IN_PROGRESS = 505;
68 var STATUS_UPDATE_RECEIVED    = 506;
69 var STATUS_UPDATE_ERROR       = 507;
70
71 /* Requests for query cycle */
72 var RUN_UPDATE     = 601;
73
74 /* MANIFOLD types */
75 var TYPE_VALUE  = 1;
76 var TYPE_RECORD = 2;
77 var TYPE_LIST_OF_VALUES = 3;
78 var TYPE_LIST_OF_RECORDS = 4;
79
80
81 // A structure for storing queries
82
83 function QueryExt(query, parent_query_ext, main_query_ext, update_query_ext, disabled) {
84
85     /* Constructor */
86     if (typeof query == "undefined")
87         throw "Must pass a query in QueryExt constructor";
88     this.query                 = query;
89     this.parent_query_ext      = (typeof parent_query_ext      == "undefined") ? null  : parent_query_ext;
90     this.main_query_ext        = (typeof main_query_ext        == "undefined") ? null  : main_query_ext;
91     this.update_query_ext      = (typeof update_query_ext      == "undefined") ? null  : update_query_ext;
92     this.update_query_orig_ext = (typeof update_query_orig_ext == "undefined") ? null  : update_query_orig_ext;
93     this.disabled              = (typeof update_query_ext      == "undefined") ? false : disabled;
94     
95     this.status       = null;
96     this.results      = null;
97     // update_query null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
98 }
99
100 function QueryStore() {
101
102     this.main_queries     = {};
103     this.analyzed_queries = {};
104
105     /* Insertion */
106
107     this.insert = function(query) {
108         // We expect only main_queries are inserted
109         
110         /* If the query has not been analyzed, then we analyze it */
111         if (query.analyzed_query == null) {
112             query.analyze_subqueries();
113         }
114
115         /* We prepare the update query corresponding to the main query and store both */
116         /* Note: they have the same UUID */
117
118         // XXX query.change_action() should become deprecated
119         update_query = query.clone();
120         update_query.action = 'update';
121         update_query.analyzed_query.action = 'update';
122         update_query.params = {};
123         update_query_ext = new QueryExt(update_query);
124
125         /* We remember the original query to be able to reset it */
126         update_query_orig_ext = new QueryExt(update_query.clone());
127
128
129         /* We store the main query */
130         query_ext = new QueryExt(query, null, null, update_query_ext, update_query_orig_ext, false);
131         manifold.query_store.main_queries[query.query_uuid] = query_ext;
132         /* Note: the update query does not have an entry! */
133
134
135         // The query is disabled; since it is incomplete until we know the content of the set of subqueries
136         // XXX unless we have no subqueries ???
137         // we will complete with params when records are received... this has to be done by the manager
138         // SET_ADD, SET_REMOVE will change the status of the elements of the set
139         // UPDATE will change also, etc.
140         // XXX We need a proper structure to store this information...
141
142         // We also need to insert all queries and subqueries from the analyzed_query
143         // XXX We need the root of all subqueries
144         query.iter_subqueries(function(sq, data, parent_query) {
145             if (parent_query)
146                 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
147             else
148                 parent_query_ext = null;
149             // XXX parent_query_ext == false
150             // XXX main.subqueries = {} # Normal, we need analyzed_query
151             sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
152             manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
153         });
154
155         // XXX We have spurious update queries...
156     }
157
158     /* Searching */
159
160     this.find_query_ext = function(query_uuid) {
161         return this.main_queries[query_uuid];
162     }
163
164     this.find_query = function(query_uuid) {
165         return this.find_query_ext(query_uuid).query;
166     }
167
168     this.find_analyzed_query_ext = function(query_uuid) {
169         return this.analyzed_queries[query_uuid];
170     }
171
172     this.find_analyzed_query = function(query_uuid) {
173         return this.find_analyzed_query_ext(query_uuid).query;
174     }
175 }
176
177 /*!
178  * This namespace holds functions for globally managing query objects
179  * \Class Manifold
180  */
181 var manifold = {
182
183     /************************************************************************** 
184      * Helper functions
185      **************************************************************************/ 
186
187     separator: '__',
188
189     spin_presets: {},
190
191     spin: function(locator, active /*= true */) {
192         active = typeof active !== 'undefined' ? active : true;
193         try {
194             if (active) {
195                 $(locator).spin(manifold.spin_presets);
196             } else {
197                 $(locator).spin(false);
198             }
199         } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
200     },
201
202     get_type: function(variable) {
203         switch(Object.toType(variable)) {
204             case 'number':
205             case 'string':
206                 return TYPE_VALUE;
207             case 'object':
208                 return TYPE_RECORD;
209             case 'array':
210                 if ((variable.length > 0) && (Object.toType(variable[0]) === 'object'))
211                     return TYPE_LIST_OF_RECORDS;
212                 else
213                     return TYPE_LIST_OF_VALUES;
214         }
215     },
216
217     /************************************************************************** 
218      * Metadata management
219      **************************************************************************/ 
220
221      metadata: {
222
223         get_table: function(method) {
224             var table = MANIFOLD_METADATA[method];
225             return (typeof table === 'undefined') ? null : table;
226         },
227
228         get_columns: function(method) {
229             var table = this.get_table(method);
230             if (!table) {
231                 return null;
232             }
233
234             return (typeof table.column === 'undefined') ? null : table.column;
235         },
236
237         get_key: function(method) {
238             var table = this.get_table(method);
239             if (!table)
240                 return null;
241
242             return (typeof table.key === 'undefined') ? null : table.key;
243         },
244
245
246         get_column: function(method, name) {
247             var columns = this.get_columns(method);
248             if (!columns)
249                 return null;
250
251             $.each(columns, function(i, c) {
252                 if (c.name == name)
253                     return c
254             });
255             return null;
256         },
257
258         get_type: function(method, name) {
259             var table = this.get_table(method);
260             if (!table)
261                 return null;
262
263             return (typeof table.type === 'undefined') ? null : table.type;
264         }
265
266      },
267
268     /************************************************************************** 
269      * Query management
270      **************************************************************************/ 
271
272     query_store: new QueryStore(),
273
274     // XXX Remaining functions are deprecated since they are replaced by the query store
275
276     /*!
277      * Associative array storing the set of queries active on the page
278      * \memberof Manifold
279      */
280     all_queries: {},
281
282     /*!
283      * Insert a query in the global hash table associating uuids to queries.
284      * If the query has no been analyzed yet, let's do it.
285      * \fn insert_query(query)
286      * \memberof Manifold
287      * \param ManifoldQuery query Query to be added
288      */
289     insert_query : function (query) { 
290         // NEW API
291         manifold.query_store.insert(query);
292
293         // FORMER API
294         if (query.analyzed_query == null) {
295             query.analyze_subqueries();
296         }
297         manifold.all_queries[query.query_uuid]=query;
298     },
299
300     /*!
301      * Returns the query associated to a UUID
302      * \fn find_query(query_uuid)
303      * \memberof Manifold
304      * \param string query_uuid The UUID of the query to be returned
305      */
306     find_query : function (query_uuid) { 
307         return manifold.all_queries[query_uuid];
308     },
309
310     /************************************************************************** 
311      * Query execution
312      **************************************************************************/ 
313
314     // trigger a query asynchroneously
315     proxy_url : '/manifold/proxy/json/',
316
317     // reasonably low-noise, shows manifold requests coming in and out
318     asynchroneous_debug : true,
319     // print our more details on result publication and related callbacks
320     publish_result_debug : false,
321
322     /**
323      * \brief We use js function closure to be able to pass the query (array)
324      * to the callback function used when data is received
325      */
326     success_closure: function(query, publish_uuid, callback) {
327         return function(data, textStatus) {
328             manifold.asynchroneous_success(data, query, publish_uuid, callback);
329         }
330     },
331
332     run_query: function(query, callback) {
333         // default value for callback = null
334         if (typeof callback === 'undefined')
335             callback = null; 
336
337         var query_json = JSON.stringify(query);
338
339         /* Nothing related to pubsub here... for the moment at least. */
340         //query.iter_subqueries(function (sq) {
341         //    manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
342         //});
343
344         $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, null, callback));
345     },
346
347     // Executes all async. queries - intended for the javascript header to initialize queries
348     // input queries are specified as a list of {'query_uuid': <query_uuid> }
349     // each plugin is responsible for managing its spinner through on_query_in_progress
350     asynchroneous_exec : function (query_exec_tuples) {
351         
352         // Loop through input array, and use publish_uuid to publish back results
353         $.each(query_exec_tuples, function(index, tuple) {
354             var query=manifold.find_query(tuple.query_uuid);
355             var query_json=JSON.stringify (query);
356             var publish_uuid=tuple.publish_uuid;
357             // by default we publish using the same uuid of course
358             if (publish_uuid==undefined) publish_uuid=query.query_uuid;
359             if (manifold.publish_result_debug) {
360                 messages.debug("sending POST on " + manifold.proxy_url + query.__repr());
361             }
362
363             query.iter_subqueries(function (sq) {
364                 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
365             });
366
367             // not quite sure what happens if we send a string directly, as POST data is named..
368             // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
369             $.post(manifold.proxy_url, {'json':query_json}, 
370                    manifold.success_closure(query, publish_uuid, tuple.callback));
371         })
372     },
373
374     /**
375      * \brief Forward a query to the manifold backend
376      * \param query (dict) the query to be executed asynchronously
377      * \param callback (function) the function to be called when the query terminates
378      */
379     forward: function(query, callback) {
380         var query_json = JSON.stringify(query);
381         $.post(manifold.proxy_url, {'json': query_json} , 
382                manifold.success_closure(query, query.query_uuid, callback));
383     },
384
385     /*!
386      * Returns whether a query expects a unique results.
387      * This is the case when the filters contain a key of the object
388      * \fn query_expects_unique_result(query)
389      * \memberof Manifold
390      * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
391      */
392     query_expects_unique_result: function(query) {
393         /* XXX we need functions to query metadata */
394         //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
395         /* TODO requires keys in metadata */
396         return true;
397     },
398
399     /*!
400      * Publish result
401      * \fn publish_result(query, results)
402      * \memberof Manifold
403      * \param ManifoldQuery query Query which has received results
404      * \param array results results corresponding to query
405      */
406     publish_result: function(query, result) {
407         if (typeof result === 'undefined')
408             result = [];
409
410         // NEW PLUGIN API
411         manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
412         if (manifold.publish_result_debug)
413             messages.debug(".. publish_result (1) ");
414         var count=0;
415         $.each(result, function(i, record) {
416             manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
417             count += 1;
418         });
419         if (manifold.publish_result_debug) 
420             messages.debug(".. publish_result NEW API (2) count=" + count);
421         manifold.raise_record_event(query.query_uuid, DONE);
422
423         // OLD PLUGIN API BELOW
424         /* Publish an update announce */
425         var channel="/results/" + query.query_uuid + "/changed";
426         if (manifold.publish_result_debug) 
427             messages.debug(".. publish_result OLD API (3) " + channel);
428
429         $.publish(channel, [result, query]);
430
431         if (manifold.publish_result_debug) 
432             messages.debug(".. publish_result - END (4) q=" + query.__repr());
433     },
434
435     /*!
436      * Recursively publish result
437      * \fn publish_result_rec(query, result)
438      * \memberof Manifold
439      * \param ManifoldQuery query Query which has received result
440      * \param array result result corresponding to query
441      *
442      * Note: this function works on the analyzed query
443      */
444     publish_result_rec: function(query, result) {
445         /* If the result is not unique, only publish the top query;
446          * otherwise, publish the main object as well as subqueries
447          * XXX how much recursive are we ?
448          */
449         if (manifold.publish_result_debug)
450             messages.debug (">>>>> publish_result_rec " + query.object);
451         if (manifold.query_expects_unique_result(query)) {
452             /* Also publish subqueries */
453             $.each(query.subqueries, function(object, subquery) {
454                 manifold.publish_result_rec(subquery, result[0][object]);
455                 /* TODO remove object from result */
456             });
457         }
458         if (manifold.publish_result_debug) 
459             messages.debug ("===== publish_result_rec " + query.object);
460
461         manifold.publish_result(query, result);
462
463         if (manifold.publish_result_debug) 
464             messages.debug ("<<<<< publish_result_rec " + query.object);
465     },
466
467     setup_update_query: function(query, records) {
468         // We don't prepare an update query if the result has more than 1 entry
469         if (records.length != 1)
470             return;
471         var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
472
473         var record = records[0];
474
475         var update_query_ext = query_ext.update_query_ext;
476         var update_query = update_query_ext.query;
477         var update_query_ext = query_ext.update_query_ext;
478         var update_query_orig = query_ext.update_query_orig_ext.query;
479
480         // Testing whether the result has subqueries (one level deep only)
481         // iif the query has subqueries
482         var count = 0;
483         var obj = query.analyzed_query.subqueries;
484         for (method in obj) {
485             if (obj.hasOwnProperty(method)) {
486                 var key = manifold.metadata.get_key(method);
487                 if (!key)
488                     continue;
489                 if (key.length > 1)
490                     continue;
491                 key = key[0];
492                 var sq_keys = [];
493                 var subrecords = record[method];
494                 if (!subrecords)
495                     continue
496                 $.each(subrecords, function (i, subrecord) {
497                     sq_keys.push(subrecord[key]);
498                 });
499                 update_query.params[method] = sq_keys;
500                 update_query_orig.params[method] = sq_keys.slice();
501                 count++;
502             }
503         }
504
505         if (count > 0) {
506             update_query_ext.disabled = false;
507             update_query_orig_ext.disabled = false;
508         }
509     },
510
511     process_get_query_records: function(query, records) {
512         this.setup_update_query(query, records);
513
514         /* Publish full results */
515         var tmp_query = manifold.find_query(query.query_uuid);
516         manifold.publish_result_rec(tmp_query.analyzed_query, records);
517     },
518
519     /**
520      * 
521      * What we need to do when receiving results from an update query:
522      * - differences between what we had, what we requested, and what we obtained
523      *    . what we had : update_query_orig (simple fields and set fields managed differently)
524      *    . what we requested : update_query
525      *    . what we received : records
526      * - raise appropriate events
527      *
528      * The normal process is that results similar to Get will be pushed in the
529      * pubsub mechanism, thus repopulating everything while we only need
530      * diff's. This means we need to move the publish functionalities in the
531      * previous 'process_get_query_records' function.
532      */
533     process_update_query_records: function(query, records) {
534         // First issue: we request everything, and not only what we modify, so will will have to ignore some fields
535         var query_uuid        = query.query_uuid;
536         var query_ext         = manifold.query_store.find_analyzed_query_ext(query_uuid);
537         var update_query      = query_ext.main_query_ext.update_query_ext.query;
538         var update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
539         
540         // Since we update objects one at a time, we can get the first record
541         var record = records[0];
542
543         // Let's iterate over the object properties
544         for (var field in record) {
545             switch (this.get_type(record[field])) {
546                 case TYPE_VALUE:
547                     // Did we ask for a change ?
548                     var update_value = update_query[field];
549                     if (!update_value)
550                         // Not requested, if it has changed: OUT OF SYNC
551                         // How we can know ?
552                         // We assume it won't have changed
553                         continue;
554
555                     var result_value = record[field];
556                     if (!result_value)
557                         throw "Internal error";
558
559                     data = {
560                         request: FIELD_REQUEST_CHANGE,
561                         key   : field,
562                         value : update_value,
563                         status: (update_value == result_value) ? FIELD_REQUEST_SUCCESS : FIELD_REQUEST_FAILURE,
564                     }
565                     manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
566
567                     break;
568                 case TYPE_RECORD:
569                     throw "Not implemented";
570                     break;
571
572                 case TYPE_LIST_OF_VALUES:
573                     // Same as list of records, but we don't have to extract keys
574                     var result_keys  = record[field]
575                     
576                     // The rest of exactly the same (XXX factorize)
577                     var update_keys  = update_query_orig.params[field];
578                     var query_keys   = update_query.params[field];
579                     var added_keys   = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
580                     var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
581
582
583                     $.each(added_keys, function(i, key) {
584                         if ($.inArray(key, result_keys) == -1) {
585                             data = {
586                                 request: FIELD_REQUEST_ADD,
587                                 key   : field,
588                                 value : key,
589                                 status: FIELD_REQUEST_FAILURE,
590                             }
591                         } else {
592                             data = {
593                                 request: FIELD_REQUEST_ADD,
594                                 key   : field,
595                                 value : key,
596                                 status: FIELD_REQUEST_SUCCESS,
597                             }
598                         }
599                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
600                     });
601                     $.each(removed_keys, function(i, key) {
602                         if ($.inArray(key, result_keys) == -1) {
603                             data = {
604                                 request: FIELD_REQUEST_REMOVE,
605                                 key   : field,
606                                 value : key,
607                                 status: FIELD_REQUEST_SUCCESS,
608                             }
609                         } else {
610                             data = {
611                                 request: FIELD_REQUEST_REMOVE,
612                                 key   : field,
613                                 value : key,
614                                 status: FIELD_REQUEST_FAILURE,
615                             }
616                         }
617                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
618                     });
619
620
621                     break;
622                 case TYPE_LIST_OF_RECORDS:
623                     // example: slice.resource
624                     //  - update_query_orig.params.resource = resources in slice before update
625                     //  - update_query.params.resource = resource requested in slice
626                     //  - keys from field = resources obtained
627                     var key = manifold.metadata.get_key(field);
628                     if (!key)
629                         continue;
630                     if (key.length > 1) {
631                         throw "Not implemented";
632                         continue;
633                     }
634                     key = key[0];
635
636                     /* XXX should be modified for multiple keys */
637                     var result_keys  = $.map(record[field], function(x) { return x[key]; });
638
639                     var update_keys  = update_query_orig.params[field];
640                     var query_keys   = update_query.params[field];
641                     var added_keys   = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
642                     var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
643
644
645                     $.each(added_keys, function(i, key) {
646                         if ($.inArray(key, result_keys) == -1) {
647                             data = {
648                                 request: FIELD_REQUEST_ADD,
649                                 key   : field,
650                                 value : key,
651                                 status: FIELD_REQUEST_FAILURE,
652                             }
653                         } else {
654                             data = {
655                                 request: FIELD_REQUEST_ADD,
656                                 key   : field,
657                                 value : key,
658                                 status: FIELD_REQUEST_SUCCESS,
659                             }
660                         }
661                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
662                     });
663                     $.each(removed_keys, function(i, key) {
664                         if ($.inArray(key, result_keys) == -1) {
665                             data = {
666                                 request: FIELD_REQUEST_REMOVE,
667                                 key   : field,
668                                 value : key,
669                                 status: FIELD_REQUEST_SUCCESS,
670                             }
671                         } else {
672                             data = {
673                                 request: FIELD_REQUEST_REMOVE,
674                                 key   : field,
675                                 value : key,
676                                 status: FIELD_REQUEST_FAILURE,
677                             }
678                         }
679                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
680                     });
681
682
683                     break;
684             }
685         }
686         
687         // XXX Now we need to adapt 'update' and 'update_orig' queries as if we had done a get
688         this.setup_update_query(query, records);
689     },
690
691     process_query_records: function(query, records) {
692         if (query.action == 'get') {
693             this.process_get_query_records(query, records);
694         } else if (query.action == 'update') {
695             this.process_update_query_records(query, records);
696         }
697     },
698
699     // if set callback is provided it is called
700     // most of the time publish_uuid will be query.query_uuid
701     // however in some cases we wish to publish the result under a different uuid
702     // e.g. an updater wants to publish its result as if from the original (get) query
703     asynchroneous_success : function (data, query, publish_uuid, callback) {
704         // xxx should have a nicer declaration of that enum in sync with the python code somehow
705         
706         var start = new Date();
707         if (manifold.asynchroneous_debug)
708             messages.debug(">>>>>>>>>> asynchroneous_success query.object=" + query.object);
709
710         if (data.code == 2) { // ERROR
711             // We need to make sense of error codes here
712             alert("Your session has expired, please log in again");
713             window.location="/logout/";
714             if (manifold.asynchroneous_debug) {
715                 duration=new Date()-start;
716                 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- error returned - logging out " + duration + " ms");
717             }
718             return;
719         }
720         if (data.code == 1) { // WARNING
721             messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
722             // publish error code and text message on a separate channel for whoever is interested
723             if (publish_uuid)
724                 $.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
725
726         }
727
728         // If a callback has been specified, we redirect results to it 
729         if (!!callback) { 
730             callback(data); 
731             if (manifold.asynchroneous_debug) {
732                 duration=new Date()-start;
733                 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- callback ended " + duration + " ms");
734             }
735             return; 
736         }
737
738         if (manifold.asynchroneous_debug) 
739             messages.debug ("========== asynchroneous_success " + query.object + " -- before process_query_records");
740
741         // once everything is checked we can use the 'value' part of the manifoldresult
742         var result=data.value;
743         if (result) {
744             /* Eventually update the content of related queries (update, etc) */
745             this.process_query_records(query, result);
746
747             /* Publish results: disabled here, done in the previous call */
748             //tmp_query = manifold.find_query(query.query_uuid);
749             //manifold.publish_result_rec(tmp_query.analyzed_query, result);
750         }
751         if (manifold.asynchroneous_debug) {
752             duration=new Date()-start;
753             messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- done " + duration + " ms");
754         }
755
756     },
757
758     /************************************************************************** 
759      * Plugin API helpers
760      **************************************************************************/ 
761
762     raise_event_handler: function(type, query_uuid, event_type, value) {
763         if ((type != 'query') && (type != 'record'))
764             throw 'Incorrect type for manifold.raise_event()';
765         // xxx we observe quite a lot of incoming calls with an undefined query_uuid
766         // this should be fixed upstream
767         if (query_uuid === undefined) {
768             messages.warning("undefined query in raise_event_handler");
769             return;
770         }
771
772         // notify the change to objects that either listen to this channel specifically,
773         // or to the wildcard channel
774         var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
775
776         $.each(channels, function(i, channel) {
777             if (value === undefined) {
778                 $('.plugin').trigger(channel, [event_type]);
779             } else {
780                 $('.plugin').trigger(channel, [event_type, value]);
781             }
782         });
783     },
784
785     raise_query_event: function(query_uuid, event_type, value) {
786         manifold.raise_event_handler('query', query_uuid, event_type, value);
787     },
788
789     raise_record_event: function(query_uuid, event_type, value) {
790         manifold.raise_event_handler('record', query_uuid, event_type, value);
791     },
792
793
794     raise_event: function(query_uuid, event_type, value) {
795         // Query uuid has been updated with the key of a new element
796         query_ext    = manifold.query_store.find_analyzed_query_ext(query_uuid);
797         query = query_ext.query;
798
799         switch(event_type) {
800             case FIELD_STATE_CHANGED:
801                 // value is an object (request, key, value, status)
802                 // update is only possible is the query is not pending, etc
803                 // SET_ADD is on a subquery, FIELD_STATE_CHANGED on the query itself
804                 // we should map SET_ADD on this...
805
806                 // 1. Update internal query store about the change in status
807
808                 // 2. Update the update query
809                 update_query      = query_ext.main_query_ext.update_query_ext.query;
810                 update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
811
812                 switch(value.request) {
813                     case FIELD_REQUEST_CHANGE:
814                         if (update_query.params[value.key] === undefined)
815                             update_query.params[value.key] = Array();
816                         update_query.params[value.key] = value.value;
817                         break;
818                     case FIELD_REQUEST_ADD:
819                         if ($.inArray(value.value, update_query_orig.params[value.key]) != -1)
820                             value.request = FIELD_REQUEST_ADD_RESET;
821                         if (update_query.params[value.key] === undefined)
822                             update_query.params[value.key] = Array();
823                         update_query.params[value.key].push(value.value);
824                         break;
825                     case FIELD_REQUEST_REMOVE:
826                         if ($.inArray(value.value, update_query_orig.params[value.key]) == -1)
827                             value.request = FIELD_REQUEST_REMOVE_RESET;
828
829                         var arr = update_query.params[value.key];
830                         arr = $.grep(arr, function(x) { return x != value.value; });
831                         if (update_query.params[value.key] === undefined)
832                             update_query.params[value.key] = Array();
833                         update_query.params[value.key] = arr;
834
835                         break;
836                     case FIELD_REQUEST_ADD_RESET:
837                     case FIELD_REQUEST_REMOVE_RESET:
838                         // XXX We would need to keep track of the original query
839                         throw "Not implemented";
840                         break;
841                 }
842
843                 // 3. Inform others about the change
844                 // a) the main query...
845                 manifold.raise_record_event(query_uuid, event_type, value);
846
847                 // b) subqueries eventually (dot in the key)
848                 // Let's unfold 
849                 var path_array = value.key.split('.');
850                 var value_key = value.key.split('.');
851
852                 var cur_query = query;
853                 if (cur_query.analyzed_query)
854                     cur_query = cur_query.analyzed_query;
855                 $.each(path_array, function(i, method) {
856                     cur_query = cur_query.subqueries[method];
857                     value_key.shift(); // XXX check that method is indeed shifted
858                 });
859                 value.key = value_key;
860
861                 manifold.raise_record_event(cur_query.query_uuid, event_type, value);
862
863                 // XXX make this DOT a global variable... could be '/'
864                 break;
865
866             case SET_ADD:
867             case SET_REMOVED:
868     
869                 // update is only possible is the query is not pending, etc
870                 // CHECK status !
871
872                 // XXX we can only update subqueries of the main query. Check !
873                 // assert query_ext.parent_query == query_ext.main_query
874                 // old // update_query = query_ext.main_query_ext.update_query_ext.query;
875
876                 // This SET_ADD is called on a subquery, so we have to
877                 // recontruct the path of the key in the main_query
878                 // We then call FIELD_STATE_CHANGED which is the equivalent for the main query
879
880                 var path = "";
881                 var sq = query_ext;
882                 while (sq.parent_query_ext) {
883                     if (path != "")
884                         path = '.' + path;
885                     path = sq.query.object + path;
886                     sq = sq.parent_query_ext;
887                 }
888
889                 main_query = query_ext.main_query_ext.query;
890                 data = {
891                     request: (event_type == SET_ADD) ? FIELD_REQUEST_ADD : FIELD_REQUEST_REMOVE,
892                     key   : path,
893                     value : value,
894                     status: FIELD_REQUEST_PENDING,
895                 };
896                 this.raise_event(main_query.query_uuid, FIELD_STATE_CHANGED, data);
897
898                 // old //update_query.params[path].push(value);
899                 // old // console.log('Updated query params', update_query);
900                 // NOTE: update might modify the fields in Get
901                 // NOTE : we have to modify all child queries
902                 // NOTE : parts of a query might not be started (eg slice.measurements, how to handle ?)
903
904                 // if everything is done right, update_query should not be null. 
905                 // It is updated when we received results from the get query
906                 // object = the same as get
907                 // filter = key : update a single object for now
908                 // fields = the same as get
909                 manifold.raise_query_event(query_uuid, event_type, value);
910
911                 break;
912
913             case RUN_UPDATE:
914                 manifold.run_query(query_ext.main_query_ext.update_query_ext.query);
915                 break;
916
917             case FILTER_ADDED: 
918 // Thierry - this is probably wrong but intended as a hotfix 
919 // http://trac.myslice.info/ticket/32
920 //                manifold.raise_query_event(query_uuid, event_type, value);
921                 break;
922             case FILTER_REMOVED:
923                 manifold.raise_query_event(query_uuid, event_type, value);
924                 break;
925             case FIELD_ADDED:
926                 main_query = query_ext.main_query_ext.query;
927                 main_update_query = query_ext.main_query_ext.update_query;
928                 query.select(value);
929
930                 // Here we need the full path through all subqueries
931                 path = ""
932                 // XXX We might need the query name in the QueryExt structure
933                 main_query.select(value);
934
935                 // XXX When is an update query associated ?
936                 // XXX main_update_query.select(value);
937
938                 manifold.raise_query_event(query_uuid, event_type, value);
939                 break;
940
941             case FIELD_REMOVED:
942                 query = query_ext.query;
943                 main_query = query_ext.main_query_ext.query;
944                 main_update_query = query_ext.main_query_ext.update_query;
945                 query.unselect(value);
946                 main_query.unselect(value);
947
948                 // We need to inform about changes in these queries to the respective plugins
949                 // Note: query & main_query have the same UUID
950                 manifold.raise_query_event(query_uuid, event_type, value);
951                 break;
952         }
953         // We need to inform about changes in these queries to the respective plugins
954         // Note: query, main_query & update_query have the same UUID
955         manifold.raise_query_event(query_uuid, event_type, value);
956         // We are targeting the same object with get and update
957         // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
958         // NOTE: Editing a subquery == editing a local view on the destination
959
960         // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
961         // For the time being, we will collect all columns during the first query
962     },
963
964     /* Publish/subscribe channels for internal use */
965     get_channel: function(type, query_uuid) {
966         if ((type !== 'query') && (type != 'record'))
967             return null;
968         return '/' + type + '/' + query_uuid;
969     },
970
971 }; // manifold object
972 /* ------------------------------------------------------------ */
973
974 (function($) {
975
976     // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
977     // https://gist.github.com/661855
978     var o = $({});
979     $.subscribe = function( channel, selector, data, fn) {
980       /* borrowed from jQuery */
981       if ( data == null && fn == null ) {
982           // ( channel, fn )
983           fn = selector;
984           data = selector = undefined;
985       } else if ( fn == null ) {
986           if ( typeof selector === "string" ) {
987               // ( channel, selector, fn )
988               fn = data;
989               data = undefined;
990           } else {
991               // ( channel, data, fn )
992               fn = data;
993               data = selector;
994               selector = undefined;
995           }
996       }
997       /* </ugly> */
998   
999       /* We use an indirection function that will clone the object passed in
1000        * parameter to the subscribe callback 
1001        * 
1002        * FIXME currently we only clone query objects which are the only ones
1003        * supported and editable, we might have the same issue with results but
1004        * the page load time will be severely affected...
1005        */
1006       o.on.apply(o, [channel, selector, data, function() { 
1007           for(i = 1; i < arguments.length; i++) {
1008               if ( arguments[i].constructor.name == 'ManifoldQuery' )
1009                   arguments[i] = arguments[i].clone();
1010           }
1011           fn.apply(o, arguments);
1012       }]);
1013     };
1014   
1015     $.unsubscribe = function() {
1016       o.off.apply(o, arguments);
1017     };
1018   
1019     $.publish = function() {
1020       o.trigger.apply(o, arguments);
1021     };
1022   
1023 }(jQuery));
1024
1025 /* ------------------------------------------------------------ */
1026
1027 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
1028 //make sure to expose csrf in our outcoming ajax/post requests
1029 $.ajaxSetup({ 
1030      beforeSend: function(xhr, settings) {
1031          function getCookie(name) {
1032              var cookieValue = null;
1033              if (document.cookie && document.cookie != '') {
1034                  var cookies = document.cookie.split(';');
1035                  for (var i = 0; i < cookies.length; i++) {
1036                      var cookie = jQuery.trim(cookies[i]);
1037                      // Does this cookie string begin with the name we want?
1038                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
1039                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
1040                      break;
1041                  }
1042              }
1043          }
1044          return cookieValue;
1045          }
1046          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
1047              // Only send the token to relative URLs i.e. locally.
1048              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
1049          }
1050      } 
1051 });