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