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