[tta] use rpc to get right context, search with right contexts
[odoo/odoo.git] / addons / web / static / src / js / view_form.js
1 openerp.web.form = function (openerp) {
2
3 var _t = openerp.web._t;
4 var QWeb = openerp.web.qweb;
5
6 openerp.web.views.add('form', 'openerp.web.FormView');
7 openerp.web.FormView = openerp.web.View.extend( /** @lends openerp.web.FormView# */{
8     /**
9      * Indicates that this view is not searchable, and thus that no search
10      * view should be displayed (if there is one active).
11      */
12     searchable: false,
13     readonly : false,
14     form_template: "FormView",
15     identifier_prefix: 'formview-',
16     /**
17      * @constructs openerp.web.FormView
18      * @extends openerp.web.View
19      *
20      * @param {openerp.web.Session} session the current openerp session
21      * @param {openerp.web.DataSet} dataset the dataset this view will work with
22      * @param {String} view_id the identifier of the OpenERP view object
23      *
24      * @property {openerp.web.Registry} registry=openerp.web.form.widgets widgets registry for this form view instance
25      */
26     init: function(parent, dataset, view_id, options) {
27         this._super(parent);
28         this.set_default_options(options);
29         this.dataset = dataset;
30         this.model = dataset.model;
31         this.view_id = view_id || false;
32         this.fields_view = {};
33         this.widgets = {};
34         this.widgets_counter = 0;
35         this.fields = {};
36         this.datarecord = {};
37         this.show_invalid = true;
38         this.default_focus_field = null;
39         this.default_focus_button = null;
40         this.registry = this.readonly ? openerp.web.form.readonly : openerp.web.form.widgets;
41         this.has_been_loaded = $.Deferred();
42         this.$form_header = null;
43         this.translatable_fields = [];
44         _.defaults(this.options, {"always_show_new_button": true,
45             "not_interactible_on_create": false});
46         this.mutating_lock = $.Deferred();
47         this.initial_mutating_lock = this.mutating_lock;
48         this.on_change_lock = $.Deferred().resolve();
49         this.reload_lock = $.Deferred().resolve();
50     },
51     start: function() {
52         this._super();
53         return this.init_view();
54     },
55     init_view: function() {
56         if (this.embedded_view) {
57             var def = $.Deferred().then(this.on_loaded);
58             var self = this;
59             setTimeout(function() {def.resolve(self.embedded_view);}, 0);
60             return def.promise();
61         } else {
62             var context = new openerp.web.CompoundContext(this.dataset.get_context());
63             return this.rpc("/web/view/load", {
64                 "model": this.model,
65                 "view_id": this.view_id,
66                 "view_type": "form",
67                 toolbar: this.options.sidebar,
68                 context: context
69                 }, this.on_loaded);
70         }
71     },
72     stop: function() {
73         if (this.sidebar) {
74             this.sidebar.attachments.stop();
75             this.sidebar.stop();
76         }
77         _.each(this.widgets, function(w) {
78             w.stop();
79         });
80         this._super();
81     },
82     reposition: function ($e) {
83         this.$element = $e;
84         this.on_loaded();
85     },
86     on_loaded: function(data) {
87         var self = this;
88         if (data) {
89             this.fields_view = data;
90             var frame = new (this.registry.get_object('frame'))(this, this.fields_view.arch);
91
92             this.rendered = QWeb.render(this.form_template, { 'frame': frame, 'widget': this });
93         }
94         this.$element.html(this.rendered);
95         _.each(this.widgets, function(w) {
96             w.start();
97         });
98         this.$form_header = this.$element.find('.oe_form_header:first');
99         this.$form_header.find('div.oe_form_pager button[data-pager-action]').click(function() {
100             var action = $(this).data('pager-action');
101             self.on_pager_action(action);
102         });
103
104         this.$form_header.find('button.oe_form_button_save').click(this.on_button_save);
105         this.$form_header.find('button.oe_form_button_new').click(this.on_button_new);
106         this.$form_header.find('button.oe_form_button_duplicate').click(this.on_button_duplicate);
107         this.$form_header.find('button.oe_form_button_delete').click(this.on_button_delete);
108         this.$form_header.find('button.oe_form_button_toggle').click(this.on_toggle_readonly);
109
110         if (this.options.sidebar && this.options.sidebar_id) {
111             this.sidebar = new openerp.web.Sidebar(this, this.options.sidebar_id);
112             this.sidebar.start();
113             this.sidebar.do_unfold();
114             this.sidebar.attachments = new openerp.web.form.SidebarAttachments(this.sidebar, this);
115             this.sidebar.add_toolbar(this.fields_view.toolbar);
116             this.set_common_sidebar_sections(this.sidebar);
117         }
118         this.has_been_loaded.resolve();
119     },
120     on_toggle_readonly: function() {
121         var self = this;
122         self.translatable_fields = [];
123         self.widgets = {};
124         self.fields = {};
125         self.$form_header.find('button').unbind('click');
126         self.readonly = !self.readonly;
127         self.registry = self.readonly ? openerp.web.form.readonly : openerp.web.form.widgets;
128         self.on_loaded(self.fields_view);
129         return self.reload();
130     },
131     do_set_readonly: function() {
132         return this.readonly ? $.Deferred().resolve() : this.on_toggle_readonly();
133     },
134     do_set_editable: function() {
135         return !this.readonly ? $.Deferred().resolve() : this.on_toggle_readonly();
136     },
137     do_show: function () {
138         var promise;
139         if (this.dataset.index === null) {
140             // null index means we should start a new record
141             promise = this.on_button_new();
142         } else {
143             promise = this.dataset.read_index(_.keys(this.fields_view.fields)).pipe(this.on_record_loaded);
144         }
145         this.$element.show();
146         if (this.sidebar) {
147             this.sidebar.$element.show();
148         }
149         return promise;
150     },
151     do_hide: function () {
152         this.$element.hide();
153         if (this.sidebar) {
154             this.sidebar.$element.hide();
155         }
156     },
157     on_record_loaded: function(record) {
158         var self = this,
159             deferred_stack = $.Deferred.queue();
160         if (!record) {
161             throw("Form: No record received");
162         }
163         if (!record.id) {
164             this.$form_header.find('.oe_form_on_create').show();
165             this.$form_header.find('.oe_form_on_update').hide();
166             if (!this.options["always_show_new_button"]) {
167                 this.$form_header.find('button.oe_form_button_new').hide();
168             }
169         } else {
170             this.$form_header.find('.oe_form_on_create').hide();
171             this.$form_header.find('.oe_form_on_update').show();
172             this.$form_header.find('button.oe_form_button_new').show();
173         }
174         this.$form_header.find('.oe_form_on_readonly').toggle(this.readonly);
175         this.$form_header.find('.oe_form_on_editable').toggle(!this.readonly);
176         this.datarecord = record;
177
178         _(this.fields).each(function (field, f) {
179             field.reset();
180             var result = field.set_value(self.datarecord[f] || false);
181             if (result && _.isFunction(result.promise)) {
182                 deferred_stack.push(result);
183             }
184             $.when(result).then(function() {
185                 field.validate();
186             });
187         });
188         deferred_stack.push('force resolution if no fields');
189         return deferred_stack.then(function() {
190             if (!record.id) {
191                 // New record: Second pass in order to trigger the onchanges
192                 self.show_invalid = false;
193                 for (var f in record) {
194                     var field = self.fields[f];
195                     if (field) {
196                         field.dirty = true;
197                         self.do_onchange(field);
198                     }
199                 }
200             }
201             self.on_form_changed();
202             self.initial_mutating_lock.resolve();
203             self.show_invalid = true;
204             self.do_update_pager(record.id == null);
205             if (self.sidebar) {
206                 self.sidebar.attachments.do_update();
207             }
208             if (self.default_focus_field && !self.embedded_view) {
209                 self.default_focus_field.focus();
210             }
211         });
212     },
213     on_form_changed: function() {
214         for (var w in this.widgets) {
215             w = this.widgets[w];
216             w.process_modifiers();
217             w.update_dom();
218         }
219     },
220     on_pager_action: function(action) {
221         if (this.can_be_discarded()) {
222             switch (action) {
223                 case 'first':
224                     this.dataset.index = 0;
225                     break;
226                 case 'previous':
227                     this.dataset.previous();
228                     break;
229                 case 'next':
230                     this.dataset.next();
231                     break;
232                 case 'last':
233                     this.dataset.index = this.dataset.ids.length - 1;
234                     break;
235             }
236             this.reload();
237         }
238     },
239     do_update_pager: function(hide_index) {
240         var $pager = this.$form_header.find('div.oe_form_pager');
241         var index = hide_index ? '-' : this.dataset.index + 1;
242         $pager.find('span.oe_pager_index').html(index);
243         $pager.find('span.oe_pager_count').html(this.dataset.ids.length);
244     },
245     parse_on_change: function (on_change, widget) {
246         var self = this;
247         var onchange = _.str.trim(on_change);
248         var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
249         if (!call) {
250             return null;
251         }
252
253         var method = call[1];
254         if (!_.str.trim(call[2])) {
255             return {method: method, args: [], context_index: null}
256         }
257
258         var argument_replacement = {
259             'False': function () {return false;},
260             'True': function () {return true;},
261             'None': function () {return null;},
262             'context': function (i) {
263                 context_index = i;
264                 var ctx = widget.build_context ? widget.build_context() : {};
265                 return ctx;
266             }
267         };
268         var parent_fields = null, context_index = null;
269         var args = _.map(call[2].split(','), function (a, i) {
270             var field = _.str.trim(a);
271
272             // literal constant or context
273             if (field in argument_replacement) {
274                 return argument_replacement[field](i);
275             }
276             // form field
277             if (self.fields[field]) {
278                 var value = self.fields[field].get_on_change_value();
279                 return value == null ? false : value;
280             }
281             // parent field
282             var splitted = field.split('.');
283             if (splitted.length > 1 && _.str.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
284                 if (parent_fields === null) {
285                     parent_fields = self.dataset.parent_view.get_fields_values();
286                 }
287                 var p_val = parent_fields[_.str.trim(splitted[1])];
288                 if (p_val !== undefined) {
289                     return p_val == null ? false : p_val;
290                 }
291             }
292             // string literal
293             var first_char = field[0], last_char = field[field.length-1];
294             if ((first_char === '"' && last_char === '"')
295                 || (first_char === "'" && last_char === "'")) {
296                 return field.slice(1, -1);
297             }
298
299             throw new Error("Could not get field with name '" + field +
300                             "' for onchange '" + onchange + "'");
301         });
302
303         return {
304             method: method,
305             args: args,
306             context_index: context_index
307         };
308     },
309     do_onchange: function(widget, processed) {
310         var self = this;
311         var act = function() {
312             try {
313                 processed = processed || [];
314                 var on_change = widget.node.attrs.on_change;
315                 if (on_change) {
316                     var change_spec = self.parse_on_change(on_change, widget);
317                     if (change_spec) {
318                         var ajax = {
319                             url: '/web/dataset/call',
320                             async: false
321                         };
322                         return self.rpc(ajax, {
323                             model: self.dataset.model,
324                             method: change_spec.method,
325                             args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
326                             context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
327                         }).pipe(function(response) {
328                             return self.on_processed_onchange(response, processed);
329                         });
330                     } else {
331                         console.warn("Wrong on_change format", on_change);
332                     }
333                 }
334             } catch(e) {
335                 console.error(e);
336                 return $.Deferred().reject();
337             }
338         };
339         this.on_change_lock = this.on_change_lock.pipe(act, act);
340         return this.on_change_lock;
341     },
342     on_processed_onchange: function(response, processed) {
343         try {
344         var result = response;
345         if (result.value) {
346             for (var f in result.value) {
347                 var field = this.fields[f];
348                 // If field is not defined in the view, just ignore it
349                 if (field) {
350                     var value = result.value[f];
351                     processed.push(field.name);
352                     if (field.get_value() != value) {
353                         field.set_value(value);
354                         field.dirty = true;
355                         if (_.indexOf(processed, field.name) < 0) {
356                             this.do_onchange(field, processed);
357                         }
358                     }
359                 }
360             }
361             this.on_form_changed();
362         }
363         if (!_.isEmpty(result.warning)) {
364             $(QWeb.render("DialogWarning", result.warning)).dialog({
365                 modal: true,
366                 buttons: {
367                     Ok: function() {
368                         $(this).dialog("close");
369                     }
370                 }
371             });
372         }
373         if (result.domain) {
374             // TODO:
375         }
376         return $.Deferred().resolve();
377         } catch(e) {
378             console.error(e);
379             return $.Deferred().reject();
380         }
381     },
382     on_button_save: function() {
383         return this.do_save().then(this.do_set_readonly);
384     },
385     on_button_new: function() {
386         var self = this;
387         var def = $.Deferred();
388         $.when(this.has_been_loaded).then(function() {
389             if (self.can_be_discarded()) {
390                 var keys = _.keys(self.fields_view.fields);
391                 $.when(self.do_set_editable()).then(function() {
392                     if (keys.length) {
393                         self.dataset.default_get(keys).pipe(self.on_record_loaded).then(function() {
394                             def.resolve();
395                         });
396                     } else {
397                         self.on_record_loaded({}).then(function() {
398                             def.resolve();
399                         });
400                     }
401                 });
402             }
403         });
404         return def.promise();
405     },
406     on_button_duplicate: function() {
407         var self = this;
408         var def = $.Deferred();
409         $.when(this.has_been_loaded).then(function() {
410             if (self.can_be_discarded()) {
411                 self.dataset.call('copy', [self.datarecord.id, {}, self.dataset.context]).then(function(new_id) {
412                     return self.on_created({ result : new_id });
413                 }).then(self.do_set_editable).then(function() {
414                     def.resolve();
415                 });
416             }
417         });
418         return def.promise();
419     },
420     on_button_delete: function() {
421         var self = this;
422         var def = $.Deferred();
423         $.when(this.has_been_loaded).then(function() {
424             if (self.can_be_discarded() && self.datarecord.id) {
425                 if (confirm(_t("Do you really want to delete this record?"))) {
426                     self.dataset.unlink([self.datarecord.id]).then(function() {
427                         self.on_pager_action('next');
428                         def.resolve();
429                     });
430                 } else {
431                     setTimeout(function () {
432                         def.reject();
433                     }, 0)
434                 }
435             }
436         });
437         return def.promise();
438     },
439     can_be_discarded: function() {
440         return !this.is_dirty() || confirm(_t("Warning, the record has been modified, your changes will be discarded."));
441     },
442     /**
443      * Triggers saving the form's record. Chooses between creating a new
444      * record or saving an existing one depending on whether the record
445      * already has an id property.
446      *
447      * @param {Function} success callback on save success
448      * @param {Boolean} [prepend_on_create=false] if ``do_save`` creates a new record, should that record be inserted at the start of the dataset (by default, records are added at the end)
449      */
450     do_save: function(success, prepend_on_create) {
451         var self = this;
452         var action = function() {
453             try {
454             if (!self.initial_mutating_lock.isResolved() && !self.initial_mutating_lock.isRejected())
455                 return;
456             var form_invalid = false,
457                 values = {},
458                 first_invalid_field = null;
459             for (var f in self.fields) {
460                 f = self.fields[f];
461                 if (!f.is_valid()) {
462                     form_invalid = true;
463                     f.update_dom();
464                     if (!first_invalid_field) {
465                         first_invalid_field = f;
466                     }
467                 } else if (f.name !== 'id' && !f.readonly && (!self.datarecord.id || f.is_dirty())) {
468                     // Special case 'id' field, do not save this field
469                     // on 'create' : save all non readonly fields
470                     // on 'edit' : save non readonly modified fields
471                     values[f.name] = f.get_value();
472                 }
473             }
474             if (form_invalid) {
475                 first_invalid_field.focus();
476                 self.on_invalid();
477                 return $.Deferred().reject();
478             } else {
479                 if (!self.datarecord.id) {
480                     openerp.log("FormView(", self, ") : About to create", values);
481                     return self.dataset.create(values).pipe(function(r) {
482                         return self.on_created(r, undefined, prepend_on_create);
483                     }).then(success);
484                 } else if (_.isEmpty(values)) {
485                     openerp.log("FormView(", self, ") : Nothing to save");
486                     if (success) {
487                         success();
488                     }
489                 } else {
490                     openerp.log("FormView(", self, ") : About to save", values);
491                     return self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
492                         return self.on_saved(r);
493                     }).then(success);
494                 }
495             }
496             } catch (e) {
497                 console.error(e);
498                 return $.Deferred().reject();
499             }
500         };
501         this.mutating_lock = this.mutating_lock.pipe(action, action);
502         return this.mutating_lock;
503     },
504     on_invalid: function() {
505         var msg = "<ul>";
506         _.each(this.fields, function(f) {
507             if (!f.is_valid()) {
508                 msg += "<li>" + f.string + "</li>";
509             }
510         });
511         msg += "</ul>";
512         this.do_warn("The following fields are invalid :", msg);
513     },
514     on_saved: function(r, success) {
515         if (!r.result) {
516             // should not happen in the server, but may happen for internal purpose
517             return $.Deferred().reject();
518         } else {
519             return $.when(this.reload()).pipe(function () {
520                 return $.when(r).then(success); }, null);
521         }
522     },
523     /**
524      * Updates the form' dataset to contain the new record:
525      *
526      * * Adds the newly created record to the current dataset (at the end by
527      *   default)
528      * * Selects that record (sets the dataset's index to point to the new
529      *   record's id).
530      * * Updates the pager and sidebar displays
531      *
532      * @param {Object} r
533      * @param {Function} success callback to execute after having updated the dataset
534      * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
535      */
536     on_created: function(r, success, prepend_on_create) {
537         if (!r.result) {
538             // should not happen in the server, but may happen for internal purpose
539             return $.Deferred().reject();
540         } else {
541             this.datarecord.id = r.result;
542             if (!prepend_on_create) {
543                 this.dataset.ids.push(this.datarecord.id);
544                 this.dataset.index = this.dataset.ids.length - 1;
545             } else {
546                 this.dataset.ids.unshift(this.datarecord.id);
547                 this.dataset.index = 0;
548             }
549             this.do_update_pager();
550             if (this.sidebar) {
551                 this.sidebar.attachments.do_update();
552             }
553             openerp.log("The record has been created with id #" + this.datarecord.id);
554             this.reload();
555             return $.when(_.extend(r, {created: true})).then(success);
556         }
557     },
558     on_action: function (action) {
559         console.debug('Executing action', action);
560     },
561     reload: function() {
562         var self = this;
563         var act = function() {
564             if (self.dataset.index == null || self.dataset.index < 0) {
565                 return $.when(self.on_button_new());
566             } else {
567                 return self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_record_loaded);
568             }
569         };
570         this.reload_lock = this.reload_lock.pipe(act, act);
571         return this.reload_lock;
572     },
573     get_fields_values: function() {
574         var values = {};
575         _.each(this.fields, function(value, key) {
576             var val = value.get_value();
577             values[key] = val;
578         });
579         return values;
580     },
581     get_selected_ids: function() {
582         var id = this.dataset.ids[this.dataset.index];
583         return id ? [id] : [];
584     },
585     recursive_save: function() {
586         var self = this;
587         return $.when(this.do_save()).pipe(function(res) {
588             if (self.dataset.parent_view)
589                 return self.dataset.parent_view.recursive_save();
590         });
591     },
592     is_dirty: function() {
593         return _.any(this.fields, function (value) {
594             return value.is_dirty();
595         });
596     },
597     is_interactible_record: function() {
598         var id = this.datarecord.id;
599         if (!id) {
600             if (this.options.not_interactible_on_create)
601                 return false;
602         } else if (typeof(id) === "string") {
603             if(openerp.web.BufferedDataSet.virtual_id_regex.test(id))
604                 return false;
605         }
606         return true;
607     },
608     sidebar_context: function () {
609         return this.do_save().pipe($.proxy(this, 'get_fields_values'));
610     }
611 });
612 openerp.web.FormDialog = openerp.web.Dialog.extend({
613     init: function(parent, options, view_id, dataset) {
614         this._super(parent, options);
615         this.dataset = dataset;
616         this.view_id = view_id;
617         return this;
618     },
619     start: function() {
620         this._super();
621         this.form = new openerp.web.FormView(this, this.dataset, this.view_id, {
622             sidebar: false,
623             pager: false
624         });
625         this.form.appendTo(this.$element);
626         this.form.on_created.add_last(this.on_form_dialog_saved);
627         this.form.on_saved.add_last(this.on_form_dialog_saved);
628         return this;
629     },
630     select_id: function(id) {
631         if (this.form.dataset.select_id(id)) {
632             return this.form.do_show();
633         } else {
634             this.do_warn("Could not find id in dataset");
635             return $.Deferred().reject();
636         }
637     },
638     on_form_dialog_saved: function(r) {
639         this.close();
640     }
641 });
642
643 /** @namespace */
644 openerp.web.form = {};
645
646 openerp.web.form.SidebarAttachments = openerp.web.Widget.extend({
647     init: function(parent, form_view) {
648         var $section = parent.add_section(_t('Attachments'), 'attachments');
649         this.$div = $('<div class="oe-sidebar-attachments"></div>');
650         $section.append(this.$div);
651
652         this._super(parent, $section.attr('id'));
653         this.view = form_view;
654     },
655     do_update: function() {
656         if (!this.view.datarecord.id) {
657             this.on_attachments_loaded([]);
658         } else {
659             (new openerp.web.DataSetSearch(
660                 this, 'ir.attachment', this.view.dataset.get_context(),
661                 [
662                     ['res_model', '=', this.view.dataset.model],
663                     ['res_id', '=', this.view.datarecord.id],
664                     ['type', 'in', ['binary', 'url']]
665                 ])).read_slice(['name', 'url', 'type'], {}, this.on_attachments_loaded);
666         }
667     },
668     on_attachments_loaded: function(attachments) {
669         this.attachments = attachments;
670         this.$div.html(QWeb.render('FormView.sidebar.attachments', this));
671         this.$element.find('.oe-binary-file').change(this.on_attachment_changed);
672         this.$element.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
673     },
674     on_attachment_changed: function(e) {
675         window[this.element_id + '_iframe'] = this.do_update;
676         var $e = $(e.target);
677         if ($e.val() != '') {
678             this.$element.find('form.oe-binary-form').submit();
679             $e.parent().find('input[type=file]').attr('disabled', 'true');
680             $e.parent().find('button').attr('disabled', 'true').find('img, span').toggle();
681         }
682     },
683     on_attachment_delete: function(e) {
684         var self = this, $e = $(e.currentTarget);
685         var name = _.str.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
686         if (confirm("Do you really want to delete the attachment " + name + " ?")) {
687             this.rpc('/web/dataset/unlink', {
688                 model: 'ir.attachment',
689                 ids: [parseInt($e.attr('data-id'))]
690             }, function(r) {
691                 $e.parent().remove();
692                 self.do_notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
693             });
694         }
695     }
696 });
697
698 openerp.web.form.compute_domain = function(expr, fields) {
699     var stack = [];
700     for (var i = expr.length - 1; i >= 0; i--) {
701         var ex = expr[i];
702         if (ex.length == 1) {
703             var top = stack.pop();
704             switch (ex) {
705                 case '|':
706                     stack.push(stack.pop() || top);
707                     continue;
708                 case '&':
709                     stack.push(stack.pop() && top);
710                     continue;
711                 case '!':
712                     stack.push(!top);
713                     continue;
714                 default:
715                     throw new Error('Unknown domain operator ' + ex);
716             }
717         }
718
719         var field = fields[ex[0]];
720         if (!field) {
721             throw new Error("Domain references unknown field : " + ex[0]);
722         }
723         var field_value = field.get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
724         var op = ex[1];
725         var val = ex[2];
726
727         switch (op.toLowerCase()) {
728             case '=':
729             case '==':
730                 stack.push(field_value == val);
731                 break;
732             case '!=':
733             case '<>':
734                 stack.push(field_value != val);
735                 break;
736             case '<':
737                 stack.push(field_value < val);
738                 break;
739             case '>':
740                 stack.push(field_value > val);
741                 break;
742             case '<=':
743                 stack.push(field_value <= val);
744                 break;
745             case '>=':
746                 stack.push(field_value >= val);
747                 break;
748             case 'in':
749                 stack.push(_(val).contains(field_value));
750                 break;
751             case 'not in':
752                 stack.push(!_(val).contains(field_value));
753                 break;
754             default:
755                 console.warn("Unsupported operator in modifiers :", op);
756         }
757     }
758     return _.all(stack, _.identity);
759 };
760
761 openerp.web.form.Widget = openerp.web.Widget.extend(/** @lends openerp.web.form.Widget# */{
762     template: 'Widget',
763     identifier_prefix: 'formview-widget-',
764     /**
765      * @constructs openerp.web.form.Widget
766      * @extends openerp.web.Widget
767      *
768      * @param view
769      * @param node
770      */
771     init: function(view, node) {
772         this.view = view;
773         this.node = node;
774         this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
775         this.always_invisible = (this.modifiers.invisible && this.modifiers.invisible === true);
776         this.type = this.type || node.tag;
777         this.element_name = this.element_name || this.type;
778         this.element_class = [
779             'formview', this.view.view_id, this.element_name,
780             this.view.widgets_counter++].join("_");
781
782         this._super(view);
783
784         this.view.widgets[this.element_class] = this;
785         this.children = node.children;
786         this.colspan = parseInt(node.attrs.colspan || 1, 10);
787         this.decrease_max_width = 0;
788
789         this.string = this.string || node.attrs.string;
790         this.help = this.help || node.attrs.help;
791         this.invisible = this.modifiers['invisible'] === true;
792         this.classname = 'oe_form_' + this.type;
793
794         this.align = parseFloat(this.node.attrs.align);
795         if (isNaN(this.align) || this.align === 1) {
796             this.align = 'right';
797         } else if (this.align === 0) {
798             this.align = 'left';
799         } else {
800             this.align = 'center';
801         }
802
803
804         this.width = this.node.attrs.width;
805     },
806     start: function() {
807         this.$element = this.view.$element.find(
808             '.' + this.element_class.replace(/[^\r\n\f0-9A-Za-z_-]/g, "\\$&"));
809     },
810     process_modifiers: function() {
811         var compute_domain = openerp.web.form.compute_domain;
812         for (var a in this.modifiers) {
813             this[a] = compute_domain(this.modifiers[a], this.view.fields);
814         }
815     },
816     update_dom: function() {
817         this.$element.toggle(!this.invisible);
818     },
819     render: function() {
820         var template = this.template;
821         return QWeb.render(template, { "widget": this });
822     },
823     do_attach_tooltip: function(widget, trigger, options) {
824         widget = widget || this;
825         trigger = trigger || this.$element;
826         options = _.extend({
827                 delay: 1000,
828                 maxWidth: openerp.connection.debug ? '300px' : '200px',
829                 content: function() {
830                     var template = widget.template + '.tooltip';
831                     if (!QWeb.has_template(template)) {
832                         template = 'WidgetLabel.tooltip';
833                     }
834                     return QWeb.render(template, {
835                         debug: openerp.connection.debug,
836                         widget: widget
837                     });
838                 }
839             }, options || {});
840         trigger.tipTip(options);
841     },
842     _build_view_fields_values: function() {
843         var a_dataset = this.view.dataset;
844         var fields_values = this.view.get_fields_values();
845         var active_id = a_dataset.ids[a_dataset.index];
846         _.extend(fields_values, {
847             active_id: active_id || false,
848             active_ids: active_id ? [active_id] : [],
849             active_model: a_dataset.model,
850             parent: a_dataset.parent_view ? a_dataset.parent_view.get_fields_values() : {}
851         });
852         return fields_values;
853     },
854     _build_eval_context: function() {
855         var a_dataset = this.view.dataset;
856         return new openerp.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values());
857     },
858     /**
859      * Builds a new context usable for operations related to fields by merging
860      * the fields'context with the action's context.
861      */
862     build_context: function() {
863         var f_context = (this.field || {}).context || {};
864         if (!!f_context.__ref) {
865             var fields_values = this._build_eval_context();
866             f_context = new openerp.web.CompoundDomain(f_context).set_eval_context(fields_values);
867         }
868         // maybe the default_get should only be used when we do a default_get?
869         var v_contexts = _.compact([this.node.attrs.default_get || null,
870             this.node.attrs.context || null]);
871         var v_context = new openerp.web.CompoundContext();
872         _.each(v_contexts, function(x) {v_context.add(x);});
873         if (_.detect(v_contexts, function(x) {return !!x.__ref;})) {
874             var fields_values = this._build_eval_context();
875             v_context.set_eval_context(fields_values);
876         }
877         // if there is a context on the node, overrides the model's context
878         var ctx = v_contexts.length > 0 ? v_context : f_context;
879         return ctx;
880     },
881     build_domain: function() {
882         var f_domain = this.field.domain || [];
883         var n_domain = this.node.attrs.domain || null;
884         // if there is a domain on the node, overrides the model's domain
885         var final_domain = n_domain !== null ? n_domain : f_domain;
886         if (!(final_domain instanceof Array)) {
887             var fields_values = this._build_eval_context();
888             final_domain = new openerp.web.CompoundDomain(final_domain).set_eval_context(fields_values);
889         }
890         return final_domain;
891     }
892 });
893
894 openerp.web.form.WidgetFrame = openerp.web.form.Widget.extend({
895     template: 'WidgetFrame',
896     init: function(view, node) {
897         this._super(view, node);
898         this.columns = parseInt(node.attrs.col || 4, 10);
899         this.x = 0;
900         this.y = 0;
901         this.table = [];
902         this.add_row();
903         for (var i = 0; i < node.children.length; i++) {
904             var n = node.children[i];
905             if (n.tag == "newline") {
906                 this.add_row();
907             } else {
908                 this.handle_node(n);
909             }
910         }
911         this.set_row_cells_with(this.table[this.table.length - 1]);
912     },
913     add_row: function(){
914         if (this.table.length) {
915             this.set_row_cells_with(this.table[this.table.length - 1]);
916         }
917         var row = [];
918         this.table.push(row);
919         this.x = 0;
920         this.y += 1;
921         return row;
922     },
923     set_row_cells_with: function(row) {
924         var bypass = 0,
925             max_width = 100,
926             row_length = row.length;
927         for (var i = 0; i < row.length; i++) {
928             if (row[i].always_invisible) {
929                 row_length--;
930             } else {
931                 bypass += row[i].width === undefined ? 0 : 1;
932                 max_width -= row[i].decrease_max_width;
933             }
934         }
935         var size_unit = Math.round(max_width / (this.columns - bypass)),
936             colspan_sum = 0;
937         for (var i = 0; i < row.length; i++) {
938             var w = row[i];
939             if (w.always_invisible) {
940                 continue;
941             }
942             colspan_sum += w.colspan;
943             if (w.width === undefined) {
944                 var width = (i === row_length - 1 && colspan_sum === this.columns) ? max_width : Math.round(size_unit * w.colspan);
945                 max_width -= width;
946                 w.width = width + '%';
947             }
948         }
949     },
950     handle_node: function(node) {
951         var type = {};
952         if (node.tag == 'field') {
953             type = this.view.fields_view.fields[node.attrs.name] || {};
954             if (node.attrs.widget == 'statusbar') {
955                 // This way we can retain backward compatibility between addons and old clients
956                 node.attrs.nolabel = '1';
957             }
958         }
959         var widget = new (this.view.registry.get_any(
960                 [node.attrs.widget, type.type, node.tag])) (this.view, node);
961         if (node.tag == 'field') {
962             if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
963                 this.view.default_focus_field = widget;
964             }
965             if (node.attrs.nolabel != '1') {
966                 var label = new (this.view.registry.get_object('label')) (this.view, node);
967                 label["for"] = widget;
968                 this.add_widget(label, widget.colspan + 1);
969             }
970         }
971         this.add_widget(widget);
972     },
973     add_widget: function(widget, colspan) {
974         var current_row = this.table[this.table.length - 1];
975         if (!widget.always_invisible) {
976             colspan = colspan || widget.colspan;
977             if (current_row.length && (this.x + colspan) > this.columns) {
978                 current_row = this.add_row();
979             }
980             this.x += widget.colspan;
981         }
982         current_row.push(widget);
983         return widget;
984     }
985 });
986
987 openerp.web.form.WidgetGroup = openerp.web.form.WidgetFrame.extend({
988     template: 'WidgetGroup',
989 }),
990
991 openerp.web.form.WidgetNotebook = openerp.web.form.Widget.extend({
992     template: 'WidgetNotebook',
993     init: function(view, node) {
994         this._super(view, node);
995         this.pages = [];
996         for (var i = 0; i < node.children.length; i++) {
997             var n = node.children[i];
998             if (n.tag == "page") {
999                 var page = new (this.view.registry.get_object('notebookpage'))(
1000                         this.view, n, this, this.pages.length);
1001                 this.pages.push(page);
1002             }
1003         }
1004     },
1005     start: function() {
1006         var self = this;
1007         this._super.apply(this, arguments);
1008         this.$element.find('> ul > li').each(function (index, tab_li) {
1009             var page = self.pages[index],
1010                 id = _.uniqueId(self.element_name + '-');
1011             page.element_id = id;
1012             $(tab_li).find('a').attr('href', '#' + id);
1013         });
1014         this.$element.find('> div').each(function (index, page) {
1015             page.id = self.pages[index].element_id;
1016         });
1017         this.$element.tabs();
1018         this.view.on_button_new.add_first(this.do_select_first_visible_tab);
1019         if (openerp.connection.debug) {
1020             this.do_attach_tooltip(this, this.$element.find('ul:first'), {
1021                 defaultPosition: 'top'
1022             });
1023         }
1024     },
1025     do_select_first_visible_tab: function() {
1026         for (var i = 0; i < this.pages.length; i++) {
1027             var page = this.pages[i];
1028             if (page.invisible === false) {
1029                 this.$element.tabs('select', page.index);
1030                 break;
1031             }
1032         }
1033     }
1034 });
1035
1036 openerp.web.form.WidgetNotebookPage = openerp.web.form.WidgetFrame.extend({
1037     template: 'WidgetNotebookPage',
1038     init: function(view, node, notebook, index) {
1039         this.notebook = notebook;
1040         this.index = index;
1041         this.element_name = 'page_' + index;
1042         this._super(view, node);
1043     },
1044     start: function() {
1045         this._super.apply(this, arguments);
1046         this.$element_tab = this.notebook.$element.find(
1047                 '> ul > li:eq(' + this.index + ')');
1048     },
1049     update_dom: function() {
1050         if (this.invisible && this.index === this.notebook.$element.tabs('option', 'selected')) {
1051             this.notebook.do_select_first_visible_tab();
1052         }
1053         this.$element_tab.toggle(!this.invisible);
1054         this.$element.toggle(!this.invisible);
1055     }
1056 });
1057
1058 openerp.web.form.WidgetSeparator = openerp.web.form.Widget.extend({
1059     template: 'WidgetSeparator',
1060     init: function(view, node) {
1061         this._super(view, node);
1062         this.orientation = node.attrs.orientation || 'horizontal';
1063         if (this.orientation === 'vertical') {
1064             this.width = '1';
1065         }
1066         this.classname += '_' + this.orientation;
1067     }
1068 });
1069
1070 openerp.web.form.WidgetButton = openerp.web.form.Widget.extend({
1071     template: 'WidgetButton',
1072     init: function(view, node) {
1073         this._super(view, node);
1074         this.force_disabled = false;
1075         if (this.string) {
1076             // We don't have button key bindings in the webclient
1077             this.string = this.string.replace(/_/g, '');
1078         }
1079         if (node.attrs.default_focus == '1') {
1080             // TODO fme: provide enter key binding to widgets
1081             this.view.default_focus_button = this;
1082         }
1083     },
1084     start: function() {
1085         this._super.apply(this, arguments);
1086         this.$element.find("button").click(this.on_click);
1087         if (this.help || openerp.connection.debug) {
1088             this.do_attach_tooltip();
1089         }
1090     },
1091     on_click: function() {
1092         var self = this;
1093         this.force_disabled = true;
1094         this.check_disable();
1095         this.execute_action().always(function() {
1096             self.force_disabled = false;
1097             self.check_disable();
1098         });
1099     },
1100     execute_action: function() {
1101         var self = this;
1102         var exec_action = function() {
1103             if (self.node.attrs.confirm) {
1104                 var def = $.Deferred();
1105                 var dialog = $('<div>' + self.node.attrs.confirm + '</div>').dialog({
1106                     title: 'Confirm',
1107                     modal: true,
1108                     buttons: {
1109                         Ok: function() {
1110                             self.on_confirmed().then(function() {
1111                                 def.resolve();
1112                             });
1113                             $(this).dialog("close");
1114                         },
1115                         Cancel: function() {
1116                             def.resolve();
1117                             $(this).dialog("close");
1118                         }
1119                     }
1120                 });
1121                 return def.promise();
1122             } else {
1123                 return self.on_confirmed();
1124             }
1125         };
1126         if (!this.node.attrs.special) {
1127             return this.view.recursive_save().pipe(exec_action);
1128         } else {
1129             return exec_action();
1130         }
1131     },
1132     on_confirmed: function() {
1133         var self = this;
1134
1135         var context = this.node.attrs.context;
1136         if (context && context.__ref) {
1137             context = new openerp.web.CompoundContext(context);
1138             context.set_eval_context(this._build_eval_context());
1139         }
1140
1141         return this.view.do_execute_action(
1142             _.extend({}, this.node.attrs, {context: context}),
1143             this.view.dataset, this.view.datarecord.id, function () {
1144                 self.view.reload();
1145             });
1146     },
1147     update_dom: function() {
1148         this._super();
1149         this.check_disable();
1150     },
1151     check_disable: function() {
1152         if (this.readonly || this.force_disabled || !this.view.is_interactible_record()) {
1153             this.$element.find("button").attr("disabled", "disabled");
1154             this.$element.find("button").css("color", "grey");
1155         } else {
1156             this.$element.find("button").removeAttr("disabled");
1157             this.$element.find("button").css("color", "");
1158         }
1159     }
1160 });
1161
1162 openerp.web.form.WidgetLabel = openerp.web.form.Widget.extend({
1163     template: 'WidgetLabel',
1164     init: function(view, node) {
1165         this.element_name = 'label_' + node.attrs.name;
1166
1167         this._super(view, node);
1168
1169         if (this.node.tag == 'label' && (this.align === 'left' || this.node.attrs.colspan || (this.string && this.string.length > 32))) {
1170             this.template = "WidgetParagraph";
1171             this.colspan = parseInt(this.node.attrs.colspan || 1, 10);
1172         } else {
1173             this.colspan = 1;
1174             this.width = '1%';
1175             this.decrease_max_width = 1;
1176             this.nowrap = true;
1177         }
1178     },
1179     render: function () {
1180         if (this['for'] && this.type !== 'label') {
1181             return QWeb.render(this.template, {widget: this['for']});
1182         }
1183         // Actual label widgets should not have a false and have type label
1184         return QWeb.render(this.template, {widget: this});
1185     },
1186     start: function() {
1187         this._super();
1188         var self = this;
1189         if (this['for'] && (this['for'].help || openerp.connection.debug)) {
1190             this.do_attach_tooltip(self['for']);
1191         }
1192         this.$element.find("label").dblclick(function() {
1193             var widget = self['for'] || self;
1194             openerp.log(widget.element_class , widget);
1195             window.w = widget;
1196         });
1197     }
1198 });
1199
1200 openerp.web.form.Field = openerp.web.form.Widget.extend(/** @lends openerp.web.form.Field# */{
1201     /**
1202      * @constructs openerp.web.form.Field
1203      * @extends openerp.web.form.Widget
1204      *
1205      * @param view
1206      * @param node
1207      */
1208     init: function(view, node) {
1209         this.name = node.attrs.name;
1210         this.value = undefined;
1211         view.fields[this.name] = this;
1212         this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
1213         this.element_name = "field_" + this.name + "_" + this.type;
1214
1215         this._super(view, node);
1216
1217         if (node.attrs.nolabel != '1' && this.colspan > 1) {
1218             this.colspan--;
1219         }
1220         this.field = view.fields_view.fields[node.attrs.name] || {};
1221         this.string = node.attrs.string || this.field.string;
1222         this.help = node.attrs.help || this.field.help;
1223         this.nolabel = (this.field.nolabel || node.attrs.nolabel) === '1';
1224         this.readonly = this.modifiers['readonly'] === true;
1225         this.required = this.modifiers['required'] === true;
1226         this.invalid = this.dirty = false;
1227
1228         this.classname = 'oe_form_field_' + this.type;
1229     },
1230     start: function() {
1231         this._super.apply(this, arguments);
1232         if (this.field.translate) {
1233             this.view.translatable_fields.push(this);
1234             this.$element.find('.oe_field_translate').click(this.on_translate);
1235         }
1236         if (this.nolabel && openerp.connection.debug) {
1237             this.do_attach_tooltip(this, this.$element, {
1238                 defaultPosition: 'top'
1239             });
1240         }
1241     },
1242     set_value: function(value) {
1243         this.value = value;
1244         this.invalid = false;
1245         this.update_dom();
1246         this.on_value_changed();
1247     },
1248     set_value_from_ui: function() {
1249         this.on_value_changed();
1250     },
1251     on_value_changed: function() {
1252     },
1253     on_translate: function() {
1254         this.view.open_translate_dialog(this);
1255     },
1256     get_value: function() {
1257         return this.value;
1258     },
1259     is_valid: function() {
1260         return !this.invalid;
1261     },
1262     is_dirty: function() {
1263         return this.dirty && !this.readonly;
1264     },
1265     get_on_change_value: function() {
1266         return this.get_value();
1267     },
1268     update_dom: function() {
1269         this._super.apply(this, arguments);
1270         if (this.field.translate) {
1271             this.$element.find('.oe_field_translate').toggle(!!this.view.datarecord.id);
1272         }
1273         if (!this.disable_utility_classes) {
1274             this.$element.toggleClass('disabled', this.readonly);
1275             this.$element.toggleClass('required', this.required);
1276             if (this.view.show_invalid) {
1277                 this.$element.toggleClass('invalid', !this.is_valid());
1278             }
1279         }
1280     },
1281     on_ui_change: function() {
1282         this.dirty = true;
1283         this.validate();
1284         if (this.is_valid()) {
1285             this.set_value_from_ui();
1286             this.view.do_onchange(this);
1287             this.view.on_form_changed();
1288         } else {
1289             this.update_dom();
1290         }
1291     },
1292     validate: function() {
1293         this.invalid = false;
1294     },
1295     focus: function() {
1296     },
1297     reset: function() {
1298         this.dirty = false;
1299     }
1300 });
1301
1302 openerp.web.form.FieldChar = openerp.web.form.Field.extend({
1303     template: 'FieldChar',
1304     init: function (view, node) {
1305         this._super(view, node);
1306         this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1307     },
1308     start: function() {
1309         this._super.apply(this, arguments);
1310         this.$element.find('input').change(this.on_ui_change);
1311     },
1312     set_value: function(value) {
1313         this._super.apply(this, arguments);
1314         var show_value = openerp.web.format_value(value, this, '');
1315         this.$element.find('input').val(show_value);
1316         return show_value;
1317     },
1318     update_dom: function() {
1319         this._super.apply(this, arguments);
1320         this.$element.find('input').attr('disabled', this.readonly);
1321     },
1322     set_value_from_ui: function() {
1323         this.value = openerp.web.parse_value(this.$element.find('input').val(), this);
1324         this._super();
1325     },
1326     validate: function() {
1327         this.invalid = false;
1328         try {
1329             var value = openerp.web.parse_value(this.$element.find('input').val(), this, '');
1330             this.invalid = this.required && value === '';
1331         } catch(e) {
1332             this.invalid = true;
1333         }
1334     },
1335     focus: function() {
1336         this.$element.find('input').focus();
1337     }
1338 });
1339
1340 openerp.web.form.FieldEmail = openerp.web.form.FieldChar.extend({
1341     template: 'FieldEmail',
1342     start: function() {
1343         this._super.apply(this, arguments);
1344         this.$element.find('button').click(this.on_button_clicked);
1345     },
1346     on_button_clicked: function() {
1347         if (!this.value || !this.is_valid()) {
1348             this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1349         } else {
1350             location.href = 'mailto:' + this.value;
1351         }
1352     }
1353 });
1354
1355 openerp.web.form.FieldUrl = openerp.web.form.FieldChar.extend({
1356     template: 'FieldUrl',
1357     start: function() {
1358         this._super.apply(this, arguments);
1359         this.$element.find('button').click(this.on_button_clicked);
1360     },
1361     on_button_clicked: function() {
1362         if (!this.value) {
1363             this.do_warn("Resource error", "This resource is empty");
1364         } else {
1365             window.open(this.value);
1366         }
1367     }
1368 });
1369
1370 openerp.web.form.FieldFloat = openerp.web.form.FieldChar.extend({
1371     init: function (view, node) {
1372         this._super(view, node);
1373         if (node.attrs.digits) {
1374             this.parse_digits(node.attrs.digits);
1375         } else {
1376             this.digits = view.fields_view.fields[node.attrs.name].digits;
1377         }
1378     },
1379     parse_digits: function (digits_attr) {
1380         // could use a Python parser instead.
1381         var match = /^\s*[\(\[](\d+),\s*(\d+)/.exec(digits_attr);
1382         return [parseInt(match[1], 10), parseInt(match[2], 10)];
1383     },
1384     set_value: function(value) {
1385         if (value === false || value === undefined) {
1386             // As in GTK client, floats default to 0
1387             value = 0;
1388         }
1389         this._super.apply(this, [value]);
1390     }
1391 });
1392
1393 openerp.web.DateTimeWidget = openerp.web.Widget.extend({
1394     template: "web.datetimepicker",
1395     jqueryui_object: 'datetimepicker',
1396     type_of_date: "datetime",
1397     init: function(parent) {
1398         this._super(parent);
1399         this.name = parent.name;
1400     },
1401     start: function() {
1402         var self = this;
1403         this.$input = this.$element.find('input.oe_datepicker_master');
1404         this.$input_picker = this.$element.find('input.oe_datepicker_container');
1405         this.$input.change(this.on_change);
1406         this.picker({
1407             onSelect: this.on_picker_select,
1408             changeMonth: true,
1409             changeYear: true,
1410             showWeek: true,
1411             showButtonPanel: true
1412         });
1413         this.$element.find('img.oe_datepicker_trigger').click(function() {
1414             if (!self.readonly) {
1415                 self.picker('setDate', self.value ? openerp.web.auto_str_to_date(self.value) : new Date());
1416                 self.$input_picker.show();
1417                 self.picker('show');
1418                 self.$input_picker.hide();
1419             }
1420         });
1421         this.set_readonly(false);
1422         this.value = false;
1423     },
1424     picker: function() {
1425         return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1426     },
1427     on_picker_select: function(text, instance) {
1428         var date = this.picker('getDate');
1429         this.$input.val(date ? this.format_client(date) : '').change();
1430     },
1431     set_value: function(value) {
1432         this.value = value;
1433         this.$input.val(value ? this.format_client(value) : '');
1434     },
1435     get_value: function() {
1436         return this.value;
1437     },
1438     set_value_from_ui: function() {
1439         var value = this.$input.val() || false;
1440         this.value = this.parse_client(value);
1441     },
1442     set_readonly: function(readonly) {
1443         this.readonly = readonly;
1444         this.$input.attr('disabled', this.readonly);
1445         this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
1446     },
1447     is_valid: function(required) {
1448         var value = this.$input.val();
1449         if (value === "") {
1450             return !required;
1451         } else {
1452             try {
1453                 this.parse_client(value);
1454                 return true;
1455             } catch(e) {
1456                 return false;
1457             }
1458         }
1459     },
1460     focus: function() {
1461         this.$input.focus();
1462     },
1463     parse_client: function(v) {
1464         return openerp.web.parse_value(v, {"widget": this.type_of_date});
1465     },
1466     format_client: function(v) {
1467         return openerp.web.format_value(v, {"widget": this.type_of_date});
1468     },
1469     on_change: function() {
1470         if (this.is_valid()) {
1471             this.set_value_from_ui();
1472         }
1473     }
1474 });
1475
1476 openerp.web.DateWidget = openerp.web.DateTimeWidget.extend({
1477     jqueryui_object: 'datepicker',
1478     type_of_date: "date"
1479 });
1480
1481 openerp.web.form.FieldDatetime = openerp.web.form.Field.extend({
1482     template: "EmptyComponent",
1483     build_widget: function() {
1484         return new openerp.web.DateTimeWidget(this);
1485     },
1486     start: function() {
1487         var self = this;
1488         this._super.apply(this, arguments);
1489         this.datewidget = this.build_widget();
1490         this.datewidget.on_change.add_last(this.on_ui_change);
1491         this.datewidget.appendTo(this.$element);
1492     },
1493     set_value: function(value) {
1494         this._super(value);
1495         this.datewidget.set_value(value);
1496     },
1497     get_value: function() {
1498         return this.datewidget.get_value();
1499     },
1500     update_dom: function() {
1501         this._super.apply(this, arguments);
1502         this.datewidget.set_readonly(this.readonly);
1503     },
1504     validate: function() {
1505         this.invalid = !this.datewidget.is_valid(this.required);
1506     },
1507     focus: function() {
1508         this.datewidget.focus();
1509     }
1510 });
1511
1512 openerp.web.form.FieldDate = openerp.web.form.FieldDatetime.extend({
1513     build_widget: function() {
1514         return new openerp.web.DateWidget(this);
1515     }
1516 });
1517
1518 openerp.web.form.FieldText = openerp.web.form.Field.extend({
1519     template: 'FieldText',
1520     start: function() {
1521         this._super.apply(this, arguments);
1522         this.$element.find('textarea').change(this.on_ui_change);
1523     },
1524     set_value: function(value) {
1525         this._super.apply(this, arguments);
1526         var show_value = openerp.web.format_value(value, this, '');
1527         this.$element.find('textarea').val(show_value);
1528     },
1529     update_dom: function() {
1530         this._super.apply(this, arguments);
1531         this.$element.find('textarea').attr('disabled', this.readonly);
1532     },
1533     set_value_from_ui: function() {
1534         this.value = openerp.web.parse_value(this.$element.find('textarea').val(), this);
1535         this._super();
1536     },
1537     validate: function() {
1538         this.invalid = false;
1539         try {
1540             var value = openerp.web.parse_value(this.$element.find('textarea').val(), this, '');
1541             this.invalid = this.required && value === '';
1542         } catch(e) {
1543             this.invalid = true;
1544         }
1545     },
1546     focus: function() {
1547         this.$element.find('textarea').focus();
1548     }
1549 });
1550
1551 openerp.web.form.FieldBoolean = openerp.web.form.Field.extend({
1552     template: 'FieldBoolean',
1553     start: function() {
1554         var self = this;
1555         this._super.apply(this, arguments);
1556         this.$element.find('input').click(self.on_ui_change);
1557     },
1558     set_value: function(value) {
1559         this._super.apply(this, arguments);
1560         this.$element.find('input')[0].checked = value;
1561     },
1562     set_value_from_ui: function() {
1563         this.value = this.$element.find('input').is(':checked');
1564         this._super();
1565     },
1566     update_dom: function() {
1567         this._super.apply(this, arguments);
1568         this.$element.find('input').attr('disabled', this.readonly);
1569     },
1570     focus: function() {
1571         this.$element.find('input').focus();
1572     }
1573 });
1574
1575 openerp.web.form.FieldProgressBar = openerp.web.form.Field.extend({
1576     template: 'FieldProgressBar',
1577     start: function() {
1578         this._super.apply(this, arguments);
1579         this.$element.find('div').progressbar({
1580             value: this.value,
1581             disabled: this.readonly
1582         });
1583     },
1584     set_value: function(value) {
1585         this._super.apply(this, arguments);
1586         var show_value = Number(value);
1587         if (isNaN(show_value)) {
1588             show_value = 0;
1589         }
1590         this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(show_value + '%');
1591     }
1592 });
1593
1594 openerp.web.form.FieldTextXml = openerp.web.form.Field.extend({
1595 // to replace view editor
1596 });
1597
1598 openerp.web.form.FieldSelection = openerp.web.form.Field.extend({
1599     template: 'FieldSelection',
1600     init: function(view, node) {
1601         var self = this;
1602         this._super(view, node);
1603         this.values = this.field.selection;
1604         _.each(this.values, function(v, i) {
1605             if (v[0] === false && v[1] === '') {
1606                 self.values.splice(i, 1);
1607             }
1608         });
1609         this.values.unshift([false, '']);
1610     },
1611     start: function() {
1612         // Flag indicating whether we're in an event chain containing a change
1613         // event on the select, in order to know what to do on keyup[RETURN]:
1614         // * If the user presses [RETURN] as part of changing the value of a
1615         //   selection, we should just let the value change and not let the
1616         //   event broadcast further (e.g. to validating the current state of
1617         //   the form in editable list view, which would lead to saving the
1618         //   current row or switching to the next one)
1619         // * If the user presses [RETURN] with a select closed (side-effect:
1620         //   also if the user opened the select and pressed [RETURN] without
1621         //   changing the selected value), takes the action as validating the
1622         //   row
1623         var ischanging = false;
1624         this._super.apply(this, arguments);
1625         this.$element.find('select')
1626             .change(this.on_ui_change)
1627             .change(function () { ischanging = true; })
1628             .click(function () { ischanging = false; })
1629             .keyup(function (e) {
1630                 if (e.which !== 13 || !ischanging) { return; }
1631                 e.stopPropagation();
1632                 ischanging = false;
1633             });
1634     },
1635     set_value: function(value) {
1636         value = value === null ? false : value;
1637         value = value instanceof Array ? value[0] : value;
1638         this._super(value);
1639         var index = 0;
1640         for (var i = 0, ii = this.values.length; i < ii; i++) {
1641             if (this.values[i][0] === value) index = i;
1642         }
1643         this.$element.find('select')[0].selectedIndex = index;
1644     },
1645     set_value_from_ui: function() {
1646         this.value = this.values[this.$element.find('select')[0].selectedIndex][0];
1647         this._super();
1648     },
1649     update_dom: function() {
1650         this._super.apply(this, arguments);
1651         this.$element.find('select').attr('disabled', this.readonly);
1652     },
1653     validate: function() {
1654         var value = this.values[this.$element.find('select')[0].selectedIndex];
1655         this.invalid = !(value && !(this.required && value[0] === false));
1656     },
1657     focus: function() {
1658         this.$element.find('select').focus();
1659     }
1660 });
1661
1662 // jquery autocomplete tweak to allow html
1663 (function() {
1664     var proto = $.ui.autocomplete.prototype,
1665         initSource = proto._initSource;
1666
1667     function filter( array, term ) {
1668         var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1669         return $.grep( array, function(value) {
1670             return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1671         });
1672     }
1673
1674     $.extend( proto, {
1675         _initSource: function() {
1676             if ( this.options.html && $.isArray(this.options.source) ) {
1677                 this.source = function( request, response ) {
1678                     response( filter( this.options.source, request.term ) );
1679                 };
1680             } else {
1681                 initSource.call( this );
1682             }
1683         },
1684
1685         _renderItem: function( ul, item) {
1686             return $( "<li></li>" )
1687                 .data( "item.autocomplete", item )
1688                 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1689                 .appendTo( ul );
1690         }
1691     });
1692 })();
1693
1694 openerp.web.form.dialog = function(content, options) {
1695     options = _.extend({
1696         autoOpen: true,
1697         width: '90%',
1698         height: '90%',
1699         min_width: '800px',
1700         min_height: '600px'
1701     }, options || {});
1702     options.autoOpen = true;
1703     var dialog = new openerp.web.Dialog(null, options);
1704     dialog.$dialog = $(content).dialog(dialog.dialog_options);
1705     return dialog.$dialog;
1706 };
1707
1708 openerp.web.form.FieldMany2One = openerp.web.form.Field.extend({
1709     template: 'FieldMany2One',
1710     init: function(view, node) {
1711         this._super(view, node);
1712         this.limit = 7;
1713         this.value = null;
1714         this.cm_id = _.uniqueId('m2o_cm_');
1715         this.last_search = [];
1716         this.tmp_value = undefined;
1717     },
1718     start: function() {
1719         this._super();
1720         var self = this;
1721         this.$input = this.$element.find("input");
1722         this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1723         this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1724
1725         // context menu
1726         var init_context_menu_def = $.Deferred().then(function(e) {
1727             var rdataset = new openerp.web.DataSetStatic(self, "ir.values", self.build_context());
1728             rdataset.call("get", ['action', 'client_action_relate',
1729                 [[self.field.relation, false]], false, rdataset.get_context()], false, 0)
1730                 .then(function(result) {
1731                 self.related_entries = result;
1732
1733                 var $cmenu = $("#" + self.cm_id);
1734                 $cmenu.append(QWeb.render("FieldMany2One.context_menu", {widget: self}));
1735                 var bindings = {};
1736                 bindings[self.cm_id + "_search"] = function() {
1737                     self._search_create_popup("search");
1738                 };
1739                 bindings[self.cm_id + "_create"] = function() {
1740                     self._search_create_popup("form");
1741                 };
1742                 bindings[self.cm_id + "_open"] = function() {
1743                     if (!self.value) {
1744                         return;
1745                     }
1746                     var pop = new openerp.web.form.FormOpenPopup(self.view);
1747                     pop.show_element(self.field.relation, self.value[0],self.build_context(), {});
1748                     pop.on_write_completed.add_last(function() {
1749                         self.set_value(self.value[0]);
1750                     });
1751                 };
1752                 _.each(_.range(self.related_entries.length), function(i) {
1753                     bindings[self.cm_id + "_related_" + i] = function() {
1754                         self.open_related(self.related_entries[i]);
1755                     };
1756                 });
1757                 var cmenu = self.$menu_btn.contextMenu(self.cm_id, {'leftClickToo': true,
1758                     bindings: bindings, itemStyle: {"color": ""},
1759                     onContextMenu: function() {
1760                         if(self.value) {
1761                             $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").removeClass("oe-m2o-disabled-cm");
1762                         } else {
1763                             $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").addClass("oe-m2o-disabled-cm");
1764                         }
1765                         if (!self.readonly) {
1766                             $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").removeClass("oe-m2o-disabled-cm");
1767                         } else {
1768                             $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").addClass("oe-m2o-disabled-cm");
1769                         }
1770                         return true;
1771                     }, menuStyle: {width: "200px"}
1772                 });
1773                 setTimeout(function() {self.$menu_btn.trigger(e);}, 0);
1774             });
1775         });
1776         var ctx_callback = function(e) {init_context_menu_def.resolve(e); e.preventDefault()};
1777         this.$menu_btn.bind('contextmenu', ctx_callback);
1778         this.$menu_btn.click(ctx_callback);
1779
1780         // some behavior for input
1781         this.$input.keyup(function() {
1782             if (self.$input.val() === "") {
1783                 self._change_int_value(null);
1784             } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1785                 self._change_int_value(undefined);
1786             }
1787         });
1788         this.$drop_down.click(function() {
1789             if (self.readonly)
1790                 return;
1791             if (self.$input.autocomplete("widget").is(":visible")) {
1792                 self.$input.autocomplete("close");
1793             } else {
1794                 if (self.value) {
1795                     self.$input.autocomplete("search", "");
1796                 } else {
1797                     self.$input.autocomplete("search");
1798                 }
1799                 self.$input.focus();
1800             }
1801         });
1802         var anyoneLoosesFocus = function() {
1803             if (!self.$input.is(":focus") &&
1804                     !self.$input.autocomplete("widget").is(":visible") &&
1805                     !self.value) {
1806                 if (self.value === undefined && self.last_search.length > 0) {
1807                     self._change_int_ext_value(self.last_search[0]);
1808                 } else {
1809                     self._change_int_ext_value(null);
1810                 }
1811             }
1812         };
1813         this.$input.focusout(anyoneLoosesFocus);
1814
1815         var isSelecting = false;
1816         // autocomplete
1817         this.$input.autocomplete({
1818             source: function(req, resp) { self.get_search_result(req, resp); },
1819             select: function(event, ui) {
1820                 isSelecting = true;
1821                 var item = ui.item;
1822                 if (item.id) {
1823                     self._change_int_value([item.id, item.name]);
1824                 } else if (item.action) {
1825                     self._change_int_value(undefined);
1826                     item.action();
1827                     return false;
1828                 }
1829             },
1830             focus: function(e, ui) {
1831                 e.preventDefault();
1832             },
1833             html: true,
1834             close: anyoneLoosesFocus,
1835             minLength: 0,
1836             delay: 0
1837         });
1838         // used to correct a bug when selecting an element by pushing 'enter' in an editable list
1839         this.$input.keyup(function(e) {
1840             if (e.which === 13) {
1841                 if (isSelecting)
1842                     e.stopPropagation();
1843             }
1844             isSelecting = false;
1845         });
1846     },
1847     // autocomplete component content handling
1848     get_search_result: function(request, response) {
1849         var search_val = request.term;
1850         var self = this;
1851
1852         var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1853
1854         dataset.name_search(search_val, self.build_domain(), 'ilike',
1855                 this.limit + 1, function(data) {
1856             self.last_search = data;
1857             // possible selections for the m2o
1858             var values = _.map(data, function(x) {
1859                 return {label: $('<span />').text(x[1]).html(), name:x[1], id:x[0]};
1860             });
1861
1862             // search more... if more results that max
1863             if (values.length > self.limit) {
1864                 values = values.slice(0, self.limit);
1865                 values.push({label: _t("<em>   Search More...</em>"), action: function() {
1866                     dataset.name_search(search_val, self.build_domain(), 'ilike'
1867                     , false, function(data) {
1868                         self._change_int_value(null);
1869                         self._search_create_popup("search", data);
1870                     });
1871                 }});
1872             }
1873             // quick create
1874             var raw_result = _(data.result).map(function(x) {return x[1];});
1875             if (search_val.length > 0 &&
1876                 !_.include(raw_result, search_val) &&
1877                 (!self.value || search_val !== self.value[1])) {
1878                 values.push({label: _.str.sprintf(_t('<em>   Create "<strong>%s</strong>"</em>'),
1879                         $('<span />').text(search_val).html()), action: function() {
1880                     self._quick_create(search_val);
1881                 }});
1882             }
1883             // create...
1884             values.push({label: _t("<em>   Create and Edit...</em>"), action: function() {
1885                 self._change_int_value(null);
1886                 self._search_create_popup("form", undefined, {"default_name": search_val});
1887             }});
1888
1889             response(values);
1890         });
1891     },
1892     _quick_create: function(name) {
1893         var self = this;
1894         var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1895         dataset.name_create(name, function(data) {
1896             self._change_int_ext_value(data);
1897         }).fail(function(error, event) {
1898             event.preventDefault();
1899             self._change_int_value(null);
1900             self._search_create_popup("form", undefined, {"default_name": name});
1901         });
1902     },
1903     // all search/create popup handling
1904     _search_create_popup: function(view, ids, context) {
1905         var self = this;
1906         var pop = new openerp.web.form.SelectCreatePopup(this);
1907         pop.select_element(self.field.relation,{
1908                 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
1909                 initial_view: view,
1910                 disable_multiple_selection: true
1911                 }, self.build_domain(),
1912                 new openerp.web.CompoundContext(self.build_context(), context || {}));
1913         pop.on_select_elements.add(function(element_ids) {
1914             var dataset = new openerp.web.DataSetStatic(self, self.field.relation, self.build_context());
1915             dataset.name_get([element_ids[0]], function(data) {
1916                 self._change_int_ext_value(data[0]);
1917             });
1918         });
1919     },
1920     _change_int_ext_value: function(value) {
1921         this._change_int_value(value);
1922         this.$input.val(this.value ? this.value[1] : "");
1923     },
1924     _change_int_value: function(value) {
1925         this.value = value;
1926         var back_orig_value = this.original_value;
1927         if (this.value === null || this.value) {
1928             this.original_value = this.value;
1929         }
1930         if (back_orig_value === undefined) { // first use after a set_value()
1931             return;
1932         }
1933         if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
1934                 !== (this.value ? this.value[0] : null))) {
1935             this.on_ui_change();
1936         }
1937     },
1938     set_value: function(value) {
1939         value = value || null;
1940         this.invalid = false;
1941         var self = this;
1942         this.tmp_value = value;
1943         self.update_dom();
1944         self.on_value_changed();
1945         var real_set_value = function(rval) {
1946             self.tmp_value = undefined;
1947             self.value = rval;
1948             self.original_value = undefined;
1949             self._change_int_ext_value(rval);
1950         };
1951         if (value && !(value instanceof Array)) {
1952             var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1953             dataset.name_get([value], function(data) {
1954                 real_set_value(data[0]);
1955             }).fail(function() {self.tmp_value = undefined;});
1956         } else {
1957             setTimeout(function() {real_set_value(value);}, 0);
1958         }
1959     },
1960     get_value: function() {
1961         if (this.tmp_value !== undefined) {
1962             if (this.tmp_value instanceof Array) {
1963                 return this.tmp_value[0];
1964             }
1965             return this.tmp_value ? this.tmp_value : false;
1966         }
1967         if (this.value === undefined)
1968             return this.original_value ? this.original_value[0] : false;
1969         return this.value ? this.value[0] : false;
1970     },
1971     validate: function() {
1972         this.invalid = false;
1973         var val = this.tmp_value !== undefined ? this.tmp_value : this.value;
1974         if (val === null) {
1975             this.invalid = this.required;
1976         }
1977     },
1978     open_related: function(related) {
1979         var self = this;
1980         if (!self.value)
1981             return;
1982         var additional_context = {
1983                 active_id: self.value[0],
1984                 active_ids: [self.value[0]],
1985                 active_model: self.field.relation
1986         };
1987         self.rpc("/web/action/load", {
1988             action_id: related[2].id,
1989             context: additional_context
1990         }, function(result) {
1991             result.result.context = _.extend(result.result.context || {}, additional_context);
1992             self.do_action(result.result);
1993         });
1994     },
1995     focus: function () {
1996         this.$input.focus();
1997     },
1998     update_dom: function() {
1999         this._super.apply(this, arguments);
2000         this.$input.attr('disabled', this.readonly);
2001     }
2002 });
2003
2004 /*
2005 # Values: (0, 0,  { fields })    create
2006 #         (1, ID, { fields })    update
2007 #         (2, ID)                remove (delete)
2008 #         (3, ID)                unlink one (target id or target of relation)
2009 #         (4, ID)                link
2010 #         (5)                    unlink all (only valid for one2many)
2011 */
2012 var commands = {
2013     // (0, _, {values})
2014     CREATE: 0,
2015     'create': function (values) {
2016         return [commands.CREATE, false, values];
2017     },
2018     // (1, id, {values})
2019     UPDATE: 1,
2020     'update': function (id, values) {
2021         return [commands.UPDATE, id, values];
2022     },
2023     // (2, id[, _])
2024     DELETE: 2,
2025     'delete': function (id) {
2026         return [commands.DELETE, id, false];
2027     },
2028     // (3, id[, _]) removes relation, but not linked record itself
2029     FORGET: 3,
2030     'forget': function (id) {
2031         return [commands.FORGET, id, false];
2032     },
2033     // (4, id[, _])
2034     LINK_TO: 4,
2035     'link_to': function (id) {
2036         return [commands.LINK_TO, id, false];
2037     },
2038     // (5[, _[, _]])
2039     DELETE_ALL: 5,
2040     'delete_all': function () {
2041         return [5, false, false];
2042     },
2043     // (6, _, ids) replaces all linked records with provided ids
2044     REPLACE_WITH: 6,
2045     'replace_with': function (ids) {
2046         return [6, false, ids];
2047     }
2048 };
2049 openerp.web.form.FieldOne2Many = openerp.web.form.Field.extend({
2050     template: 'FieldOne2Many',
2051     multi_selection: false,
2052     init: function(view, node) {
2053         this._super(view, node);
2054         this.is_loaded = $.Deferred();
2055         this.initial_is_loaded = this.is_loaded;
2056         this.is_setted = $.Deferred();
2057         this.form_last_update = $.Deferred();
2058         this.init_form_last_update = this.form_last_update;
2059         this.disable_utility_classes = true;
2060     },
2061     start: function() {
2062         this._super.apply(this, arguments);
2063
2064         var self = this;
2065
2066         this.dataset = new openerp.web.form.One2ManyDataSet(this, this.field.relation);
2067         this.dataset.o2m = this;
2068         this.dataset.parent_view = this.view;
2069         this.dataset.on_change.add_last(function() {
2070             self.on_ui_change();
2071         });
2072
2073         this.is_setted.then(function() {
2074             self.load_views();
2075         });
2076     },
2077     is_readonly: function() {
2078         return this.readonly || this.force_readonly;
2079     },
2080     load_views: function() {
2081         var self = this;
2082         
2083         var modes = this.node.attrs.mode;
2084         modes = !!modes ? modes.split(",") : ["tree"];
2085         var views = [];
2086         _.each(modes, function(mode) {
2087             var view = {
2088                 view_id: false,
2089                 view_type: mode == "tree" ? "list" : mode,
2090                 options: { sidebar : false }
2091             };
2092             if (self.field.views && self.field.views[mode]) {
2093                 view.embedded_view = self.field.views[mode];
2094             }
2095             if(view.view_type === "list") {
2096                 view.options.selectable = self.multi_selection;
2097                 if (self.is_readonly()) {
2098                     view.options.addable = null;
2099                     view.options.deletable = null;
2100                 }
2101             } else if (view.view_type === "form") {
2102                 view.options.not_interactible_on_create = true;
2103             }
2104             views.push(view);
2105         });
2106         this.views = views;
2107         
2108         this.viewmanager = new openerp.web.ViewManager(this, this.dataset, views);
2109         this.viewmanager.registry = openerp.web.views.clone({
2110             list: 'openerp.web.form.One2ManyListView',
2111             form: 'openerp.web.FormView'
2112         });
2113         var once = $.Deferred().then(function() {
2114             self.init_form_last_update.resolve();
2115         });
2116         var def = $.Deferred().then(function() {
2117             self.initial_is_loaded.resolve();
2118         });
2119         this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2120             if (view_type == "list") {
2121                 controller.o2m = self;
2122                 if (self.is_readonly())
2123                     controller.set_editable(false);
2124             } else if (view_type == "form") {
2125                 if (self.is_readonly()) {
2126                     controller.on_toggle_readonly();
2127                     $(controller.$element.find(".oe_form_buttons")[0]).children().remove();
2128                 }
2129                 controller.on_record_loaded.add_last(function() {
2130                     once.resolve();
2131                 });
2132                 controller.on_pager_action.add_first(function() {
2133                     self.save_any_view();
2134                 });
2135                 controller.$element.find(".oe_form_button_save").hide();
2136             } else if (view_type == "graph") {
2137                 self.reload_current_view()
2138             }
2139             def.resolve();
2140         });
2141         this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2142             $.when(self.save_any_view()).then(function() {
2143                 if(n_mode === "list")
2144                     setTimeout(function() {self.reload_current_view();}, 0);
2145             });
2146         });
2147         this.is_setted.then(function() {
2148             setTimeout(function () {
2149                 self.viewmanager.appendTo(self.$element);
2150             }, 0);
2151         });
2152         return def;
2153     },
2154     reload_current_view: function() {
2155         var self = this;
2156         return self.is_loaded = self.is_loaded.pipe(function() {
2157             var view = self.viewmanager.views[self.viewmanager.active_view].controller;
2158             if(self.viewmanager.active_view === "list") {
2159                 return view.reload_content();
2160             } else if (self.viewmanager.active_view === "form") {
2161                 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2162                     self.dataset.index = 0;
2163                 }
2164                 var act = function() {
2165                     return view.do_show();
2166                 }
2167                 self.form_last_update = self.form_last_update.pipe(act, act);
2168                 return self.form_last_update;
2169             } else if (self.viewmanager.active_view === "graph") {
2170                 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2171             }
2172         });
2173     },
2174     set_value: function(value) {
2175         value = value || [];
2176         var self = this;
2177         this.dataset.reset_ids([]);
2178         if(value.length >= 1 && value[0] instanceof Array) {
2179             var ids = [];
2180             _.each(value, function(command) {
2181                 var obj = {values: command[2]};
2182                 switch (command[0]) {
2183                     case commands.CREATE:
2184                         obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2185                         obj.defaults = {};
2186                         self.dataset.to_create.push(obj);
2187                         self.dataset.cache.push(_.clone(obj));
2188                         ids.push(obj.id);
2189                         return;
2190                     case commands.UPDATE:
2191                         obj['id'] = command[1];
2192                         self.dataset.to_write.push(obj);
2193                         self.dataset.cache.push(_.clone(obj));
2194                         ids.push(obj.id);
2195                         return;
2196                     case commands.DELETE:
2197                         self.dataset.to_delete.push({id: command[1]});
2198                         return;
2199                     case commands.LINK_TO:
2200                         ids.push(command[1]);
2201                         return;
2202                     case commands.DELETE_ALL:
2203                         self.dataset.delete_all = true;
2204                         return;
2205                 }
2206             });
2207             this._super(ids);
2208             this.dataset.set_ids(ids);
2209         } else if (value.length >= 1 && typeof(value[0]) === "object") {
2210             var ids = [];
2211             this.dataset.delete_all = true;
2212             _.each(value, function(command) {
2213                 var obj = {values: command};
2214                 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2215                 obj.defaults = {};
2216                 self.dataset.to_create.push(obj);
2217                 self.dataset.cache.push(_.clone(obj));
2218                 ids.push(obj.id);
2219             });
2220             this._super(ids);
2221             this.dataset.set_ids(ids);
2222         } else {
2223             this._super(value);
2224             this.dataset.reset_ids(value);
2225         }
2226         if (this.dataset.index === null && this.dataset.ids.length > 0) {
2227             this.dataset.index = 0;
2228         }
2229         self.is_setted.resolve();
2230         return self.reload_current_view();
2231     },
2232     get_value: function() {
2233         var self = this;
2234         if (!this.dataset)
2235             return [];
2236         var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2237         val = val.concat(_.map(this.dataset.ids, function(id) {
2238             var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2239             if (alter_order) {
2240                 return commands.create(alter_order.values);
2241             }
2242             alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2243             if (alter_order) {
2244                 return commands.update(alter_order.id, alter_order.values);
2245             }
2246             return commands.link_to(id);
2247         }));
2248         return val.concat(_.map(
2249             this.dataset.to_delete, function(x) {
2250                 return commands['delete'](x.id);}));
2251     },
2252     save_any_view: function() {
2253         if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2254             this.viewmanager.views[this.viewmanager.active_view] &&
2255             this.viewmanager.views[this.viewmanager.active_view].controller) {
2256             var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2257             if (this.viewmanager.active_view === "form") {
2258                 var res = $.when(view.do_save());
2259                 // it seems line there are some cases when this happens
2260                 /*if (!res.isResolved() && !res.isRejected()) {
2261                     console.warn("Asynchronous get_value() is not supported in form view.");
2262                 }*/
2263                 return res;
2264             } else if (this.viewmanager.active_view === "list") {
2265                 var res = $.when(view.ensure_saved());
2266                 // it seems line there are some cases when this happens
2267                 /*if (!res.isResolved() && !res.isRejected()) {
2268                     console.warn("Asynchronous get_value() is not supported in list view.");
2269                 }*/
2270                 return res;
2271             }
2272         }
2273         return false;
2274     },
2275     is_valid: function() {
2276         this.validate();
2277         return this._super();
2278     },
2279     validate: function() {
2280         this.invalid = false;
2281         if (!this.viewmanager.views[this.viewmanager.active_view])
2282             return;
2283         var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2284         if (this.viewmanager.active_view === "form") {
2285             for (var f in view.fields) {
2286                 f = view.fields[f];
2287                 if (!f.is_valid()) {
2288                     this.invalid = true;
2289                     return;
2290                 }
2291             }
2292         }
2293     },
2294     is_dirty: function() {
2295         this.save_any_view();
2296         return this._super();
2297     },
2298     update_dom: function() {
2299         this._super.apply(this, arguments);
2300         var self = this;
2301         if (this.previous_readonly !== this.readonly) {
2302             this.previous_readonly = this.readonly;
2303             if (this.viewmanager) {
2304                 this.is_loaded = this.is_loaded.pipe(function() {
2305                     self.viewmanager.stop();
2306                     return $.when(self.load_views()).then(function() {
2307                         self.reload_current_view();
2308                     });
2309                 });
2310             }
2311         }
2312     }
2313 });
2314
2315 openerp.web.form.One2ManyDataSet = openerp.web.BufferedDataSet.extend({
2316     get_context: function() {
2317         this.context = this.o2m.build_context();
2318         return this.context;
2319     }
2320 });
2321
2322 openerp.web.form.One2ManyListView = openerp.web.ListView.extend({
2323     do_add_record: function () {
2324         if (this.options.editable) {
2325             this._super.apply(this, arguments);
2326         } else {
2327             var self = this;
2328             var pop = new openerp.web.form.SelectCreatePopup(this);
2329             pop.on_default_get.add(self.dataset.on_default_get);
2330             pop.select_element(self.o2m.field.relation,{
2331                 initial_view: "form",
2332                 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2333                 create_function: function(data, callback, error_callback) {
2334                     return self.o2m.dataset.create(data).then(function(r) {
2335                         self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2336                         self.o2m.dataset.on_change();
2337                     }).then(callback, error_callback);
2338                 },
2339                 read_function: function() {
2340                     return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2341                 },
2342                 parent_view: self.o2m.view,
2343                 form_view_options: {'not_interactible_on_create':true}
2344             }, self.o2m.build_domain(), self.o2m.build_context());
2345             pop.on_select_elements.add_last(function() {
2346                 self.o2m.reload_current_view();
2347             });
2348         }
2349     },
2350     do_activate_record: function(index, id) {
2351         var self = this;
2352         var pop = new openerp.web.form.FormOpenPopup(self.o2m.view);
2353         pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(),{
2354             auto_write: false,
2355             alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2356             parent_view: self.o2m.view,
2357             read_function: function() {
2358                 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2359             },
2360             form_view_options: {'not_interactible_on_create':true},
2361             readonly: self.o2m.is_readonly()
2362         });
2363         pop.on_write.add(function(id, data) {
2364             self.o2m.dataset.write(id, data, {}, function(r) {
2365                 self.o2m.reload_current_view();
2366             });
2367         });
2368     }
2369 });
2370
2371 openerp.web.form.FieldMany2Many = openerp.web.form.Field.extend({
2372     template: 'FieldMany2Many',
2373     multi_selection: false,
2374     init: function(view, node) {
2375         this._super(view, node);
2376         this.list_id = _.uniqueId("many2many");
2377         this.is_loaded = $.Deferred();
2378         this.initial_is_loaded = this.is_loaded;
2379         this.is_setted = $.Deferred();
2380     },
2381     start: function() {
2382         this._super.apply(this, arguments);
2383
2384         var self = this;
2385
2386         this.dataset = new openerp.web.form.Many2ManyDataSet(this, this.field.relation);
2387         this.dataset.m2m = this;
2388         this.dataset.on_unlink.add_last(function(ids) {
2389             self.on_ui_change();
2390         });
2391         
2392         this.is_setted.then(function() {
2393             self.load_view();
2394         });
2395     },
2396     set_value: function(value) {
2397         value = value || [];
2398         if (value.length >= 1 && value[0] instanceof Array) {
2399             value = value[0][2];
2400         }
2401         this._super(value);
2402         this.dataset.set_ids(value);
2403         var self = this;
2404         self.reload_content();
2405         this.is_setted.resolve();
2406     },
2407     get_value: function() {
2408         return [commands.replace_with(this.dataset.ids)];
2409     },
2410     validate: function() {
2411         this.invalid = false;
2412     },
2413     is_readonly: function() {
2414         return this.readonly || this.force_readonly;
2415     },
2416     load_view: function() {
2417         var self = this;
2418         this.list_view = new openerp.web.form.Many2ManyListView(this, this.dataset, false, {
2419                     'addable': self.is_readonly() ? null : 'Add',
2420                     'deletable': self.is_readonly() ? false : true,
2421                     'selectable': self.multi_selection
2422             });
2423         var embedded = (this.field.views || {}).tree;
2424         if (embedded) {
2425             this.list_view.set_embedded_view(embedded);
2426         }
2427         this.list_view.m2m_field = this;
2428         var loaded = $.Deferred();
2429         this.list_view.on_loaded.add_last(function() {
2430             self.initial_is_loaded.resolve();
2431             loaded.resolve();
2432         });
2433         setTimeout(function () {
2434             self.list_view.appendTo($("#" + self.list_id));
2435         }, 0);
2436         return loaded;
2437     },
2438     reload_content: function() {
2439         var self = this;
2440         this.is_loaded = this.is_loaded.pipe(function() {
2441             return self.list_view.reload_content();
2442         });
2443     },
2444     update_dom: function() {
2445         this._super.apply(this, arguments);
2446         var self = this;
2447         if (this.previous_readonly !== this.readonly) {
2448             this.previous_readonly = this.readonly;
2449             if (this.list_view) {
2450                 this.is_loaded = this.is_loaded.pipe(function() {
2451                     self.list_view.stop();
2452                     return $.when(self.load_view()).then(function() {
2453                         self.reload_content();
2454                     });
2455                 });
2456             }
2457         }
2458     }
2459 });
2460
2461 openerp.web.form.Many2ManyDataSet = openerp.web.DataSetStatic.extend({
2462     get_context: function() {
2463         this.context = this.m2m.build_context();
2464         return this.context;
2465     }
2466 });
2467
2468 /**
2469  * @class
2470  * @extends openerp.web.ListView
2471  */
2472 openerp.web.form.Many2ManyListView = openerp.web.ListView.extend(/** @lends openerp.web.form.Many2ManyListView# */{
2473     do_add_record: function () {
2474         var pop = new openerp.web.form.SelectCreatePopup(this);
2475         pop.select_element(this.model, {},
2476             new openerp.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
2477             this.m2m_field.build_context());
2478         var self = this;
2479         pop.on_select_elements.add(function(element_ids) {
2480             _.each(element_ids, function(element_id) {
2481                 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
2482                     self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
2483                     self.m2m_field.on_ui_change();
2484                     self.reload_content();
2485                 }
2486             });
2487         });
2488     },
2489     do_activate_record: function(index, id) {
2490         var self = this;
2491         var pop = new openerp.web.form.FormOpenPopup(this);
2492         pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {});
2493         pop.on_write_completed.add_last(function() {
2494             self.reload_content();
2495         });
2496     }
2497 });
2498
2499 /**
2500  * @class
2501  * @extends openerp.web.OldWidget
2502  */
2503 openerp.web.form.SelectCreatePopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.SelectCreatePopup# */{
2504     identifier_prefix: "selectcreatepopup",
2505     template: "SelectCreatePopup",
2506     /**
2507      * options:
2508      * - initial_ids
2509      * - initial_view: form or search (default search)
2510      * - disable_multiple_selection
2511      * - alternative_form_view
2512      * - create_function (defaults to a naive saving behavior)
2513      * - parent_view
2514      * - form_view_options
2515      * - list_view_options
2516      * - read_function
2517      */
2518     select_element: function(model, options, domain, context) {
2519         var self = this;
2520         this.model = model;
2521         this.domain = domain || [];
2522         this.context = context || {};
2523         this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
2524             return self.create_row.apply(self, arguments);
2525         }, read_function: null});
2526         this.initial_ids = this.options.initial_ids;
2527         this.created_elements = [];
2528         this.render_element();
2529         openerp.web.form.dialog(this.$element, {close:function() {
2530             self.check_exit();
2531         }});
2532         this.start();
2533     },
2534     start: function() {
2535         this._super();
2536         var self = this;
2537         search_defaults = {};
2538         this.dataset = new openerp.web.ProxyDataSet(this, this.model,
2539             this.context);
2540         this.dataset.create_function = function() {
2541             return self.options.create_function.apply(null, arguments).then(function(r) {
2542                 self.created_elements.push(r.result);
2543             });
2544         };
2545         this.dataset.write_function = function() {
2546             return self.write_row.apply(self, arguments);
2547         };
2548         this.dataset.read_function = this.options.read_function;
2549         this.dataset.parent_view = this.options.parent_view;
2550         this.dataset.on_default_get.add(this.on_default_get);
2551         if (this.options.initial_view == "search") {
2552             self.rpc('/web/session/eval_domain_and_context', {
2553                     domains: []  ,
2554                     contexts: [this.context],
2555                 }, function (results) {           
2556                     _.each(results.context, function (value, key) {
2557                         var match = /^search_default_(.*)$/.exec(key);
2558                         if (match) {
2559                             search_defaults[match[1]] = value;
2560                         }
2561                     });
2562                     self.setup_search_view(search_defaults);
2563             });
2564         } else { // "form"
2565             this.new_object();
2566         }
2567     },
2568     setup_search_view: function(search_defaults) {
2569         var self = this;
2570         if (this.searchview) {
2571             this.searchview.stop();
2572         }
2573         this.searchview = new openerp.web.SearchView(this,
2574                 this.dataset, false,  search_defaults);
2575         this.searchview.on_search.add(function(domains, contexts, groupbys) {
2576             if (self.initial_ids) {
2577                 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
2578                     contexts, groupbys);
2579                 self.initial_ids = undefined;
2580             } else {
2581                 self.do_search(domains.concat([self.domain]), contexts, groupbys);
2582             }
2583         });
2584         this.searchview.on_loaded.add_last(function () {
2585             var $buttons = self.searchview.$element.find(".oe_search-view-buttons");
2586             $buttons.append(QWeb.render("SelectCreatePopup.search.buttons"));
2587             var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
2588             $cbutton.click(function() {
2589                 self.stop();
2590             });
2591             var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
2592             if(self.options.disable_multiple_selection) {
2593                 $sbutton.hide();
2594             }
2595             $sbutton.click(function() {
2596                 self.on_select_elements(self.selected_ids);
2597                 self.stop();
2598             });
2599             self.view_list = new openerp.web.form.SelectCreateListView(self,
2600                     self.dataset, false,
2601                     _.extend({'deletable': false,
2602                         'selectable': !self.options.disable_multiple_selection
2603                     }, self.options.list_view_options || {}));
2604             self.view_list.popup = self;
2605             self.view_list.appendTo($("#" + self.element_id + "_view_list")).pipe(function() {
2606                 self.view_list.do_show();
2607             }).pipe(function() {
2608                 self.searchview.do_search();
2609             });
2610         });
2611         this.searchview.appendTo($("#" + this.element_id + "_search"));
2612     },
2613     do_search: function(domains, contexts, groupbys) {
2614         var self = this;
2615         this.rpc('/web/session/eval_domain_and_context', {
2616             domains: domains || [],
2617             contexts: contexts || [],
2618             group_by_seq: groupbys || []
2619         }, function (results) {
2620             self.view_list.do_search(results.domain, results.context, results.group_by);
2621         });
2622     },
2623     create_row: function() {
2624         var self = this;
2625         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2626         wdataset.parent_view = this.options.parent_view;
2627         return wdataset.create.apply(wdataset, arguments);
2628     },
2629     write_row: function() {
2630         var self = this;
2631         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2632         wdataset.parent_view = this.options.parent_view;
2633         return wdataset.write.apply(wdataset, arguments);
2634     },
2635     on_select_elements: function(element_ids) {
2636     },
2637     on_click_element: function(ids) {
2638         this.selected_ids = ids || [];
2639         if(this.selected_ids.length > 0) {
2640             this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
2641         } else {
2642             this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
2643         }
2644     },
2645     new_object: function() {
2646         var self = this;
2647         if (this.searchview) {
2648             this.searchview.hide();
2649         }
2650         if (this.view_list) {
2651             this.view_list.$element.hide();
2652         }
2653         this.dataset.index = null;
2654         this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
2655         if (this.options.alternative_form_view) {
2656             this.view_form.set_embedded_view(this.options.alternative_form_view);
2657         }
2658         this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2659         this.view_form.on_loaded.add_last(function() {
2660             var $buttons = self.view_form.$element.find(".oe_form_buttons");
2661             $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
2662             var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
2663             $nbutton.click(function() {
2664                 $.when(self.view_form.do_save()).then(function() {
2665                     self.view_form.reload_lock.then(function() {
2666                         self.view_form.on_button_new();
2667                     });
2668                 });
2669             });
2670             var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
2671             $nbutton.click(function() {
2672                 $.when(self.view_form.do_save()).then(function() {
2673                     self.view_form.reload_lock.then(function() {
2674                         self.check_exit();
2675                     });
2676                 });
2677             });
2678             var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
2679             $cbutton.click(function() {
2680                 self.check_exit();
2681             });
2682         });
2683         this.view_form.do_show();
2684     },
2685     check_exit: function() {
2686         if (this.created_elements.length > 0) {
2687             this.on_select_elements(this.created_elements);
2688         }
2689         this.stop();
2690     },
2691     on_default_get: function(res) {}
2692 });
2693
2694 openerp.web.form.SelectCreateListView = openerp.web.ListView.extend({
2695     do_add_record: function () {
2696         this.popup.new_object();
2697     },
2698     select_record: function(index) {
2699         this.popup.on_select_elements([this.dataset.ids[index]]);
2700         this.popup.stop();
2701     },
2702     do_select: function(ids, records) {
2703         this._super(ids, records);
2704         this.popup.on_click_element(ids);
2705     }
2706 });
2707
2708 /**
2709  * @class
2710  * @extends openerp.web.OldWidget
2711  */
2712 openerp.web.form.FormOpenPopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.FormOpenPopup# */{
2713     identifier_prefix: "formopenpopup",
2714     template: "FormOpenPopup",
2715     /**
2716      * options:
2717      * - alternative_form_view
2718      * - auto_write (default true)
2719      * - read_function
2720      * - parent_view
2721      * - form_view_options
2722      * - readonly
2723      */
2724     show_element: function(model, row_id, context, options) {
2725         this.model = model;
2726         this.row_id = row_id;
2727         this.context = context || {};
2728         this.options = _.defaults(options || {}, {"auto_write": true});
2729         this.render_element();
2730         this.$element.dialog({title: '',
2731                     modal: true,
2732                     width: 960,
2733                     height: 600});
2734         this.start();
2735     },
2736     start: function() {
2737         this._super();
2738         this.dataset = new openerp.web.form.FormOpenDataset(this, this.model, this.context);
2739         this.dataset.fop = this;
2740         this.dataset.ids = [this.row_id];
2741         this.dataset.index = 0;
2742         this.dataset.parent_view = this.options.parent_view;
2743         this.setup_form_view();
2744     },
2745     on_write: function(id, data) {
2746         if (!this.options.auto_write)
2747             return;
2748         var self = this;
2749         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2750         wdataset.parent_view = this.options.parent_view;
2751         wdataset.write(id, data, {}, function(r) {
2752             self.on_write_completed();
2753         });
2754     },
2755     on_write_completed: function() {},
2756     setup_form_view: function() {
2757         var self = this;
2758         this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
2759         if (this.options.alternative_form_view) {
2760             this.view_form.set_embedded_view(this.options.alternative_form_view);
2761         }
2762         this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2763         var once = $.Deferred().then(function() {
2764             if (self.options.readonly) {
2765                 self.view_form.on_toggle_readonly();
2766             }
2767         });
2768         this.view_form.on_loaded.add_last(function() {
2769             once.resolve();
2770             var $buttons = self.view_form.$element.find(".oe_form_buttons");
2771             $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
2772             var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
2773             $nbutton.click(function() {
2774                 self.view_form.do_save().then(function() {
2775                     self.stop();
2776                 });
2777             });
2778             var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
2779             $cbutton.click(function() {
2780                 self.stop();
2781             });
2782             if (self.options.readonly) {
2783                 $nbutton.hide();
2784                 $cbutton.text(_t("Close"));
2785             }
2786             self.view_form.do_show();
2787         });
2788         this.dataset.on_write.add(this.on_write);
2789     }
2790 });
2791
2792 openerp.web.form.FormOpenDataset = openerp.web.ProxyDataSet.extend({
2793     read_ids: function() {
2794         if (this.fop.options.read_function) {
2795             return this.fop.options.read_function.apply(null, arguments);
2796         } else {
2797             return this._super.apply(this, arguments);
2798         }
2799     }
2800 });
2801
2802 openerp.web.form.FieldReference = openerp.web.form.Field.extend({
2803     template: 'FieldReference',
2804     init: function(view, node) {
2805         this._super(view, node);
2806         this.fields_view = {
2807             fields: {
2808                 selection: {
2809                     selection: view.fields_view.fields[this.name].selection
2810                 },
2811                 m2o: {
2812                     relation: null
2813                 }
2814             }
2815         };
2816         this.get_fields_values = view.get_fields_values;
2817         this.do_onchange = this.on_form_changed = this.on_nop;
2818         this.dataset = this.view.dataset;
2819         this.widgets_counter = 0;
2820         this.view_id = 'reference_' + _.uniqueId();
2821         this.widgets = {};
2822         this.fields = {};
2823         this.selection = new openerp.web.form.FieldSelection(this, { attrs: {
2824             name: 'selection',
2825             widget: 'selection'
2826         }});
2827         this.selection.on_value_changed.add_last(this.on_selection_changed);
2828         this.m2o = new openerp.web.form.FieldMany2One(this, { attrs: {
2829             name: 'm2o',
2830             widget: 'many2one'
2831         }});
2832     },
2833     on_nop: function() {
2834     },
2835     on_selection_changed: function() {
2836         var sel = this.selection.get_value();
2837         this.m2o.field.relation = sel;
2838         this.m2o.set_value(null);
2839         this.m2o.$element.toggle(sel !== false);
2840     },
2841     start: function() {
2842         this._super();
2843         this.selection.start();
2844         this.m2o.start();
2845     },
2846     is_valid: function() {
2847         return this.required === false || typeof(this.get_value()) === 'string';
2848     },
2849     is_dirty: function() {
2850         return this.selection.is_dirty() || this.m2o.is_dirty();
2851     },
2852     set_value: function(value) {
2853         this._super(value);
2854         if (typeof(value) === 'string') {
2855             var vals = value.split(',');
2856             this.selection.set_value(vals[0]);
2857             this.m2o.set_value(parseInt(vals[1], 10));
2858         }
2859     },
2860     get_value: function() {
2861         var model = this.selection.get_value(),
2862             id = this.m2o.get_value();
2863         if (typeof(model) === 'string' && typeof(id) === 'number') {
2864             return model + ',' + id;
2865         } else {
2866             return false;
2867         }
2868     }
2869 });
2870
2871 openerp.web.form.FieldBinary = openerp.web.form.Field.extend({
2872     init: function(view, node) {
2873         this._super(view, node);
2874         this.iframe = this.element_id + '_iframe';
2875         this.binary_value = false;
2876     },
2877     start: function() {
2878         this._super.apply(this, arguments);
2879         this.$element.find('input.oe-binary-file').change(this.on_file_change);
2880         this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
2881         this.$element.find('.oe-binary-file-clear').click(this.on_clear);
2882     },
2883     human_filesize : function(size) {
2884         var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
2885         var i = 0;
2886         while (size >= 1024) {
2887             size /= 1024;
2888             ++i;
2889         }
2890         return size.toFixed(2) + ' ' + units[i];
2891     },
2892     on_file_change: function(e) {
2893         // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
2894         // http://www.html5rocks.com/tutorials/file/dndfiles/
2895         // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
2896         window[this.iframe] = this.on_file_uploaded;
2897         if ($(e.target).val() != '') {
2898             this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
2899             this.$element.find('form.oe-binary-form').submit();
2900             this.$element.find('.oe-binary-progress').show();
2901             this.$element.find('.oe-binary').hide();
2902         }
2903     },
2904     on_file_uploaded: function(size, name, content_type, file_base64) {
2905         delete(window[this.iframe]);
2906         if (size === false) {
2907             this.do_warn("File Upload", "There was a problem while uploading your file");
2908             // TODO: use openerp web crashmanager
2909             console.warn("Error while uploading file : ", name);
2910         } else {
2911             this.on_file_uploaded_and_valid.apply(this, arguments);
2912             this.on_ui_change();
2913         }
2914         this.$element.find('.oe-binary-progress').hide();
2915         this.$element.find('.oe-binary').show();
2916     },
2917     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
2918     },
2919     on_save_as: function() {
2920         var url = '/web/binary/saveas?session_id=' + this.session.session_id + '&model=' +
2921             this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name +
2922             '&fieldname=' + (this.node.attrs.filename || '') + '&t=' + (new Date().getTime());
2923         window.open(url);
2924     },
2925     on_clear: function() {
2926         if (this.value !== false) {
2927             this.value = false;
2928             this.binary_value = false;
2929             this.on_ui_change();
2930         }
2931         return false;
2932     }
2933 });
2934
2935 openerp.web.form.FieldBinaryFile = openerp.web.form.FieldBinary.extend({
2936     template: 'FieldBinaryFile',
2937     update_dom: function() {
2938         this._super.apply(this, arguments);
2939         this.$element.find('.oe-binary-file-set, .oe-binary-file-clear').toggle(!this.readonly);
2940         this.$element.find('input[type=text]').attr('disabled', this.readonly);
2941     },
2942     set_value: function(value) {
2943         this._super.apply(this, arguments);
2944         var show_value = (value != null && value !== false) ? value : '';
2945         this.$element.find('input').eq(0).val(show_value);
2946     },
2947     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
2948         this.value = file_base64;
2949         this.binary_value = true;
2950         var show_value = this.human_filesize(size);
2951         this.$element.find('input').eq(0).val(show_value);
2952         this.set_filename(name);
2953     },
2954     set_filename: function(value) {
2955         var filename = this.node.attrs.filename;
2956         if (this.view.fields[filename]) {
2957             this.view.fields[filename].set_value(value);
2958             this.view.fields[filename].on_ui_change();
2959         }
2960     },
2961     on_clear: function() {
2962         this._super.apply(this, arguments);
2963         this.$element.find('input').eq(0).val('');
2964         this.set_filename('');
2965     }
2966 });
2967
2968 openerp.web.form.FieldBinaryImage = openerp.web.form.FieldBinary.extend({
2969     template: 'FieldBinaryImage',
2970     start: function() {
2971         this._super.apply(this, arguments);
2972         this.$image = this.$element.find('img.oe-binary-image');
2973     },
2974     update_dom: function() {
2975         this._super.apply(this, arguments);
2976         this.$element.find('.oe-binary').toggle(!this.readonly);
2977     },
2978     set_value: function(value) {
2979         this._super.apply(this, arguments);
2980         this.set_image_maxwidth();
2981         var url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
2982             this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
2983         this.$image.attr('src', url);
2984     },
2985     set_image_maxwidth: function() {
2986         this.$image.css('max-width', this.$element.width());
2987     },
2988     on_file_change: function() {
2989         this.set_image_maxwidth();
2990         this._super.apply(this, arguments);
2991     },
2992     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
2993         this.value = file_base64;
2994         this.binary_value = true;
2995         this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
2996     },
2997     on_clear: function() {
2998         this._super.apply(this, arguments);
2999         this.$image.attr('src', '/web/static/src/img/placeholder.png');
3000     }
3001 });
3002
3003 openerp.web.form.FieldStatus = openerp.web.form.Field.extend({
3004     template: "EmptyComponent",
3005     start: function() {
3006         this._super();
3007         this.selected_value = null;
3008
3009         this.render_list();
3010     },
3011     set_value: function(value) {
3012         this._super(value);
3013         this.selected_value = value;
3014
3015         this.render_list();
3016     },
3017     render_list: function() {
3018         var self = this;
3019         var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
3020             function(x) { return _.str.trim(x); });
3021         shown = _.select(shown, function(x) { return x.length > 0; });
3022
3023         if (shown.length == 0) {
3024             this.to_show = this.field.selection;
3025         } else {
3026             this.to_show = _.select(this.field.selection, function(x) {
3027                 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
3028             });
3029         }
3030
3031         var content = openerp.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3032         this.$element.html(content);
3033
3034         var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3035         var color = colors[this.selected_value];
3036         if (color) {
3037             var elem = this.$element.find("li.oe-arrow-list-selected span");
3038             elem.css("border-color", color);
3039             if (this.check_white(color))
3040                 elem.css("color", "white");
3041             elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3042             elem.css("border-left-color", "rgba(0,0,0,0)");
3043             elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3044             elem.css("border-color", "rgba(0,0,0,0)");
3045             elem.css("border-left-color", color);
3046         }
3047     },
3048     check_white: function(color) {
3049         var div = $("<div></div>");
3050         div.css("display", "none");
3051         div.css("color", color);
3052         div.appendTo($("body"));
3053         var ncolor = div.css("color");
3054         div.remove();
3055         var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3056         if (!res) {
3057             return false;
3058         }
3059         var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3060         var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3061         if (lum < 128) {
3062             return true;
3063         }
3064         return false;
3065     }
3066 });
3067
3068 openerp.web.form.FieldReadonly = openerp.web.form.Field.extend({
3069
3070 });
3071 openerp.web.form.FieldCharReadonly = openerp.web.form.FieldReadonly.extend({
3072     template: 'FieldChar.readonly',
3073     init: function(view, node) {
3074         this._super(view, node);
3075         this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
3076     },
3077     set_value: function (value) {
3078         this._super.apply(this, arguments);
3079         var show_value = openerp.web.format_value(value, this, '');
3080         if (this.password) {
3081             show_value = new Array(show_value.length + 1).join('*');
3082         }
3083         this.$element.find('div').text(show_value);
3084         return show_value;
3085     }
3086 });
3087 openerp.web.form.FieldURIReadonly = openerp.web.form.FieldCharReadonly.extend({
3088     template: 'FieldURI.readonly',
3089     scheme: null,
3090     set_value: function (value) {
3091         var displayed = this._super.apply(this, arguments);
3092         this.$element.find('a')
3093                 .attr('href', this.scheme + ':' + displayed)
3094                 .text(displayed);
3095     }
3096 });
3097 openerp.web.form.FieldEmailReadonly = openerp.web.form.FieldURIReadonly.extend({
3098     scheme: 'mailto'
3099 });
3100 openerp.web.form.FieldUrlReadonly = openerp.web.form.FieldURIReadonly.extend({
3101     set_value: function (value) {
3102         var s = /(\w+):(.+)/.exec(value);
3103         if (!s || !(s[1] === 'http' || s[1] === 'https')) { return; }
3104         this.scheme = s[1];
3105         this._super(s[2]);
3106     }
3107 });
3108 openerp.web.form.FieldBooleanReadonly = openerp.web.form.FieldCharReadonly.extend({
3109     set_value: function (value) {
3110         this._super(value ? '\u2611' : '\u2610');
3111     }
3112 });
3113 openerp.web.form.FieldSelectionReadonly = openerp.web.form.FieldReadonly.extend({
3114     template: 'FieldChar.readonly',
3115     init: function(view, node) {
3116         // lifted straight from r/w version
3117         var self = this;
3118         this._super(view, node);
3119         this.values = this.field.selection;
3120         _.each(this.values, function(v, i) {
3121             if (v[0] === false && v[1] === '') {
3122                 self.values.splice(i, 1);
3123             }
3124         });
3125         this.values.unshift([false, '']);
3126     },
3127     set_value: function (value) {
3128         value = value === null ? false : value;
3129         value = value instanceof Array ? value[0] : value;
3130         var option = _(this.values)
3131             .detect(function (record) { return record[0] === value; });
3132         this._super(value);
3133         this.$element.find('div').text(option ? option[1] : this.values[0][1]);
3134     }
3135 });
3136 openerp.web.form.FieldMany2OneReadonly = openerp.web.form.FieldURIReadonly.extend({
3137     set_value: function (value) {
3138         value = value || null;
3139         this.invalid = false;
3140         var self = this;
3141         this.value = value;
3142         self.update_dom();
3143         self.on_value_changed();
3144         var real_set_value = function(rval) {
3145             self.value = rval;
3146             self.$element.find('a')
3147                  .unbind('click')
3148                  .text(rval ? rval[1] : '')
3149                  .click(function () {
3150                     self.do_action({
3151                         type: 'ir.actions.act_window',
3152                         res_model: self.field.relation,
3153                         res_id: self.value[0],
3154                         context: self.build_context(),
3155                         views: [[false, 'form']],
3156                         target: 'current'
3157                     });
3158                     return false;
3159                  });
3160         };
3161         if (value && !(value instanceof Array)) {
3162             new openerp.web.DataSetStatic(
3163                     this, this.field.relation, self.build_context())
3164                 .name_get([value], function(data) {
3165                     real_set_value(data[0]);
3166             });
3167         } else {
3168             setTimeout(function() {real_set_value(value);}, 0);
3169         }
3170     },
3171     get_value: function() {
3172         if (!this.value) {
3173             return false;
3174         } else if (this.value instanceof Array) {
3175             return this.value[0];
3176         } else {
3177             return this.value;
3178         }
3179     }
3180 });
3181
3182 /**
3183  * Registry of form widgets, called by :js:`openerp.web.FormView`
3184  */
3185 openerp.web.form.widgets = new openerp.web.Registry({
3186     'frame' : 'openerp.web.form.WidgetFrame',
3187     'group' : 'openerp.web.form.WidgetGroup',
3188     'notebook' : 'openerp.web.form.WidgetNotebook',
3189     'notebookpage' : 'openerp.web.form.WidgetNotebookPage',
3190     'separator' : 'openerp.web.form.WidgetSeparator',
3191     'label' : 'openerp.web.form.WidgetLabel',
3192     'button' : 'openerp.web.form.WidgetButton',
3193     'char' : 'openerp.web.form.FieldChar',
3194     'email' : 'openerp.web.form.FieldEmail',
3195     'url' : 'openerp.web.form.FieldUrl',
3196     'text' : 'openerp.web.form.FieldText',
3197     'text_wiki' : 'openerp.web.form.FieldText',
3198     'date' : 'openerp.web.form.FieldDate',
3199     'datetime' : 'openerp.web.form.FieldDatetime',
3200     'selection' : 'openerp.web.form.FieldSelection',
3201     'many2one' : 'openerp.web.form.FieldMany2One',
3202     'many2many' : 'openerp.web.form.FieldMany2Many',
3203     'one2many' : 'openerp.web.form.FieldOne2Many',
3204     'one2many_list' : 'openerp.web.form.FieldOne2Many',
3205     'reference' : 'openerp.web.form.FieldReference',
3206     'boolean' : 'openerp.web.form.FieldBoolean',
3207     'float' : 'openerp.web.form.FieldFloat',
3208     'integer': 'openerp.web.form.FieldFloat',
3209     'float_time': 'openerp.web.form.FieldFloat',
3210     'progressbar': 'openerp.web.form.FieldProgressBar',
3211     'image': 'openerp.web.form.FieldBinaryImage',
3212     'binary': 'openerp.web.form.FieldBinaryFile',
3213     'statusbar': 'openerp.web.form.FieldStatus'
3214 });
3215
3216 openerp.web.form.FieldMany2ManyReadonly = openerp.web.form.FieldMany2Many.extend({
3217     force_readonly: true
3218 });
3219 openerp.web.form.FieldOne2ManyReadonly = openerp.web.form.FieldOne2Many.extend({
3220     force_readonly: true
3221 });
3222 openerp.web.form.readonly = openerp.web.form.widgets.clone({
3223     'char': 'openerp.web.form.FieldCharReadonly',
3224     'email': 'openerp.web.form.FieldEmailReadonly',
3225     'url': 'openerp.web.form.FieldUrlReadonly',
3226     'text': 'openerp.web.form.FieldCharReadonly',
3227     'text_wiki' : 'openerp.web.form.FieldCharReadonly',
3228     'date': 'openerp.web.form.FieldCharReadonly',
3229     'datetime': 'openerp.web.form.FieldCharReadonly',
3230     'selection' : 'openerp.web.form.FieldSelectionReadonly',
3231     'many2one': 'openerp.web.form.FieldMany2OneReadonly',
3232     'many2many' : 'openerp.web.form.FieldMany2ManyReadonly',
3233     'one2many' : 'openerp.web.form.FieldOne2ManyReadonly',
3234     'one2many_list' : 'openerp.web.form.FieldOne2ManyReadonly',
3235     'boolean': 'openerp.web.form.FieldBooleanReadonly',
3236     'float': 'openerp.web.form.FieldCharReadonly',
3237     'integer': 'openerp.web.form.FieldCharReadonly',
3238     'float_time': 'openerp.web.form.FieldCharReadonly'
3239 });
3240
3241 };
3242
3243 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: