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