[IMP] allows to specify a specific eval domain in /web/action/load
[odoo/odoo.git] / addons / web / static / src / js / views.js
1 /*---------------------------------------------------------
2  * OpenERP web library
3  *---------------------------------------------------------*/
4
5 openerp.web.views = function(instance) {
6 var QWeb = instance.web.qweb,
7     _t = instance.web._t;
8
9 instance.web.ActionManager = instance.web.Widget.extend({
10     init: function(parent) {
11         this._super(parent);
12         this.inner_action = null;
13         this.inner_widget = null;
14         this.dialog = null;
15         this.dialog_widget = null;
16         this.breadcrumbs = [];
17         this.on('history_back', this, function() {
18             return this.history_back();
19         });
20     },
21     start: function() {
22         this._super.apply(this, arguments);
23         this.$el.on('click', 'a.oe_breadcrumb_item', this.on_breadcrumb_clicked);
24     },
25     dialog_stop: function () {
26         if (this.dialog) {
27             this.dialog.destroy();
28         }
29         this.dialog = null;
30     },
31     /**
32      * Add a new item to the breadcrumb
33      *
34      * If the title of an item is an array, the multiple title mode is in use.
35      * (eg: a widget with multiple views might need to display a title for each view)
36      * In multiple title mode, the show() callback can check the index it receives
37      * in order to detect which of its titles has been clicked on by the user.
38      *
39      * @param {Object} item breadcrumb item
40      * @param {Object} item.widget widget containing the view(s) to be added to the breadcrumb added
41      * @param {Function} [item.show] triggered whenever the widget should be shown back
42      * @param {Function} [item.hide] triggered whenever the widget should be shown hidden
43      * @param {Function} [item.destroy] triggered whenever the widget should be destroyed
44      * @param {String|Array} [item.title] title(s) of the view(s) to be displayed in the breadcrumb
45      * @param {Function} [item.get_title] should return the title(s) of the view(s) to be displayed in the breadcrumb
46      */
47     push_breadcrumb: function(item) {
48         var last = this.breadcrumbs.slice(-1)[0];
49         if (last) {
50             last.hide();
51         }
52         var item = _.extend({
53             show: function(index) {
54                 this.widget.$el.show();
55             },
56             hide: function() {
57                 this.widget.$el.hide();
58             },
59             destroy: function() {
60                 this.widget.destroy();
61             },
62             get_title: function() {
63                 return this.title || this.widget.get('title');
64             }
65         }, item);
66         item.id = _.uniqueId('breadcrumb_');
67         this.breadcrumbs.push(item);
68     },
69     history_back: function() {
70         var last = this.breadcrumbs.slice(-1)[0];
71         if (!last) {
72             return false;
73         }
74         var title = last.get_title();
75         if (_.isArray(title) && title.length > 1) {
76             return this.select_breadcrumb(this.breadcrumbs.length - 1, title.length - 2);
77         } else if (this.breadcrumbs.length === 1) {
78             // Only one single titled item in breadcrumb, most of the time you want to trigger back to home
79             return false;
80         } else {
81             var prev = this.breadcrumbs[this.breadcrumbs.length - 2];
82             title = prev.get_title();
83             return this.select_breadcrumb(this.breadcrumbs.length - 2, _.isArray(title) ? title.length - 1 : undefined);
84         }
85     },
86     on_breadcrumb_clicked: function(ev) {
87         var $e = $(ev.target);
88         var id = $e.data('id');
89         var index;
90         for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
91             if (this.breadcrumbs[i].id == id) {
92                 index = i;
93                 break;
94             }
95         }
96         var subindex = $e.parent().find('a.oe_breadcrumb_item[data-id=' + $e.data('id') + ']').index($e);
97         this.select_breadcrumb(index, subindex);
98     },
99     select_breadcrumb: function(index, subindex) {
100         var next_item = this.breadcrumbs[index + 1];
101         if (next_item && next_item.on_reverse_breadcrumb) {
102             next_item.on_reverse_breadcrumb(this.breadcrumbs[index].widget);
103         }
104         for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
105             if (i > index) {
106                 if (this.remove_breadcrumb(i) === false) {
107                     return false;
108                 }
109             }
110         }
111         var item = this.breadcrumbs[index];
112         item.show(subindex);
113         this.inner_widget = item.widget;
114         this.inner_action = item.action;
115         return true;
116     },
117     clear_breadcrumbs: function() {
118         for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
119             if (this.remove_breadcrumb(0) === false) {
120                 break;
121             }
122         }
123     },
124     remove_breadcrumb: function(index) {
125         var item = this.breadcrumbs.splice(index, 1)[0];
126         if (item) {
127             var dups = _.filter(this.breadcrumbs, function(it) {
128                 return item.widget === it.widget;
129             });
130             if (!dups.length) {
131                 if (this.getParent().has_uncommitted_changes()) {
132                     this.inner_widget = item.widget;
133                     this.inner_action = item.action;
134                     this.breadcrumbs.splice(index, 0, item);
135                     return false;
136                 } else {
137                     item.destroy();
138                 }
139             }
140         }
141         var last_widget = this.breadcrumbs.slice(-1)[0];
142         if (last_widget) {
143             this.inner_widget = last_widget.widget;
144             this.inner_action = last_widget.action;
145         }
146     },
147     get_title: function() {
148         var titles = [];
149         for (var i = 0; i < this.breadcrumbs.length; i += 1) {
150             var item = this.breadcrumbs[i];
151             var tit = item.get_title();
152             if (!_.isArray(tit)) {
153                 tit = [tit];
154             }
155             for (var j = 0; j < tit.length; j += 1) {
156                 var label = _.escape(tit[j]);
157                 if (i === this.breadcrumbs.length - 1 && j === tit.length - 1) {
158                     titles.push(_.str.sprintf('<span class="oe_breadcrumb_item">%s</span>', label));
159                 } else {
160                     titles.push(_.str.sprintf('<a href="#" class="oe_breadcrumb_item" data-id="%s">%s</a>', item.id, label));
161                 }
162             }
163         }
164         return titles.join(' <span class="oe_fade">/</span> ');
165     },
166     do_push_state: function(state) {
167         state = state || {};
168         if (this.getParent() && this.getParent().do_push_state) {
169             if (this.inner_action) {
170                 if (this.inner_action._push_me === false) {
171                     // this action has been explicitly marked as not pushable
172                     return;
173                 }
174                 state['title'] = this.inner_action.name;
175                 if(this.inner_action.type == 'ir.actions.act_window') {
176                     state['model'] = this.inner_action.res_model;
177                 }
178                 if (this.inner_action.menu_id) {
179                     state['menu_id'] = this.inner_action.menu_id;
180                 }
181                 if (this.inner_action.id) {
182                     state['action'] = this.inner_action.id;
183                 } else if (this.inner_action.type == 'ir.actions.client') {
184                     state['action'] = this.inner_action.tag;
185                     var params = {};
186                     _.each(this.inner_action.params, function(v, k) {
187                         if(_.isString(v) || _.isNumber(v)) {
188                             params[k] = v;
189                         }
190                     });
191                     state = _.extend(params || {}, state);
192                 }
193             }
194             if(!this.dialog) {
195                 this.getParent().do_push_state(state);
196             }
197         }
198     },
199     do_load_state: function(state, warm) {
200         var self = this,
201             action_loaded;
202         if (state.action) {
203             if (_.isString(state.action) && instance.web.client_actions.contains(state.action)) {
204                 var action_client = {
205                     type: "ir.actions.client",
206                     tag: state.action,
207                     params: state,
208                     _push_me: state._push_me,
209                 };
210                 this.null_action();
211                 action_loaded = this.do_action(action_client);
212             } else {
213                 var run_action = (!this.inner_widget || !this.inner_widget.action) || this.inner_widget.action.id !== state.action;
214                 if (run_action) {
215                     this.null_action();
216                     action_loaded = this.do_action(state.action);
217                     $.when(action_loaded || null).done(function() {
218                         instance.webclient.menu.has_been_loaded.done(function() {
219                             if (self.inner_action && self.inner_action.id) {
220                                 instance.webclient.menu.open_action(self.inner_action.id);
221                             }
222                         });
223                     });
224                 }
225             }
226         } else if (state.model && state.id) {
227             // TODO handle context & domain ?
228             this.null_action();
229             var action = {
230                 res_model: state.model,
231                 res_id: state.id,
232                 type: 'ir.actions.act_window',
233                 views: [[false, 'form']]
234             };
235             action_loaded = this.do_action(action);
236         } else if (state.sa) {
237             // load session action
238             this.null_action();
239             action_loaded = this.rpc('/web/session/get_session_action',  {key: state.sa}).then(function(action) {
240                 if (action) {
241                     return self.do_action(action);
242                 }
243             });
244         }
245
246         $.when(action_loaded || null).done(function() {
247             if (self.inner_widget && self.inner_widget.do_load_state) {
248                 self.inner_widget.do_load_state(state, warm);
249             }
250         });
251     },
252     do_action: function(action, options) {
253         options = _.defaults(options || {}, {
254             clear_breadcrumbs: false,
255             on_reverse_breadcrumb: function() {},
256             on_close: function() {},
257             action_menu_id: null,
258         });
259         if (_.isString(action) && instance.web.client_actions.contains(action)) {
260             var action_client = { type: "ir.actions.client", tag: action, params: {} };
261             return this.do_action(action_client, options);
262         } else if (_.isNumber(action) || _.isString(action)) {
263             var self = this;
264             return self.rpc("/web/action/load", { action_id: action }).then(function(result) {
265                 return self.do_action(result, options);
266             });
267         }
268         if (!action.type) {
269             console.error("No type for action", action);
270             return $.Deferred().reject();
271         }
272         var type = action.type.replace(/\./g,'_');
273         var popup = action.target === 'new';
274         var inline = action.target === 'inline' || action.target === 'inlineview';
275         action.flags = _.extend({
276             views_switcher : !popup && !inline,
277             search_view : !popup && !inline,
278             action_buttons : !popup && !inline,
279             sidebar : !popup && !inline,
280             pager : !popup && !inline,
281             display_title : !popup
282         }, action.flags || {});
283         action.menu_id = options.action_menu_id;
284         if (!(type in this)) {
285             console.error("Action manager can't handle action of type " + action.type, action);
286             return $.Deferred().reject();
287         }
288         return this[type](action, options);
289     },
290     null_action: function() {
291         this.dialog_stop();
292         this.clear_breadcrumbs();
293     },
294     /**
295      *
296      * @param {Object} executor
297      * @param {Object} executor.action original action
298      * @param {Function<instance.web.Widget>} executor.widget function used to fetch the widget instance
299      * @param {String} executor.klass CSS class to add on the dialog root, if action.target=new
300      * @param {Function<instance.web.Widget, undefined>} executor.post_process cleanup called after a widget has been added as inner_widget
301      * @param {Object} options
302      * @return {*}
303      */
304     ir_actions_common: function(executor, options) {
305         if (this.inner_widget && executor.action.target !== 'new') {
306             if (this.getParent().has_uncommitted_changes()) {
307                 return $.Deferred().reject();
308             } else if (options.clear_breadcrumbs) {
309                 this.clear_breadcrumbs();
310             }
311         }
312         var widget = executor.widget();
313         if (executor.action.target === 'new') {
314             if (this.dialog_widget && !this.dialog_widget.isDestroyed()) {
315                 this.dialog_widget.destroy();
316             }
317             this.dialog_stop();
318             this.dialog = new instance.web.Dialog(this, {
319                 dialogClass: executor.klass,
320             });
321             this.dialog.on("closing", null, options.on_close);
322             this.dialog.init_dialog();
323             this.dialog.dialog_title = executor.action.name;
324             if (widget instanceof instance.web.ViewManager) {
325                 _.extend(widget.flags, {
326                     $buttons: this.dialog.$buttons,
327                     footer_to_buttons: true,
328                 });
329             }
330             this.dialog_widget = widget;
331             this.dialog_widget.setParent(this.dialog);
332             var initialized = this.dialog_widget.appendTo(this.dialog.$el);
333             this.dialog.open();
334             return initialized;
335         } else  {
336             this.dialog_stop();
337             this.inner_action = executor.action;
338             this.inner_widget = widget;
339             executor.post_process(widget);
340             return this.inner_widget.appendTo(this.$el);
341         }
342     },
343     ir_actions_act_window: function (action, options) {
344         var self = this;
345
346         return this.ir_actions_common({
347             widget: function () { return new instance.web.ViewManagerAction(self, action); },
348             action: action,
349             klass: 'oe_act_window',
350             post_process: function (widget) { widget.add_breadcrumb(options.on_reverse_breadcrumb); }
351         }, options);
352     },
353     ir_actions_client: function (action, options) {
354         var self = this;
355         var ClientWidget = instance.web.client_actions.get_object(action.tag);
356
357         if (!(ClientWidget.prototype instanceof instance.web.Widget)) {
358             var next;
359             if (next = ClientWidget(this, action)) {
360                 return this.do_action(next, options);
361             }
362             return $.when();
363         }
364
365         return this.ir_actions_common({
366             widget: function () { return new ClientWidget(self, action); },
367             action: action,
368             klass: 'oe_act_client',
369             post_process: function(widget) {
370                 self.push_breadcrumb({
371                     widget: widget,
372                     title: action.name,
373                     on_reverse_breadcrumb: options.on_reverse_breadcrumb,
374                 });
375                 if (action.tag !== 'reload') {
376                     self.do_push_state({});
377                 }
378             }
379         }, options);
380     },
381     ir_actions_act_window_close: function (action, options) {
382         if (!this.dialog) {
383             options.on_close();
384         }
385         this.dialog_stop();
386     },
387     ir_actions_server: function (action, options) {
388         var self = this;
389         this.rpc('/web/action/run', {
390             action_id: action.id,
391             context: action.context || {}
392         }).done(function (action) {
393             self.do_action(action, options)
394         });
395     },
396     ir_actions_report_xml: function(action, options) {
397         var self = this;
398         instance.web.blockUI();
399         self.rpc("/web/session/eval_domain_and_context", {
400             contexts: [action.context],
401             domains: []
402         }).done(function(res) {
403             action = _.clone(action);
404             action.context = res.context;
405             var c = instance.webclient.crashmanager;
406             self.session.get_file({
407                 url: '/web/report',
408                 data: {action: JSON.stringify(action)},
409                 complete: instance.web.unblockUI,
410                 success: function(){
411                     if (!self.dialog) {
412                         options.on_close();
413                     }
414                     self.dialog_stop();
415                 },
416                 error: c.rpc_error.bind(c)
417             })
418         });
419     },
420     ir_actions_act_url: function (action) {
421         window.open(action.url, action.target === 'self' ? '_self' : '_blank');
422     },
423 });
424
425 instance.web.ViewManager =  instance.web.Widget.extend({
426     template: "ViewManager",
427     init: function(parent, dataset, views, flags) {
428         this._super(parent);
429         this.url_states = {};
430         this.model = dataset ? dataset.model : undefined;
431         this.dataset = dataset;
432         this.searchview = null;
433         this.active_view = null;
434         this.views_src = _.map(views, function(x) {
435             if (x instanceof Array) {
436                 var View = instance.web.views.get_object(x[1], true);
437                 return {
438                     view_id: x[0],
439                     view_type: x[1],
440                     label: View ? View.prototype.display_name : (void 'nope')
441                 };
442             } else {
443                 return x;
444             }
445         });
446         this.views = {};
447         this.flags = flags || {};
448         this.registry = instance.web.views;
449         this.views_history = [];
450     },
451     /**
452      * @returns {jQuery.Deferred} initial view loading promise
453      */
454     start: function() {
455         this._super();
456         var self = this;
457         this.$el.find('.oe_view_manager_switch a').click(function() {
458             self.switch_mode($(this).data('view-type'));
459         }).tipsy();
460         var views_ids = {};
461         _.each(this.views_src, function(view) {
462             self.views[view.view_type] = $.extend({}, view, {
463                 deferred : $.Deferred(),
464                 controller : null,
465                 options : _.extend({
466                     $buttons : self.$el.find('.oe_view_manager_buttons'),
467                     $sidebar : self.flags.sidebar ? self.$el.find('.oe_view_manager_sidebar') : undefined,
468                     $pager : self.$el.find('.oe_view_manager_pager'),
469                     action : self.action,
470                     action_views_ids : views_ids
471                 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
472             });
473             views_ids[view.view_type] = view.view_id;
474         });
475         if (this.flags.views_switcher === false) {
476             this.$el.find('.oe_view_manager_switch').hide();
477         }
478         // If no default view defined, switch to the first one in sequence
479         var default_view = this.flags.default_view || this.views_src[0].view_type;
480         return this.switch_mode(default_view);
481     },
482     switch_mode: function(view_type, no_store, view_options) {
483         var self = this;
484         var view = this.views[view_type];
485         var view_promise;
486         var form = this.views['form'];
487         if (!view || (form && form.controller && !form.controller.can_be_discarded())) {
488             self.trigger('switch_mode', view_type, no_store, view_options);
489             return $.Deferred().reject();
490         }
491         if (!no_store) {
492             this.views_history.push(view_type);
493         }
494         this.active_view = view_type;
495
496         if (!view.controller) {
497             view_promise = this.do_create_view(view_type);
498         } else if (this.searchview
499                 && self.flags.auto_search
500                 && view.controller.searchable !== false) {
501             this.searchview.ready.done(this.searchview.do_search);
502         }
503
504         if (this.searchview) {
505             this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
506         }
507
508         this.$el.find('.oe_view_manager_switch a').parent().removeClass('active');
509         this.$el
510             .find('.oe_view_manager_switch a').filter('[data-view-type="' + view_type + '"]')
511             .parent().addClass('active');
512
513         return $.when(view_promise).done(function () {
514             _.each(_.keys(self.views), function(view_name) {
515                 var controller = self.views[view_name].controller;
516                 if (controller) {
517                     var container = self.$el.find(".oe_view_manager_view_" + view_name + ":first");
518                     if (view_name === view_type) {
519                         container.show();
520                         controller.do_show(view_options || {});
521                     } else {
522                         container.hide();
523                         controller.do_hide();
524                     }
525                 }
526             });
527             self.trigger('switch_mode', view_type, no_store, view_options);
528         });
529     },
530     do_create_view: function(view_type) {
531         // Lazy loading of views
532         var self = this;
533         var view = this.views[view_type];
534         var viewclass = this.registry.get_object(view_type);
535         var options = _.clone(view.options);
536         if (view_type === "form" && this.action && (this.action.target == 'new' || this.action.target == 'inline')) {
537             options.initial_mode = 'edit';
538         }
539         var controller = new viewclass(this, this.dataset, view.view_id, options);
540
541         controller.on('history_back', this, function() {
542             var am = self.getParent();
543             if (am && am.trigger) {
544                 return am.trigger('history_back');
545             }
546         });
547
548         controller.on("change:title", this, function() {
549             if (self.active_view === view_type) {
550                 self.set_title(controller.get('title'));
551             }
552         });
553
554         if (view.embedded_view) {
555             controller.set_embedded_view(view.embedded_view);
556         }
557         controller.on('switch_mode', self, this.switch_mode);
558         controller.on('previous_view', self, this.prev_view);
559         
560         var container = this.$el.find(".oe_view_manager_view_" + view_type);
561         var view_promise = controller.appendTo(container);
562         this.views[view_type].controller = controller;
563         this.views[view_type].deferred.resolve(view_type);
564         return $.when(view_promise).done(function() {
565             if (self.searchview
566                     && self.flags.auto_search
567                     && view.controller.searchable !== false) {
568                 self.searchview.ready.done(self.searchview.do_search);
569             }
570             self.trigger("controller_inited",view_type,controller);
571         });
572     },
573     set_title: function(title) {
574         this.$el.find('.oe_view_title_text:first').text(title);
575     },
576     add_breadcrumb: function(on_reverse_breadcrumb) {
577         var self = this;
578         var views = [this.active_view || this.views_src[0].view_type];
579         this.on('switch_mode', self, function(mode) {
580             var last = views.slice(-1)[0];
581             if (mode !== last) {
582                 if (mode !== 'form') {
583                     views.length = 0;
584                 }
585                 views.push(mode);
586             }
587         });
588         this.getParent().push_breadcrumb({
589             widget: this,
590             action: this.action,
591             show: function(index) {
592                 var view_to_select = views[index];
593                 var state = self.url_states[view_to_select];
594                 self.do_push_state(state || {});
595                 $.when(self.switch_mode(view_to_select)).done(function() {
596                     self.$el.show();
597                 });
598             },
599             get_title: function() {
600                 var id;
601                 var currentIndex;
602                 _.each(self.getParent().breadcrumbs, function(bc, i) {
603                     if (bc.widget === self) {
604                         currentIndex = i;
605                     }
606                 });
607                 var next = self.getParent().breadcrumbs.slice(currentIndex + 1)[0];
608                 var titles = _.map(views, function(v) {
609                     var controller = self.views[v].controller;
610                     if (v === 'form') {
611                         id = controller.datarecord.id;
612                     }
613                     return controller.get('title');
614                 });
615                 if (next && next.action && next.action.res_id && self.dataset &&
616                     self.active_view === 'form' && self.dataset.model === next.action.res_model && id === next.action.res_id) {
617                     // If the current active view is a formview and the next item in the breadcrumbs
618                     // is an action on same object (model / res_id), then we omit the current formview's title
619                     titles.pop();
620                 }
621                 return titles;
622             },
623             on_reverse_breadcrumb: on_reverse_breadcrumb,
624         });
625     },
626     /**
627      * Returns to the view preceding the caller view in this manager's
628      * navigation history (the navigation history is appended to via
629      * switch_mode)
630      *
631      * @param {Object} [options]
632      * @param {Boolean} [options.created=false] resource was created
633      * @param {String} [options.default=null] view to switch to if no previous view
634      * @returns {$.Deferred} switching end signal
635      */
636     prev_view: function (options) {
637         options = options || {};
638         var current_view = this.views_history.pop();
639         var previous_view = this.views_history[this.views_history.length - 1] || options['default'];
640         if (options.created && current_view === 'form' && previous_view === 'list') {
641             // APR special case: "If creation mode from list (and only from a list),
642             // after saving, go to page view (don't come back in list)"
643             return this.switch_mode('form');
644         } else if (options.created && !previous_view && this.action && this.action.flags.default_view === 'form') {
645             // APR special case: "If creation from dashboard, we have no previous view
646             return this.switch_mode('form');
647         }
648         return this.switch_mode(previous_view, true);
649     },
650     /**
651      * Sets up the current viewmanager's search view.
652      *
653      * @param {Number|false} view_id the view to use or false for a default one
654      * @returns {jQuery.Deferred} search view startup deferred
655      */
656     setup_search_view: function(view_id, search_defaults) {
657         var self = this;
658         if (this.searchview) {
659             this.searchview.destroy();
660         }
661         this.searchview = new instance.web.SearchView(this, this.dataset, view_id, search_defaults, this.flags.search_view === false);
662
663         this.searchview.on('search_data', self, this.do_searchview_search);
664         return this.searchview.appendTo(this.$el.find(".oe_view_manager_view_search"));
665     },
666     do_searchview_search: function(domains, contexts, groupbys) {
667         var self = this,
668             controller = this.views[this.active_view].controller,
669             action_context = this.action.context || {};
670         this.rpc('/web/session/eval_domain_and_context', {
671             domains: [this.action.domain || []].concat(domains || []),
672             contexts: [action_context].concat(contexts || []),
673             group_by_seq: groupbys || []
674         }).done(function (results) {
675             self.dataset._model = new instance.web.Model(
676                 self.dataset.model, results.context, results.domain);
677             var groupby = results.group_by.length
678                         ? results.group_by
679                         : action_context.group_by;
680             if (_.isString(groupby)) {
681                 groupby = [groupby];
682             }
683             controller.do_search(results.domain, results.context, groupby || []);
684         });
685     },
686     /**
687      * Called when one of the view want to execute an action
688      */
689     on_action: function(action) {
690     },
691     on_create: function() {
692     },
693     on_remove: function() {
694     },
695     on_edit: function() {
696     },
697     /**
698      * Called by children view after executing an action
699      */
700     on_action_executed: function () {
701     },
702 });
703
704 instance.web.ViewManagerAction = instance.web.ViewManager.extend({
705     template:"ViewManagerAction",
706     /**
707      * @constructs instance.web.ViewManagerAction
708      * @extends instance.web.ViewManager
709      *
710      * @param {instance.web.ActionManager} parent parent object/widget
711      * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
712      */
713     init: function(parent, action) {
714         // dataset initialization will take the session from ``this``, so if we
715         // do not have it yet (and we don't, because we've not called our own
716         // ``_super()``) rpc requests will blow up.
717         var flags = action.flags || {};
718         if (!('auto_search' in flags)) {
719             flags.auto_search = action.auto_search !== false;
720         }
721         if (action.res_model == 'board.board' && action.view_mode === 'form') {
722             // Special case for Dashboards
723             _.extend(flags, {
724                 views_switcher : false,
725                 display_title : false,
726                 search_view : false,
727                 pager : false,
728                 sidebar : false,
729                 action_buttons : false
730             });
731         }
732         this._super(parent, null, action.views, flags);
733         this.session = parent.session;
734         this.action = action;
735         var dataset = new instance.web.DataSetSearch(this, action.res_model, action.context, action.domain);
736         if (action.res_id) {
737             dataset.ids.push(action.res_id);
738             dataset.index = 0;
739         }
740         this.dataset = dataset;
741
742         // setup storage for session-wise menu hiding
743         if (this.session.hidden_menutips) {
744             return;
745         }
746         this.session.hidden_menutips = {};
747     },
748     /**
749      * Initializes the ViewManagerAction: sets up the searchview (if the
750      * searchview is enabled in the manager's action flags), calls into the
751      * parent to initialize the primary view and (if the VMA has a searchview)
752      * launches an initial search after both views are done rendering.
753      */
754     start: function() {
755         var self = this,
756             searchview_loaded,
757             search_defaults = {};
758         _.each(this.action.context, function (value, key) {
759             var match = /^search_default_(.*)$/.exec(key);
760             if (match) {
761                 search_defaults[match[1]] = value;
762             }
763         });
764         // init search view
765         var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
766
767         searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
768
769         var main_view_loaded = this._super();
770
771         var manager_ready = $.when(searchview_loaded, main_view_loaded);
772
773         this.$el.find('.oe_debug_view').change(this.on_debug_changed);
774         this.$el.addClass("oe_view_manager_" + (this.action.target || 'current'));
775         return manager_ready;
776     },
777     on_debug_changed: function (evt) {
778         var self = this,
779             $sel = $(evt.currentTarget),
780             $option = $sel.find('option:selected'),
781             val = $sel.val(),
782             current_view = this.views[this.active_view].controller;
783         switch (val) {
784             case 'fvg':
785                 var dialog = new instance.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
786                 $('<pre>').text(instance.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$el);
787                 break;
788             case 'tests':
789                 this.do_action({
790                     name: "JS Tests",
791                     target: 'new',
792                     type : 'ir.actions.act_url',
793                     url: '/web/tests?mod=*'
794                 });
795                 break;
796             case 'perm_read':
797                 var ids = current_view.get_selected_ids();
798                 if (ids.length === 1) {
799                     this.dataset.call('perm_read', [ids]).done(function(result) {
800                         var dialog = new instance.web.Dialog(this, {
801                             title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
802                             width: 400
803                         }, QWeb.render('ViewManagerDebugViewLog', {
804                             perm : result[0],
805                             format : instance.web.format_value
806                         })).open();
807                     });
808                 }
809                 break;
810             case 'toggle_layout_outline':
811                 current_view.rendering_engine.toggle_layout_debugging();
812                 break;
813             case 'translate':
814                 this.do_action({
815                     name: "Technical Translation",
816                     res_model : 'ir.translation',
817                     domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
818                     views: [[false, 'list'], [false, 'form']],
819                     type : 'ir.actions.act_window',
820                     view_type : "list",
821                     view_mode : "list"
822                 });
823                 break;
824             case 'fields':
825                 this.dataset.call('fields_get', [false, {}]).done(function (fields) {
826                     var $root = $('<dl>');
827                     _(fields).each(function (attributes, name) {
828                         $root.append($('<dt>').append($('<h4>').text(name)));
829                         var $attrs = $('<dl>').appendTo($('<dd>').appendTo($root));
830                         _(attributes).each(function (def, name) {
831                             if (def instanceof Object) {
832                                 def = JSON.stringify(def);
833                             }
834                             $attrs
835                                 .append($('<dt>').text(name))
836                                 .append($('<dd style="white-space: pre-wrap;">').text(def));
837                         });
838                     });
839                     new instance.web.Dialog(self, {
840                         title: _.str.sprintf(_t("Model %s fields"),
841                                              self.dataset.model),
842                         width: '95%'}, $root).open();
843                 });
844                 break;
845             case 'edit_workflow':
846                 return this.do_action({
847                     res_model : 'workflow',
848                     domain : [['osv', '=', this.dataset.model]],
849                     views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
850                     type : 'ir.actions.act_window',
851                     view_type : 'list',
852                     view_mode : 'list'
853                 });
854                 break;
855             case 'edit':
856                 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
857                 break;
858             case 'manage_filters':
859                 this.do_action({
860                     res_model: 'ir.filters',
861                     views: [[false, 'list'], [false, 'form']],
862                     type: 'ir.actions.act_window',
863                     context: {
864                         search_default_my_filters: true,
865                         search_default_model_id: this.dataset.model
866                     }
867                 });
868                 break;
869             case 'print_workflow':
870                 if (current_view.get_selected_ids  && current_view.get_selected_ids().length == 1) {
871                     instance.web.blockUI();
872                     var action = {
873                         context: { active_ids: current_view.get_selected_ids() },
874                         report_name: "workflow.instance.graph",
875                         datas: {
876                             model: this.dataset.model,
877                             id: current_view.get_selected_ids()[0],
878                             nested: true,
879                         }
880                     };
881                     this.session.get_file({ url: '/web/report', data: {action: JSON.stringify(action)}, complete: instance.web.unblockUI });
882                 }
883                 break;
884             default:
885                 if (val) {
886                     console.log("No debug handler for ", val);
887                 }
888         }
889         evt.currentTarget.selectedIndex = 0;
890     },
891     do_edit_resource: function(model, id, action) {
892         var action = _.extend({
893             res_model : model,
894             res_id : id,
895             type : 'ir.actions.act_window',
896             view_type : 'form',
897             view_mode : 'form',
898             views : [[false, 'form']],
899             target : 'new',
900             flags : {
901                 action_buttons : true,
902                 form : {
903                     resize_textareas : true
904                 }
905             }
906         }, action || {});
907         this.do_action(action);
908     },
909     switch_mode: function (view_type, no_store, options) {
910         var self = this;
911
912         return $.when(this._super.apply(this, arguments)).done(function () {
913             var controller = self.views[self.active_view].controller;
914             self.$el.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
915                 view: controller,
916                 view_manager: self
917             }));
918             self.set_title();
919         });
920     },
921     do_create_view: function(view_type) {
922         var r = this._super.apply(this, arguments);
923         var view = this.views[view_type].controller;
924         view.set({ 'title': this.action.name });
925         return r;
926     },
927     get_action_manager: function() {
928         var cur = this;
929         while (cur = cur.getParent()) {
930             if (cur instanceof instance.web.ActionManager) {
931                 return cur;
932             }
933         }
934         return undefined;
935     },
936     set_title: function(title) {
937         this.$el.find('.oe_breadcrumb_title:first').html(this.get_action_manager().get_title());
938     },
939     do_push_state: function(state) {
940         if (this.getParent() && this.getParent().do_push_state) {
941             state["view_type"] = this.active_view;
942             this.url_states[this.active_view] = state;
943             this.getParent().do_push_state(state);
944         }
945     },
946     do_load_state: function(state, warm) {
947         var self = this,
948             defs = [];
949         if (state.view_type && state.view_type !== this.active_view) {
950             defs.push(
951                 this.views[this.active_view].deferred.then(function() {
952                     return self.switch_mode(state.view_type, true);
953                 })
954             );
955         } 
956
957         $.when(defs).done(function() {
958             self.views[self.active_view].controller.do_load_state(state, warm);
959         });
960     },
961 });
962
963 instance.web.Sidebar = instance.web.Widget.extend({
964     init: function(parent) {
965         var self = this;
966         this._super(parent);
967         var view = this.getParent();
968         this.sections = [
969             { 'name' : 'print', 'label' : _t('Print'), },
970             { 'name' : 'other', 'label' : _t('More'), }
971         ];
972         this.items = {
973             'print' : [],
974             'other' : []
975         };
976         this.fileupload_id = _.uniqueId('oe_fileupload');
977         $(window).on(this.fileupload_id, function() {
978             var args = [].slice.call(arguments).slice(1);
979             if (args[0] && args[0].error) {
980                 alert(args[0].error);
981             } else {
982                 self.do_attachement_update(self.dataset, self.model_id);
983             }
984             instance.web.unblockUI();
985         });
986     },
987     start: function() {
988         var self = this;
989         this._super(this);
990         this.redraw();
991         this.$el.on('click','.oe_dropdown_menu li a', function(event) {
992             var section = $(this).data('section');
993             var index = $(this).data('index');
994             var item = self.items[section][index];
995             if (item.callback) {
996                 item.callback.apply(self, [item]);
997             } else if (item.action) {
998                 self.on_item_action_clicked(item);
999             } else if (item.url) {
1000                 return true;
1001             }
1002             event.preventDefault();
1003         });
1004     },
1005     redraw: function() {
1006         var self = this;
1007         self.$el.html(QWeb.render('Sidebar', {widget: self}));
1008
1009         // Hides Sidebar sections when item list is empty
1010         this.$('.oe_form_dropdown_section').each(function() {
1011             $(this).toggle(!!$(this).find('li').length);
1012         });
1013     },
1014     /**
1015      * For each item added to the section:
1016      *
1017      * ``label``
1018      *     will be used as the item's name in the sidebar, can be html
1019      *
1020      * ``action``
1021      *     descriptor for the action which will be executed, ``action`` and
1022      *     ``callback`` should be exclusive
1023      *
1024      * ``callback``
1025      *     function to call when the item is clicked in the sidebar, called
1026      *     with the item descriptor as its first argument (so information
1027      *     can be stored as additional keys on the object passed to
1028      *     ``add_items``)
1029      *
1030      * ``classname`` (optional)
1031      *     ``@class`` set on the sidebar serialization of the item
1032      *
1033      * ``title`` (optional)
1034      *     will be set as the item's ``@title`` (tooltip)
1035      *
1036      * @param {String} section_code
1037      * @param {Array<{label, action | callback[, classname][, title]}>} items
1038      */
1039     add_items: function(section_code, items) {
1040         var self = this;
1041         if (items) {
1042             this.items[section_code].push.apply(this.items[section_code],items);
1043             this.redraw();
1044         }
1045     },
1046     add_toolbar: function(toolbar) {
1047         var self = this;
1048         _.each(['print','action','relate'], function(type) {
1049             var items = toolbar[type];
1050             if (items) {
1051                 for (var i = 0; i < items.length; i++) {
1052                     items[i] = {
1053                         label: items[i]['name'],
1054                         action: items[i],
1055                         classname: 'oe_sidebar_' + type
1056                     }
1057                 }
1058                 self.add_items(type=='print' ? 'print' : 'other', items);
1059             }
1060         });
1061     },
1062     on_item_action_clicked: function(item) {
1063         var self = this;
1064         self.getParent().sidebar_eval_context().done(function (sidebar_eval_context) {
1065             var ids = self.getParent().get_selected_ids();
1066             if (ids.length == 0) {
1067                 instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), { title: _t("Warning"), modal: true });
1068                 return false;
1069             }
1070             var active_ids_context = {
1071                 active_id: ids[0],
1072                 active_ids: ids,
1073                 active_model: self.getParent().dataset.model
1074             };
1075             self.rpc("/web/action/load", {
1076                 action_id: item.action.id,
1077                 context: active_ids_context,
1078                 eval_context: new instance.web.CompoundContext(sidebar_eval_context, active_ids_context),
1079             }).done(function(result) {
1080                 console.log(result.context);
1081                 result.context = new instance.web.CompoundContext(result.context || {}, active_ids_context);
1082                 result.flags = result.flags || {};
1083                 result.flags.new_window = true;
1084                 self.do_action(result, {
1085                     on_close: function() {
1086                         // reload view
1087                         self.getParent().reload();
1088                     },
1089                 });
1090             });
1091         });
1092     },
1093     do_attachement_update: function(dataset, model_id) {
1094         this.dataset = dataset;
1095         this.model_id = model_id;
1096         if (!model_id) {
1097             this.on_attachments_loaded([]);
1098         } else {
1099             var dom = [ ['res_model', '=', dataset.model], ['res_id', '=', model_id], ['type', 'in', ['binary', 'url']] ];
1100             var ds = new instance.web.DataSetSearch(this, 'ir.attachment', dataset.get_context(), dom);
1101             ds.read_slice(['name', 'url', 'type'], {}).done(this.on_attachments_loaded);
1102         }
1103     },
1104     on_attachments_loaded: function(attachments) {
1105         var self = this;
1106         var items = [];
1107         var prefix = this.session.url('/web/binary/saveas', {model: 'ir.attachment', field: 'datas', filename_field: 'name'});
1108         _.each(attachments,function(a) {
1109             a.label = a.name;
1110             if(a.type === "binary") {
1111                 a.url = prefix  + '&id=' + a.id + '&t=' + (new Date().getTime());
1112             }
1113         });
1114         self.items['files'] = attachments;
1115         self.redraw();
1116         this.$('.oe_sidebar_add_attachment .oe_form_binary_file').change(this.on_attachment_changed);
1117         this.$el.find('.oe_sidebar_delete_item').click(this.on_attachment_delete);
1118     },
1119     on_attachment_changed: function(e) {
1120         var $e = $(e.target);
1121         if ($e.val() !== '') {
1122             this.$el.find('form.oe_form_binary_form').submit();
1123             $e.parent().find('input[type=file]').prop('disabled', true);
1124             $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
1125             this.$('.oe_sidebar_add_attachment span').text(_t('Uploading...'));
1126             instance.web.blockUI();
1127         }
1128     },
1129     on_attachment_delete: function(e) {
1130         var self = this;
1131         e.preventDefault();
1132         e.stopPropagation();
1133         var self = this;
1134         var $e = $(e.currentTarget);
1135         if (confirm(_t("Do you really want to delete this attachment ?"))) {
1136             (new instance.web.DataSet(this, 'ir.attachment')).unlink([parseInt($e.attr('data-id'), 10)]).done(function() {
1137                 self.do_attachement_update(self.dataset, self.model_id);
1138             });
1139         }
1140     }
1141 });
1142
1143 instance.web.View = instance.web.Widget.extend({
1144     // name displayed in view switchers
1145     display_name: '',
1146     /**
1147      * Define a view type for each view to allow automatic call to fields_view_get.
1148      */
1149     view_type: undefined,
1150     init: function(parent, dataset, view_id, options) {
1151         this._super(parent);
1152         this.dataset = dataset;
1153         this.view_id = view_id;
1154         this.set_default_options(options);
1155     },
1156     start: function () {
1157         return this.load_view();
1158     },
1159     load_view: function(context) {
1160         var self = this;
1161         var view_loaded;
1162         if (this.embedded_view) {
1163             view_loaded = $.Deferred();
1164             $.async_when().done(function() {
1165                 view_loaded.resolve(self.embedded_view);
1166             });
1167         } else {
1168             if (! this.view_type)
1169                 console.warn("view_type is not defined", this);
1170             view_loaded = this.rpc("/web/view/load", {
1171                 "model": this.dataset.model,
1172                 "view_id": this.view_id,
1173                 "view_type": this.view_type,
1174                 toolbar: !!this.options.$sidebar,
1175                 context: this.dataset.get_context(context)
1176             });
1177         }
1178         return view_loaded.then(function(r) {
1179             self.trigger('view_loaded', r);
1180             // add css classes that reflect the (absence of) access rights
1181             self.$el.addClass('oe_view')
1182                 .toggleClass('oe_cannot_create', !self.is_action_enabled('create'))
1183                 .toggleClass('oe_cannot_edit', !self.is_action_enabled('edit'))
1184                 .toggleClass('oe_cannot_delete', !self.is_action_enabled('delete'));
1185         });
1186     },
1187     set_default_options: function(options) {
1188         this.options = options || {};
1189         _.defaults(this.options, {
1190             // All possible views options should be defaulted here
1191             $sidebar: null,
1192             sidebar_id: null,
1193             action: null,
1194             action_views_ids: {}
1195         });
1196     },
1197     /**
1198      * Fetches and executes the action identified by ``action_data``.
1199      *
1200      * @param {Object} action_data the action descriptor data
1201      * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1202      * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1203      * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1204      * @param {Object} [action_data.context=null] additional action context, to add to the current context
1205      * @param {instance.web.DataSet} dataset a dataset object used to communicate with the server
1206      * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1207      * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1208      */
1209     do_execute_action: function (action_data, dataset, record_id, on_closed) {
1210         var self = this;
1211         var result_handler = function () {
1212             if (on_closed) { on_closed.apply(null, arguments); }
1213             if (self.getParent() && self.getParent().on_action_executed) {
1214                 return self.getParent().on_action_executed.apply(null, arguments);
1215             }
1216         };
1217         var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {});
1218
1219         var handler = function (r) {
1220             var action = r;
1221             if (action && action.constructor == Object) {
1222                 var ncontext = new instance.web.CompoundContext(context);
1223                 if (record_id) {
1224                     ncontext.add({
1225                         active_id: record_id,
1226                         active_ids: [record_id],
1227                         active_model: dataset.model
1228                     });
1229                 }
1230                 ncontext.add(action.context || {});
1231                 return self.rpc('/web/session/eval_domain_and_context', {
1232                     contexts: [ncontext],
1233                     domains: []
1234                 }).then(function (results) {
1235                     action.context = results.context;
1236                     /* niv: previously we were overriding once more with action_data.context,
1237                      * I assumed this was not a correct behavior and removed it
1238                      */
1239                     return self.do_action(action, {
1240                         on_close: result_handler,
1241                     });
1242                 }, null);
1243             } else {
1244                 self.do_action({"type":"ir.actions.act_window_close"});
1245                 return result_handler();
1246             }
1247         };
1248
1249         if (action_data.special === 'cancel') {
1250             return handler({"type":"ir.actions.act_window_close"});
1251         } else if (action_data.type=="object") {
1252             var args = [[record_id]], additional_args = [];
1253             if (action_data.args) {
1254                 try {
1255                     // Warning: quotes and double quotes problem due to json and xml clash
1256                     // Maybe we should force escaping in xml or do a better parse of the args array
1257                     additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1258                     args = args.concat(additional_args);
1259                 } catch(e) {
1260                     console.error("Could not JSON.parse arguments", action_data.args);
1261                 }
1262             }
1263             args.push(context);
1264             return dataset.call_button(action_data.name, args).done(handler);
1265         } else if (action_data.type=="action") {
1266             return this.rpc('/web/action/load', { action_id: action_data.name, context: context, do_not_eval: true}).done(handler);
1267         } else  {
1268             return dataset.exec_workflow(record_id, action_data.name).done(handler);
1269         }
1270     },
1271     /**
1272      * Directly set a view to use instead of calling fields_view_get. This method must
1273      * be called before start(). When an embedded view is set, underlying implementations
1274      * of instance.web.View must use the provided view instead of any other one.
1275      *
1276      * @param embedded_view A view.
1277      */
1278     set_embedded_view: function(embedded_view) {
1279         this.embedded_view = embedded_view;
1280     },
1281     do_show: function () {
1282         this.$el.show();
1283     },
1284     do_hide: function () {
1285         this.$el.hide();
1286     },
1287     is_active: function () {
1288         var manager = this.getParent();
1289         return !manager || !manager.active_view
1290              || manager.views[manager.active_view].controller === this;
1291     }, /**
1292      * Wraps fn to only call it if the current view is the active one. If the
1293      * current view is not active, doesn't call fn.
1294      *
1295      * fn can not return anything, as a non-call to fn can't return anything
1296      * either
1297      *
1298      * @param {Function} fn function to wrap in the active guard
1299      */
1300     guard_active: function (fn) {
1301         var self = this;
1302         return function () {
1303             if (self.is_active()) {
1304                 fn.apply(self, arguments);
1305             }
1306         }
1307     },
1308     do_push_state: function(state) {
1309         if (this.getParent() && this.getParent().do_push_state) {
1310             this.getParent().do_push_state(state);
1311         }
1312     },
1313     do_load_state: function(state, warm) {
1314     },
1315     /**
1316      * Switches to a specific view type
1317      */
1318     do_switch_view: function() { 
1319         this.trigger.apply(this, ['switch_mode'].concat(_.toArray(arguments)));
1320     },
1321     /**
1322      * Cancels the switch to the current view, switches to the previous one
1323      *
1324      * @param {Object} [options]
1325      * @param {Boolean} [options.created=false] resource was created
1326      * @param {String} [options.default=null] view to switch to if no previous view
1327      */
1328
1329     do_search: function(view) {
1330     },
1331     on_sidebar_export: function() {
1332         new instance.web.DataExport(this, this.dataset).open();
1333     },
1334     sidebar_eval_context: function () {
1335         return $.when();
1336     },
1337     /**
1338      * Asks the view to reload itself, if the reloading is asynchronous should
1339      * return a {$.Deferred} indicating when the reloading is done.
1340      */
1341     reload: function () {
1342         return $.when();
1343     },
1344     /**
1345      * Return whether the user can perform the action ('create', 'edit', 'delete') in this view.
1346      * An action is disabled by setting the corresponding attribute in the view's main element,
1347      * like: <form string="" create="false" edit="false" delete="false">
1348      */
1349     is_action_enabled: function(action) {
1350         var attrs = this.fields_view.arch.attrs;
1351         return (action in attrs) ? JSON.parse(attrs[action]) : true;
1352     }
1353 });
1354
1355 instance.web.xml_to_json = function(node) {
1356     switch (node.nodeType) {
1357         case 3:
1358         case 4:
1359             return node.data;
1360         break;
1361         case 1:
1362             var attrs = $(node).getAttributes();
1363             _.each(['domain', 'filter_domain', 'context', 'default_get'], function(key) {
1364                 if (attrs[key]) {
1365                     try {
1366                         attrs[key] = JSON.parse(attrs[key]);
1367                     } catch(e) { }
1368                 }
1369             });
1370             return {
1371                 tag: node.tagName.toLowerCase(),
1372                 attrs: attrs,
1373                 children: _.map(node.childNodes, instance.web.xml_to_json)
1374             }
1375     }
1376 }
1377 instance.web.json_node_to_xml = function(node, human_readable, indent) {
1378     // For debugging purpose, this function will convert a json node back to xml
1379     indent = indent || 0;
1380     var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1381         r = sindent + '<' + node.tag,
1382         cr = human_readable ? '\n' : '';
1383
1384     if (typeof(node) === 'string') {
1385         return sindent + node;
1386     } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1387         throw new Error(
1388             _.str.sprintf("Node [%s] is not a JSONified XML node",
1389                           JSON.stringify(node)));
1390     }
1391     for (var attr in node.attrs) {
1392         var vattr = node.attrs[attr];
1393         if (typeof(vattr) !== 'string') {
1394             // domains, ...
1395             vattr = JSON.stringify(vattr);
1396         }
1397         vattr = vattr.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
1398         if (human_readable) {
1399             vattr = vattr.replace(/&quot;/g, "'");
1400         }
1401         r += ' ' + attr + '="' + vattr + '"';
1402     }
1403     if (node.children && node.children.length) {
1404         r += '>' + cr;
1405         var childs = [];
1406         for (var i = 0, ii = node.children.length; i < ii; i++) {
1407             childs.push(instance.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1408         }
1409         r += childs.join(cr);
1410         r += cr + sindent + '</' + node.tag + '>';
1411         return r;
1412     } else {
1413         return r + '/>';
1414     }
1415 };
1416 instance.web.xml_to_str = function(node) {
1417     if (window.XMLSerializer) {
1418         return (new XMLSerializer()).serializeToString(node);
1419     } else if (window.ActiveXObject) {
1420         return node.xml;
1421     } else {
1422         throw new Error("Could not serialize XML");
1423     }
1424 };
1425 instance.web.str_to_xml = function(s) {
1426     if (window.DOMParser) {
1427         var dp = new DOMParser();
1428         var r = dp.parseFromString(s, "text/xml");
1429         if (r.body && r.body.firstChild && r.body.firstChild.nodeName == 'parsererror') {
1430             throw new Error("Could not parse string to xml");
1431         }
1432         return r;
1433     }
1434     var xDoc;
1435     try {
1436         xDoc = new ActiveXObject("MSXML2.DOMDocument");
1437     } catch (e) {
1438         throw new Error("Could not find a DOM Parser: " + e.message);
1439     }
1440     xDoc.async = false;
1441     xDoc.preserveWhiteSpace = true;
1442     xDoc.loadXML(s);
1443     return xDoc;
1444 }
1445
1446 /**
1447  * Registry for all the main views
1448  */
1449 instance.web.views = new instance.web.Registry();
1450
1451 };
1452
1453 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: