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