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