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