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