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