2 function debug_dict_keys (msg, o) {
4 for (var k in o) keys.push(k);
5 messages.debug ("debug_dict_keys: " + msg + " keys= " + keys);
7 function debug_dict (msg, o) {
8 for (var k in o) messages.debug ("debug_dict: " + msg + " [" + k + "]=" + o[k]);
10 function debug_value (msg, value) {
11 messages.debug ("debug_value: " + msg + " " + value);
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);
20 /* ------------------------------------------------------------ */
22 // Constants that should be somehow moved to a plugin.js file
24 var FILTER_REMOVED = 2;
25 var CLEAR_FILTERS = 3;
27 var FIELD_REMOVED = 5;
30 var CLEAR_RECORDS = 8;
32 var IN_PROGRESS = 101;
35 /* Update requests from plugins */
37 var SET_REMOVED = 202;
40 var STATUS_NONE = 500; // Query has not been started yet
41 var STATUS_GET_IN_PROGRESS = 501; // Query has been sent, no result has been received
42 var STATUS_GET_RECEIVED = 502; // Success
43 var STATUS_GET_ERROR = 503; // Error
44 var STATUS_UPDATE_PENDING = 504;
45 var STATUS_UPDATE_IN_PROGRESS = 505;
46 var STATUS_UPDATE_RECEIVED = 506;
47 var STATUS_UPDATE_ERROR = 507;
50 // A structure for storing queries
54 function QueryExt(query, parent_query, main_query) {
57 if (typeof query == "undefined")
58 throw "Must pass a query in QueryExt constructor";
60 this.parent_query_ext = (typeof parent_query == "undefined") ? false : parent_query
61 this.main_query_ext = (typeof main_query == "undefined") ? false : main_query
65 this.update_query = null; // null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
68 function QueryStore() {
70 this.main_queries = {};
71 this.analyzed_queries = {};
75 this.insert = function(query)
77 if (query.analyzed_query == null) {
78 query.analyze_subqueries();
81 query_ext = new QueryExt(query, null, null)
82 manifold.query_store.main_queries[query.query_uuid] = query_ext;
84 // We also need to insert all queries and subqueries from the analyzed_query
85 // XXX We need the root of all subqueries
86 query.iter_subqueries(function(sq, data, parent_query) {
88 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
90 parent_query_ext = null;
91 // XXX parent_query_ext == false
92 // XXX main.subqueries = {} # Normal, we need analyzed_query
93 sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
94 manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
100 this.find_query_ext = function(query_uuid)
102 return this.main_queries[query_uuid];
105 this.find_query = function(query_uuid)
107 return this.find_query_ext(query_uuid).query;
110 this.find_analyzed_query_ext = function(query_uuid)
112 return this.analyzed_queries[query_uuid];
115 this.find_analyzed_query = function(query_uuid)
117 return this.find_analyzed_query_ext(query_uuid).query;
122 * This namespace holds functions for globally managing query objects
127 /**************************************************************************
129 **************************************************************************/
133 spin: function(locator, active /*= true */) {
134 active = typeof active !== 'undefined' ? active : true;
137 $(locator).spin(manifold.spin_presets);
139 $(locator).spin(false);
141 } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
144 /**************************************************************************
146 **************************************************************************/
148 query_store: new QueryStore(),
150 // XXX Remaining functions are deprecated since they are replaced by the query store
153 * Associative array storing the set of queries active on the page
159 * Insert a query in the global hash table associating uuids to queries.
160 * If the query has no been analyzed yet, let's do it.
161 * \fn insert_query(query)
163 * \param ManifoldQuery query Query to be added
165 insert_query : function (query) {
167 manifold.query_store.insert(query);
170 if (query.analyzed_query == null) {
171 query.analyze_subqueries();
173 manifold.all_queries[query.query_uuid]=query;
177 * Returns the query associated to a UUID
178 * \fn find_query(query_uuid)
180 * \param string query_uuid The UUID of the query to be returned
182 find_query : function (query_uuid) {
183 return manifold.all_queries[query_uuid];
186 /**************************************************************************
188 **************************************************************************/
190 // trigger a query asynchroneously
191 proxy_url : '/manifold/proxy/json/',
193 asynchroneous_debug : true,
196 * \brief We use js function closure to be able to pass the query (array)
197 * to the callback function used when data is received
199 success_closure: function(query, publish_uuid, callback /*domid*/)
201 return function(data, textStatus) {
202 manifold.asynchroneous_success(data, query, publish_uuid, callback /*domid*/);
206 // Executes all async. queries
207 // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
208 asynchroneous_exec : function (query_publish_dom_tuples) {
211 // in case the spin stuff was not loaded, let's make sure we proceed to the exit
213 // if (manifold.asynchroneous_debug)
214 // messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
215 // jQuery('.need-spin').spin(manifold.spin_presets);
216 //} catch (err) { messages.debug("Cannot turn on spins " + err); }
218 // Loop through input array, and use publish_uuid to publish back results
219 jQuery.each(query_publish_dom_tuples, function(index, tuple) {
220 var query=manifold.find_query(tuple.query_uuid);
221 var query_json=JSON.stringify (query);
222 var publish_uuid=tuple.publish_uuid;
223 // by default we publish using the same uuid of course
224 if (publish_uuid==undefined) publish_uuid=query.query_uuid;
225 if (manifold.asynchroneous_debug) {
226 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
227 messages.debug("... ctd... with actual query= " + query.__repr());
230 query.iter_subqueries(function (sq) {
231 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
234 // not quite sure what happens if we send a string directly, as POST data is named..
235 // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
236 jQuery.post(manifold.proxy_url, {'json':query_json} , manifold.success_closure(query, publish_uuid, tuple.callback /*domid*/));
241 * \brief Forward a query to the manifold backend
242 * \param query (dict) the query to be executed asynchronously
243 * \param callback (function) the function to be called when the query terminates
245 * \param domid (string) the domid to be notified about the results (null for using the pub/sub system
247 forward: function(query, callback /*domid*/) {
248 var query_json = JSON.stringify(query);
249 $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, query.query_uuid, callback/*domid*/));
253 * Returns whether a query expects a unique results.
254 * This is the case when the filters contain a key of the object
255 * \fn query_expects_unique_result(query)
257 * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
259 query_expects_unique_result: function(query) {
260 /* XXX we need functions to query metadata */
261 //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
262 /* TODO requires keys in metadata */
268 * \fn publish_result(query, results)
270 * \param ManifoldQuery query Query which has received results
271 * \param array results results corresponding to query
273 publish_result: function(query, result) {
274 if (typeof result === 'undefined')
278 manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
279 $.each(result, function(i, record) {
280 manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
282 manifold.raise_record_event(query.query_uuid, DONE);
284 // OLD PLUGIN API BELOW
285 /* Publish an update announce */
286 var channel="/results/" + query.query_uuid + "/changed";
287 if (manifold.asynchroneous_debug)
288 messages.debug("publishing result on " + channel);
289 jQuery.publish(channel, [result, query]);
293 * Recursively publish result
294 * \fn publish_result_rec(query, result)
296 * \param ManifoldQuery query Query which has received result
297 * \param array result result corresponding to query
299 publish_result_rec: function(query, result) {
300 /* If the result is not unique, only publish the top query;
301 * otherwise, publish the main object as well as subqueries
302 * XXX how much recursive are we ?
304 if (manifold.query_expects_unique_result(query)) {
305 /* Also publish subqueries */
306 jQuery.each(query.subqueries, function(object, subquery) {
307 manifold.publish_result_rec(subquery, result[0][object]);
308 /* TODO remove object from result */
311 manifold.publish_result(query, result);
314 // if set domid allows the result to be directed to just one plugin
315 // most of the time publish_uuid will be query.query_uuid
316 // however in some cases we wish to publish the result under a different uuid
317 // e.g. an updater wants to publish its result as if from the original (get) query
318 asynchroneous_success : function (data, query, publish_uuid, callback /*domid*/) {
319 // xxx should have a nicer declaration of that enum in sync with the python code somehow
321 /* If a callback has been specified, we redirect results to it */
322 if (!!callback) { callback(data); return; }
324 if (data.code == 2) { // ERROR
325 // We need to make sense of error codes here
326 alert("Your session has expired, please log in again");
327 window.location="/logout/";
330 if (data.code == 1) { // WARNING
331 messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
332 // publish error code and text message on a separate channel for whoever is interested
333 jQuery.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
335 $("#notifications").notify("create", "sticky", {
337 text: data.description
344 // once everything is checked we can use the 'value' part of the manifoldresult
345 var result=data.value;
347 //if (!!callback /* domid */) {
348 // /* Directly inform the requestor */
349 // if (manifold.asynchroneous_debug) messages.debug("directing result to callback");
351 // //if (manifold.asynchroneous_debug) messages.debug("directing result to " + domid);
352 // //jQuery('#' + domid).trigger('results', [result]);
354 /* XXX Jordan XXX I don't need publish_uuid here... What is it used for ? */
355 /* query is the query we sent to the backend; we need to find the
356 * corresponding analyezd_query in manifold.all_queries
358 tmp_query = manifold.find_query(query.query_uuid);
359 manifold.publish_result_rec(tmp_query.analyzed_query, result);
365 /**************************************************************************
367 **************************************************************************/
369 raise_event_handler: function(type, query_uuid, event_type, value)
371 if (type == 'query') {
372 var channels = [ manifold.get_query_channel(query_uuid), manifold.get_query_channel('*') ];
373 } else if (type == 'record') {
374 var channels = [ manifold.get_record_channel(query_uuid), manifold.get_record_channel('*') ];
377 throw 'Incorrect type for manifold.raise_event()';
379 $.each(channels, function(i, channel) {
380 if (value === undefined)
381 $('.plugin').trigger(channel, [event_type]);
383 $('.plugin').trigger(channel, [event_type, value]);
387 raise_query_event: function(query_uuid, event_type, value)
389 manifold.raise_event_handler('query', query_uuid, event_type, value);
392 raise_record_event: function(query_uuid, event_type, value)
394 manifold.raise_event_handler('record', query_uuid, event_type, value);
398 raise_event: function(query_uuid, event_type, value)
400 // Query uuid has been updated with the key of a new element
401 query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
402 query = query_ext.query;
406 // update is only possible is the query is not pending, etc
409 // XXX we can only update subqueries of the main query. Check !
410 // assert query_ext.parent_query == query_ext.main_query
411 update_query = query_ext.parent_query_ext.update_query;
413 // NOTE: update might modify the fields in Get
414 // NOTE : we have to modify all child queries
415 // NOTE : parts of a query might not be started (eg slice.measurements, how to handle ?)
417 // if everything is done right, update_query should not be null. It is updated when we received results from the get query
418 // object = the same as get
419 // filter = key : update a single object for now
420 // fields = the same as get
424 // Query uuid has been updated with the key of a removed element
431 main_query = query_ext.main_query_ext.query;
432 main_update_query = query_ext.main_query_ext.update_query;
435 // Here we need the full path through all subqueries
437 // XXX We might need the query name in the QueryExt structure
438 main_query.select(value);
440 // XXX When is an update query associated ?
441 // XXX main_update_query.select(value);
443 // We need to inform about changes in these queries to the respective plugins
444 // Note: query, main_query & update_query have the same UUID
445 manifold.raise_query_event(query_uuid, event_type, value);
446 // We are targeting the same object with get and update
447 // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
448 // NOTE: Editing a subquery == editing a local view on the destination
452 query = query_ext.query;
453 main_query = query_ext.main_query_ext.query;
454 main_update_query = query_ext.main_query_ext.update_query;
455 query.unselect(value);
456 main_query.unselect(value);
458 // We need to inform about changes in these queries to the respective plugins
459 // Note: query & main_query have the same UUID
460 manifold.raise_query_event(query_uuid, event_type, value);
463 // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
464 // For the time being, we will collect all columns during the first query
467 /* Publish/subscribe channels for internal use */
468 get_query_channel: function(uuid) { return '/query/' + uuid },
469 get_record_channel: function(uuid) { return '/record/' + uuid },
471 }; // manifold object
472 /* ------------------------------------------------------------ */
478 * NOTE: Since we don't have a plugin class, we are extending all jQuery
483 * \brief Associates a query handler to the current plugin
484 * \param uuid (string) query uuid
485 * \param handler (function) handler callback
487 $.fn.set_query_handler = function(uuid, handler)
489 this.on(manifold.get_query_channel(uuid), handler);
492 $.fn.set_record_handler = function(uuid, handler)
494 this.on(manifold.get_record_channel(uuid), handler);
497 // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
498 // https://gist.github.com/661855
500 $.subscribe = function( channel, selector, data, fn) {
501 /* borrowed from jQuery */
502 if ( data == null && fn == null ) {
505 data = selector = undefined;
506 } else if ( fn == null ) {
507 if ( typeof selector === "string" ) {
508 // ( channel, selector, fn )
512 // ( channel, data, fn )
515 selector = undefined;
520 /* We use an indirection function that will clone the object passed in
521 * parameter to the subscribe callback
523 * FIXME currently we only clone query objects which are the only ones
524 * supported and editable, we might have the same issue with results but
525 * the page load time will be severely affected...
527 o.on.apply(o, [channel, selector, data, function() {
528 for(i = 1; i < arguments.length; i++) {
529 if ( arguments[i].constructor.name == 'ManifoldQuery' )
530 arguments[i] = arguments[i].clone();
532 fn.apply(o, arguments);
536 $.unsubscribe = function() {
537 o.off.apply(o, arguments);
540 $.publish = function() {
541 o.trigger.apply(o, arguments);
546 /* ------------------------------------------------------------ */
548 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
549 //make sure to expose csrf in our outcoming ajax/post requests
551 beforeSend: function(xhr, settings) {
552 function getCookie(name) {
553 var cookieValue = null;
554 if (document.cookie && document.cookie != '') {
555 var cookies = document.cookie.split(';');
556 for (var i = 0; i < cookies.length; i++) {
557 var cookie = jQuery.trim(cookies[i]);
558 // Does this cookie string begin with the name we want?
559 if (cookie.substring(0, name.length + 1) == (name + '=')) {
560 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
567 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
568 // Only send the token to relative URLs i.e. locally.
569 xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));