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