[FIX] Merge last trunk
[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(changed_by_user) {
217         if (changed_by_user) {
218             this.$element.addClass('oe_form_dirty');
219         }
220         for (var w in this.widgets) {
221             w = this.widgets[w];
222             w.process_modifiers();
223             if (w.field) {
224                 w.validate();
225             }
226             w.update_dom();
227         }
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         } else {
1422             this.update_dom(true);
1423         }
1424     },
1425     validate: function() {
1426         this.invalid = false;
1427     },
1428     focus: function($element) {
1429         if ($element) {
1430             setTimeout(function() {
1431                 $element.focus();
1432             }, 50);
1433         }
1434     },
1435     reset: function() {
1436         this.dirty = false;
1437     },
1438     get_definition_options: function() {
1439         if (!this.definition_options) {
1440             var str = this.node.attrs.options || '{}';
1441             this.definition_options = JSON.parse(str);
1442         }
1443         return this.definition_options;
1444     }
1445 });
1446
1447 openerp.web.form.FieldChar = openerp.web.form.Field.extend({
1448     template: 'FieldChar',
1449     init: function (view, node) {
1450         this._super(view, node);
1451         this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1452     },
1453     start: function() {
1454         this._super.apply(this, arguments);
1455         this.$element.find('input').change(this.on_ui_change);
1456     },
1457     set_value: function(value) {
1458         this._super.apply(this, arguments);
1459         var show_value = openerp.web.format_value(value, this, '');
1460         this.$element.find('input').val(show_value);
1461         return show_value;
1462     },
1463     update_dom: function() {
1464         this._super.apply(this, arguments);
1465         this.$element.find('input').prop('readonly', this.readonly);
1466     },
1467     set_value_from_ui: function() {
1468         this.value = openerp.web.parse_value(this.$element.find('input').val(), this);
1469         this._super();
1470     },
1471     validate: function() {
1472         this.invalid = false;
1473         try {
1474             var value = openerp.web.parse_value(this.$element.find('input').val(), this, '');
1475             this.invalid = this.required && value === '';
1476         } catch(e) {
1477             this.invalid = true;
1478         }
1479     },
1480     focus: function($element) {
1481         this._super($element || this.$element.find('input:first'));
1482     }
1483 });
1484
1485 openerp.web.form.FieldID = openerp.web.form.FieldChar.extend({
1486     update_dom: function() {
1487         this._super.apply(this, arguments);
1488         this.$element.find('input').prop('readonly', true);
1489     }
1490 });
1491
1492 openerp.web.form.FieldEmail = openerp.web.form.FieldChar.extend({
1493     template: 'FieldEmail',
1494     start: function() {
1495         this._super.apply(this, arguments);
1496         this.$element.find('button').click(this.on_button_clicked);
1497     },
1498     on_button_clicked: function() {
1499         if (!this.value || !this.is_valid()) {
1500             this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1501         } else {
1502             location.href = 'mailto:' + this.value;
1503         }
1504     }
1505 });
1506
1507 openerp.web.form.FieldUrl = openerp.web.form.FieldChar.extend({
1508     template: 'FieldUrl',
1509     start: function() {
1510         this._super.apply(this, arguments);
1511         this.$element.find('button').click(this.on_button_clicked);
1512     },
1513     on_button_clicked: function() {
1514         if (!this.value) {
1515             this.do_warn("Resource error", "This resource is empty");
1516         } else {
1517             window.open(this.value);
1518         }
1519     }
1520 });
1521
1522 openerp.web.form.FieldFloat = openerp.web.form.FieldChar.extend({
1523     init: function (view, node) {
1524         this._super(view, node);
1525         if (node.attrs.digits) {
1526             this.parse_digits(node.attrs.digits);
1527         } else {
1528             this.digits = view.fields_view.fields[node.attrs.name].digits;
1529         }
1530     },
1531     parse_digits: function (digits_attr) {
1532         // could use a Python parser instead.
1533         var match = /^\s*[\(\[](\d+),\s*(\d+)/.exec(digits_attr);
1534         return [parseInt(match[1], 10), parseInt(match[2], 10)];
1535     },
1536     set_value: function(value) {
1537         if (value === false || value === undefined) {
1538             // As in GTK client, floats default to 0
1539             value = 0;
1540         }
1541         this._super.apply(this, [value]);
1542     }
1543 });
1544
1545 openerp.web.DateTimeWidget = openerp.web.OldWidget.extend({
1546     template: "web.datetimepicker",
1547     jqueryui_object: 'datetimepicker',
1548     type_of_date: "datetime",
1549     init: function(parent) {
1550         this._super(parent);
1551         this.name = parent.name;
1552     },
1553     start: function() {
1554         var self = this;
1555         this.$input = this.$element.find('input.oe_datepicker_master');
1556         this.$input_picker = this.$element.find('input.oe_datepicker_container');
1557         this.$input.change(this.on_change);
1558         this.picker({
1559             onSelect: this.on_picker_select,
1560             changeMonth: true,
1561             changeYear: true,
1562             showWeek: true,
1563             showButtonPanel: true
1564         });
1565         this.$element.find('img.oe_datepicker_trigger').click(function() {
1566             if (!self.readonly && !self.picker('widget').is(':visible')) {
1567                 self.picker('setDate', self.value ? openerp.web.auto_str_to_date(self.value) : new Date());
1568                 self.$input_picker.show();
1569                 self.picker('show');
1570                 self.$input_picker.hide();
1571             }
1572         });
1573         this.set_readonly(false);
1574         this.value = false;
1575     },
1576     picker: function() {
1577         return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1578     },
1579     on_picker_select: function(text, instance) {
1580         var date = this.picker('getDate');
1581         this.$input.val(date ? this.format_client(date) : '').change();
1582     },
1583     set_value: function(value) {
1584         this.value = value;
1585         this.$input.val(value ? this.format_client(value) : '');
1586     },
1587     get_value: function() {
1588         return this.value;
1589     },
1590     set_value_from_ui: function() {
1591         var value = this.$input.val() || false;
1592         this.value = this.parse_client(value);
1593     },
1594     set_readonly: function(readonly) {
1595         this.readonly = readonly;
1596         this.$input.prop('readonly', this.readonly);
1597         this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
1598     },
1599     is_valid: function(required) {
1600         var value = this.$input.val();
1601         if (value === "") {
1602             return !required;
1603         } else {
1604             try {
1605                 this.parse_client(value);
1606                 return true;
1607             } catch(e) {
1608                 return false;
1609             }
1610         }
1611     },
1612     parse_client: function(v) {
1613         return openerp.web.parse_value(v, {"widget": this.type_of_date});
1614     },
1615     format_client: function(v) {
1616         return openerp.web.format_value(v, {"widget": this.type_of_date});
1617     },
1618     on_change: function() {
1619         if (this.is_valid()) {
1620             this.set_value_from_ui();
1621         }
1622     }
1623 });
1624
1625 openerp.web.DateWidget = openerp.web.DateTimeWidget.extend({
1626     jqueryui_object: 'datepicker',
1627     type_of_date: "date"
1628 });
1629
1630 openerp.web.form.FieldDatetime = openerp.web.form.Field.extend({
1631     template: "EmptyComponent",
1632     build_widget: function() {
1633         return new openerp.web.DateTimeWidget(this);
1634     },
1635     start: function() {
1636         var self = this;
1637         this._super.apply(this, arguments);
1638         this.datewidget = this.build_widget();
1639         this.datewidget.on_change.add_last(this.on_ui_change);
1640         this.datewidget.appendTo(this.$element);
1641     },
1642     set_value: function(value) {
1643         this._super(value);
1644         this.datewidget.set_value(value);
1645     },
1646     get_value: function() {
1647         return this.datewidget.get_value();
1648     },
1649     update_dom: function() {
1650         this._super.apply(this, arguments);
1651         this.datewidget.set_readonly(this.readonly);
1652     },
1653     validate: function() {
1654         this.invalid = !this.datewidget.is_valid(this.required);
1655     },
1656     focus: function($element) {
1657         this._super($element || this.datewidget.$input);
1658     }
1659 });
1660
1661 openerp.web.form.FieldDate = openerp.web.form.FieldDatetime.extend({
1662     build_widget: function() {
1663         return new openerp.web.DateWidget(this);
1664     }
1665 });
1666
1667 openerp.web.form.FieldText = openerp.web.form.Field.extend({
1668     template: 'FieldText',
1669     start: function() {
1670         this._super.apply(this, arguments);
1671         this.$element.find('textarea').change(this.on_ui_change);
1672         this.resized = false;
1673     },
1674     set_value: function(value) {
1675         this._super.apply(this, arguments);
1676         var show_value = openerp.web.format_value(value, this, '');
1677         this.$element.find('textarea').val(show_value);
1678         if (!this.resized && this.view.options.resize_textareas) {
1679             this.do_resize(this.view.options.resize_textareas);
1680             this.resized = true;
1681         }
1682     },
1683     update_dom: function() {
1684         this._super.apply(this, arguments);
1685         this.$element.find('textarea').prop('readonly', this.readonly);
1686     },
1687     set_value_from_ui: function() {
1688         this.value = openerp.web.parse_value(this.$element.find('textarea').val(), this);
1689         this._super();
1690     },
1691     validate: function() {
1692         this.invalid = false;
1693         try {
1694             var value = openerp.web.parse_value(this.$element.find('textarea').val(), this, '');
1695             this.invalid = this.required && value === '';
1696         } catch(e) {
1697             this.invalid = true;
1698         }
1699     },
1700     focus: function($element) {
1701         this._super($element || this.$element.find('textarea:first'));
1702     },
1703     do_resize: function(max_height) {
1704         max_height = parseInt(max_height, 10);
1705         var $input = this.$element.find('textarea'),
1706             $div = $('<div style="position: absolute; z-index: 1000; top: 0"/>').width($input.width()),
1707             new_height;
1708         $div.text($input.val());
1709         _.each('font-family,font-size,white-space'.split(','), function(style) {
1710             $div.css(style, $input.css(style));
1711         });
1712         $div.appendTo($('body'));
1713         new_height = $div.height();
1714         if (new_height < 90) {
1715             new_height = 90;
1716         }
1717         if (!isNaN(max_height) && new_height > max_height) {
1718             new_height = max_height;
1719         }
1720         $div.remove();
1721         $input.height(new_height);
1722     },
1723     reset: function() {
1724         this.resized = false;
1725     }
1726 });
1727
1728 openerp.web.form.FieldBoolean = openerp.web.form.Field.extend({
1729     template: 'FieldBoolean',
1730     start: function() {
1731         var self = this;
1732         this._super.apply(this, arguments);
1733         this.$element.find('input').click(self.on_ui_change);
1734     },
1735     set_value: function(value) {
1736         this._super.apply(this, arguments);
1737         this.$element.find('input')[0].checked = value;
1738     },
1739     set_value_from_ui: function() {
1740         this.value = this.$element.find('input').is(':checked');
1741         this._super();
1742     },
1743     update_dom: function() {
1744         this._super.apply(this, arguments);
1745         this.$element.find('input').prop('disabled', this.readonly);
1746     },
1747     focus: function($element) {
1748         this._super($element || this.$element.find('input:first'));
1749     }
1750 });
1751
1752 openerp.web.form.FieldProgressBar = openerp.web.form.Field.extend({
1753     template: 'FieldProgressBar',
1754     start: function() {
1755         this._super.apply(this, arguments);
1756         this.$element.find('div').progressbar({
1757             value: this.value,
1758             disabled: this.readonly
1759         });
1760     },
1761     set_value: function(value) {
1762         this._super.apply(this, arguments);
1763         var show_value = Number(value);
1764         if (isNaN(show_value)) {
1765             show_value = 0;
1766         }
1767         var formatted_value = openerp.web.format_value(show_value, { type : 'float' }, '0');
1768         this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(formatted_value + '%');
1769     }
1770 });
1771
1772 openerp.web.form.FieldTextXml = openerp.web.form.Field.extend({
1773 // to replace view editor
1774 });
1775
1776 openerp.web.form.FieldSelection = openerp.web.form.Field.extend({
1777     template: 'FieldSelection',
1778     init: function(view, node) {
1779         var self = this;
1780         this._super(view, node);
1781         this.values = _.clone(this.field.selection);
1782         _.each(this.values, function(v, i) {
1783             if (v[0] === false && v[1] === '') {
1784                 self.values.splice(i, 1);
1785             }
1786         });
1787         this.values.unshift([false, '']);
1788     },
1789     start: function() {
1790         // Flag indicating whether we're in an event chain containing a change
1791         // event on the select, in order to know what to do on keyup[RETURN]:
1792         // * If the user presses [RETURN] as part of changing the value of a
1793         //   selection, we should just let the value change and not let the
1794         //   event broadcast further (e.g. to validating the current state of
1795         //   the form in editable list view, which would lead to saving the
1796         //   current row or switching to the next one)
1797         // * If the user presses [RETURN] with a select closed (side-effect:
1798         //   also if the user opened the select and pressed [RETURN] without
1799         //   changing the selected value), takes the action as validating the
1800         //   row
1801         var ischanging = false;
1802         this._super.apply(this, arguments);
1803         this.$element.find('select')
1804             .change(this.on_ui_change)
1805             .change(function () { ischanging = true; })
1806             .click(function () { ischanging = false; })
1807             .keyup(function (e) {
1808                 if (e.which !== 13 || !ischanging) { return; }
1809                 e.stopPropagation();
1810                 ischanging = false;
1811             });
1812     },
1813     set_value: function(value) {
1814         value = value === null ? false : value;
1815         value = value instanceof Array ? value[0] : value;
1816         this._super(value);
1817         var index = 0;
1818         for (var i = 0, ii = this.values.length; i < ii; i++) {
1819             if (this.values[i][0] === value) index = i;
1820         }
1821         this.$element.find('select')[0].selectedIndex = index;
1822     },
1823     set_value_from_ui: function() {
1824         this.value = this.values[this.$element.find('select')[0].selectedIndex][0];
1825         this._super();
1826     },
1827     update_dom: function() {
1828         this._super.apply(this, arguments);
1829         this.$element.find('select').prop('disabled', this.readonly);
1830     },
1831     validate: function() {
1832         var value = this.values[this.$element.find('select')[0].selectedIndex];
1833         this.invalid = !(value && !(this.required && value[0] === false));
1834     },
1835     focus: function($element) {
1836         this._super($element || this.$element.find('select:first'));
1837     }
1838 });
1839
1840 // jquery autocomplete tweak to allow html
1841 (function() {
1842     var proto = $.ui.autocomplete.prototype,
1843         initSource = proto._initSource;
1844
1845     function filter( array, term ) {
1846         var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1847         return $.grep( array, function(value) {
1848             return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1849         });
1850     }
1851
1852     $.extend( proto, {
1853         _initSource: function() {
1854             if ( this.options.html && $.isArray(this.options.source) ) {
1855                 this.source = function( request, response ) {
1856                     response( filter( this.options.source, request.term ) );
1857                 };
1858             } else {
1859                 initSource.call( this );
1860             }
1861         },
1862
1863         _renderItem: function( ul, item) {
1864             return $( "<li></li>" )
1865                 .data( "item.autocomplete", item )
1866                 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1867                 .appendTo( ul );
1868         }
1869     });
1870 })();
1871
1872 openerp.web.form.dialog = function(content, options) {
1873     options = _.extend({
1874         width: '90%',
1875         height: 'auto',
1876         min_width: '800px'
1877     }, options || {});
1878     var dialog = new openerp.web.Dialog(null, options, content).open();
1879     return dialog.$element;
1880 };
1881
1882 openerp.web.form.FieldMany2One = openerp.web.form.Field.extend({
1883     template: 'FieldMany2One',
1884     init: function(view, node) {
1885         this._super(view, node);
1886         this.limit = 7;
1887         this.value = null;
1888         this.cm_id = _.uniqueId('m2o_cm_');
1889         this.last_search = [];
1890         this.tmp_value = undefined;
1891     },
1892     start: function() {
1893         this._super();
1894         var self = this;
1895         this.$input = this.$element.find("input");
1896         this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1897         this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1898
1899         // context menu
1900         var init_context_menu_def = $.Deferred().then(function(e) {
1901             var rdataset = new openerp.web.DataSetStatic(self, "ir.values", self.build_context());
1902             rdataset.call("get", ['action', 'client_action_relate',
1903                 [[self.field.relation, false]], false, rdataset.get_context()], false, 0)
1904                 .then(function(result) {
1905                 self.related_entries = result;
1906
1907                 var $cmenu = $("#" + self.cm_id);
1908                 $cmenu.append(QWeb.render("FieldMany2One.context_menu", {widget: self}));
1909                 var bindings = {};
1910                 bindings[self.cm_id + "_search"] = function() {
1911                     self._search_create_popup("search");
1912                 };
1913                 bindings[self.cm_id + "_create"] = function() {
1914                     self._search_create_popup("form");
1915                 };
1916                 bindings[self.cm_id + "_open"] = function() {
1917                     if (!self.value) {
1918                         return;
1919                     }
1920                     var pop = new openerp.web.form.FormOpenPopup(self.view);
1921                     pop.show_element(
1922                         self.field.relation,
1923                         self.value[0],
1924                         self.build_context(),
1925                         {
1926                             title: _t("Open: ") + (self.string || self.name)
1927                         }
1928                     );
1929                     pop.on_write_completed.add_last(function() {
1930                         self.set_value(self.value[0]);
1931                     });
1932                 };
1933                 _.each(_.range(self.related_entries.length), function(i) {
1934                     bindings[self.cm_id + "_related_" + i] = function() {
1935                         self.open_related(self.related_entries[i]);
1936                     };
1937                 });
1938                 var cmenu = self.$menu_btn.contextMenu(self.cm_id, {'noRightClick': true,
1939                     bindings: bindings, itemStyle: {"color": ""},
1940                     onContextMenu: function() {
1941                         if(self.value) {
1942                             $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").removeClass("oe-m2o-disabled-cm");
1943                         } else {
1944                             $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").addClass("oe-m2o-disabled-cm");
1945                         }
1946                         if (!self.readonly) {
1947                             $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").removeClass("oe-m2o-disabled-cm");
1948                         } else {
1949                             $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").addClass("oe-m2o-disabled-cm");
1950                         }
1951                         return true;
1952                     }, menuStyle: {width: "200px"}
1953                 });
1954                 $.async_when().then(function() {self.$menu_btn.trigger(e);});
1955             });
1956         });
1957         var ctx_callback = function(e) {init_context_menu_def.resolve(e); e.preventDefault()};
1958         this.$menu_btn.click(ctx_callback);
1959
1960         // some behavior for input
1961         this.$input.keyup(function() {
1962             if (self.$input.val() === "") {
1963                 self._change_int_value(null);
1964             } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1965                 self._change_int_value(undefined);
1966             }
1967         });
1968         this.$drop_down.click(function() {
1969             if (self.readonly)
1970                 return;
1971             if (self.$input.autocomplete("widget").is(":visible")) {
1972                 self.$input.autocomplete("close");
1973             } else {
1974                 if (self.value) {
1975                     self.$input.autocomplete("search", "");
1976                 } else {
1977                     self.$input.autocomplete("search");
1978                 }
1979                 self.$input.focus();
1980             }
1981         });
1982         var anyoneLoosesFocus = function() {
1983             if (!self.$input.is(":focus") &&
1984                     !self.$input.autocomplete("widget").is(":visible") &&
1985                     !self.value) {
1986                 if (self.value === undefined && self.last_search.length > 0) {
1987                     self._change_int_ext_value(self.last_search[0]);
1988                 } else {
1989                     self._change_int_ext_value(null);
1990                 }
1991             }
1992         };
1993         this.$input.focusout(anyoneLoosesFocus);
1994
1995         var isSelecting = false;
1996         // autocomplete
1997         this.$input.autocomplete({
1998             source: function(req, resp) { self.get_search_result(req, resp); },
1999             select: function(event, ui) {
2000                 isSelecting = true;
2001                 var item = ui.item;
2002                 if (item.id) {
2003                     self._change_int_value([item.id, item.name]);
2004                 } else if (item.action) {
2005                     self._change_int_value(undefined);
2006                     item.action();
2007                     return false;
2008                 }
2009             },
2010             focus: function(e, ui) {
2011                 e.preventDefault();
2012             },
2013             html: true,
2014             close: anyoneLoosesFocus,
2015             minLength: 0,
2016             delay: 0
2017         });
2018         // used to correct a bug when selecting an element by pushing 'enter' in an editable list
2019         this.$input.keyup(function(e) {
2020             if (e.which === 13) {
2021                 if (isSelecting)
2022                     e.stopPropagation();
2023             }
2024             isSelecting = false;
2025         });
2026     },
2027     // autocomplete component content handling
2028     get_search_result: function(request, response) {
2029         var search_val = request.term;
2030         var self = this;
2031
2032         if (this.abort_last) {
2033             this.abort_last();
2034             delete this.abort_last;
2035         }
2036         var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2037
2038         dataset.name_search(search_val, self.build_domain(), 'ilike',
2039                 this.limit + 1, function(data) {
2040             self.last_search = data;
2041             // possible selections for the m2o
2042             var values = _.map(data, function(x) {
2043                 return {
2044                     label: _.str.escapeHTML(x[1]),
2045                     value:x[1],
2046                     name:x[1],
2047                     id:x[0]
2048                 };
2049             });
2050
2051             // search more... if more results that max
2052             if (values.length > self.limit) {
2053                 values = values.slice(0, self.limit);
2054                 values.push({label: _t("<em>   Search More...</em>"), action: function() {
2055                     dataset.name_search(search_val, self.build_domain(), 'ilike'
2056                     , false, function(data) {
2057                         self._change_int_value(null);
2058                         self._search_create_popup("search", data);
2059                     });
2060                 }});
2061             }
2062             // quick create
2063             var raw_result = _(data.result).map(function(x) {return x[1];});
2064             if (search_val.length > 0 &&
2065                 !_.include(raw_result, search_val) &&
2066                 (!self.value || search_val !== self.value[1])) {
2067                 values.push({label: _.str.sprintf(_t('<em>   Create "<strong>%s</strong>"</em>'),
2068                         $('<span />').text(search_val).html()), action: function() {
2069                     self._quick_create(search_val);
2070                 }});
2071             }
2072             // create...
2073             values.push({label: _t("<em>   Create and Edit...</em>"), action: function() {
2074                 self._change_int_value(null);
2075                 self._search_create_popup("form", undefined, {"default_name": search_val});
2076             }});
2077
2078             response(values);
2079         });
2080         this.abort_last = dataset.abort_last;
2081     },
2082     _quick_create: function(name) {
2083         var self = this;
2084         var slow_create = function () {
2085             self._change_int_value(null);
2086             self._search_create_popup("form", undefined, {"default_name": name});
2087         };
2088         if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
2089             var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2090             dataset.name_create(name, function(data) {
2091                 self._change_int_ext_value(data);
2092             }).fail(function(error, event) {
2093                 event.preventDefault();
2094                 slow_create();
2095             });
2096         } else
2097             slow_create();
2098     },
2099     // all search/create popup handling
2100     _search_create_popup: function(view, ids, context) {
2101         var self = this;
2102         var pop = new openerp.web.form.SelectCreatePopup(this);
2103         pop.select_element(
2104             self.field.relation,
2105             {
2106                 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
2107                 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
2108                 initial_view: view,
2109                 disable_multiple_selection: true
2110             },
2111             self.build_domain(),
2112             new openerp.web.CompoundContext(self.build_context(), context || {})
2113         );
2114         pop.on_select_elements.add(function(element_ids) {
2115             var dataset = new openerp.web.DataSetStatic(self, self.field.relation, self.build_context());
2116             dataset.name_get([element_ids[0]], function(data) {
2117                 self._change_int_ext_value(data[0]);
2118             });
2119         });
2120     },
2121     _change_int_ext_value: function(value) {
2122         this._change_int_value(value);
2123         this.$input.val(this.value ? this.value[1] : "");
2124     },
2125     _change_int_value: function(value) {
2126         this.value = value;
2127         var back_orig_value = this.original_value;
2128         if (this.value === null || this.value) {
2129             this.original_value = this.value;
2130         }
2131         if (back_orig_value === undefined) { // first use after a set_value()
2132             return;
2133         }
2134         if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
2135                 !== (this.value ? this.value[0] : null))) {
2136             this.on_ui_change();
2137         }
2138     },
2139     set_value: function(value) {
2140         value = value || null;
2141         this.invalid = false;
2142         var self = this;
2143         this.tmp_value = value;
2144         self.update_dom();
2145         self.on_value_changed();
2146         var real_set_value = function(rval) {
2147             self.tmp_value = undefined;
2148             self.value = rval;
2149             self.original_value = undefined;
2150             self._change_int_ext_value(rval);
2151         };
2152         if (value && !(value instanceof Array)) {
2153             // name_get in a m2o does not use the context of the field
2154             var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
2155             dataset.name_get([value], function(data) {
2156                 real_set_value(data[0]);
2157             }).fail(function() {self.tmp_value = undefined;});
2158         } else {
2159             $.async_when().then(function() {real_set_value(value);});
2160         }
2161     },
2162     get_value: function() {
2163         if (this.tmp_value !== undefined) {
2164             if (this.tmp_value instanceof Array) {
2165                 return this.tmp_value[0];
2166             }
2167             return this.tmp_value ? this.tmp_value : false;
2168         }
2169         if (this.value === undefined)
2170             return this.original_value ? this.original_value[0] : false;
2171         return this.value ? this.value[0] : false;
2172     },
2173     validate: function() {
2174         this.invalid = false;
2175         var val = this.tmp_value !== undefined ? this.tmp_value : this.value;
2176         if (val === null) {
2177             this.invalid = this.required;
2178         }
2179     },
2180     open_related: function(related) {
2181         var self = this;
2182         if (!self.value)
2183             return;
2184         var additional_context = {
2185                 active_id: self.value[0],
2186                 active_ids: [self.value[0]],
2187                 active_model: self.field.relation
2188         };
2189         self.rpc("/web/action/load", {
2190             action_id: related[2].id,
2191             context: additional_context
2192         }, function(result) {
2193             result.result.context = _.extend(result.result.context || {}, additional_context);
2194             self.do_action(result.result);
2195         });
2196     },
2197     focus: function ($element) {
2198         this._super($element || this.$input);
2199     },
2200     update_dom: function() {
2201         this._super.apply(this, arguments);
2202         this.$input.prop('readonly', this.readonly);
2203     }
2204 });
2205
2206 /*
2207 # Values: (0, 0,  { fields })    create
2208 #         (1, ID, { fields })    update
2209 #         (2, ID)                remove (delete)
2210 #         (3, ID)                unlink one (target id or target of relation)
2211 #         (4, ID)                link
2212 #         (5)                    unlink all (only valid for one2many)
2213 */
2214 var commands = {
2215     // (0, _, {values})
2216     CREATE: 0,
2217     'create': function (values) {
2218         return [commands.CREATE, false, values];
2219     },
2220     // (1, id, {values})
2221     UPDATE: 1,
2222     'update': function (id, values) {
2223         return [commands.UPDATE, id, values];
2224     },
2225     // (2, id[, _])
2226     DELETE: 2,
2227     'delete': function (id) {
2228         return [commands.DELETE, id, false];
2229     },
2230     // (3, id[, _]) removes relation, but not linked record itself
2231     FORGET: 3,
2232     'forget': function (id) {
2233         return [commands.FORGET, id, false];
2234     },
2235     // (4, id[, _])
2236     LINK_TO: 4,
2237     'link_to': function (id) {
2238         return [commands.LINK_TO, id, false];
2239     },
2240     // (5[, _[, _]])
2241     DELETE_ALL: 5,
2242     'delete_all': function () {
2243         return [5, false, false];
2244     },
2245     // (6, _, ids) replaces all linked records with provided ids
2246     REPLACE_WITH: 6,
2247     'replace_with': function (ids) {
2248         return [6, false, ids];
2249     }
2250 };
2251 openerp.web.form.FieldOne2Many = openerp.web.form.Field.extend({
2252     template: 'FieldOne2Many',
2253     multi_selection: false,
2254     init: function(view, node) {
2255         this._super(view, node);
2256         this.is_loaded = $.Deferred();
2257         this.initial_is_loaded = this.is_loaded;
2258         this.is_setted = $.Deferred();
2259         this.form_last_update = $.Deferred();
2260         this.init_form_last_update = this.form_last_update;
2261         this.disable_utility_classes = true;
2262     },
2263     start: function() {
2264         this._super.apply(this, arguments);
2265
2266         var self = this;
2267
2268         this.dataset = new openerp.web.form.One2ManyDataSet(this, this.field.relation);
2269         this.dataset.o2m = this;
2270         this.dataset.parent_view = this.view;
2271         this.dataset.child_name = this.name;
2272         //this.dataset.child_name = 
2273         this.dataset.on_change.add_last(function() {
2274             self.trigger_on_change();
2275         });
2276
2277         this.is_setted.then(function() {
2278             self.load_views();
2279         });
2280     },
2281     trigger_on_change: function() {
2282         var tmp = this.doing_on_change;
2283         this.doing_on_change = true;
2284         this.on_ui_change();
2285         this.doing_on_change = tmp;
2286     },
2287     is_readonly: function() {
2288         return this.readonly || this.force_readonly;
2289     },
2290     load_views: function() {
2291         var self = this;
2292         
2293         var modes = this.node.attrs.mode;
2294         modes = !!modes ? modes.split(",") : ["tree"];
2295         var views = [];
2296         _.each(modes, function(mode) {
2297             var view = {
2298                 view_id: false,
2299                 view_type: mode == "tree" ? "list" : mode,
2300                 options: { sidebar : false }
2301             };
2302             if (self.field.views && self.field.views[mode]) {
2303                 view.embedded_view = self.field.views[mode];
2304             }
2305             if(view.view_type === "list") {
2306                 view.options.selectable = self.multi_selection;
2307                 if (self.is_readonly()) {
2308                     view.options.addable = null;
2309                     view.options.deletable = null;
2310                     view.options.isClarkGable = false;
2311                 }
2312             } else if (view.view_type === "form") {
2313                 if (self.is_readonly()) {
2314                     view.view_type = 'page';
2315                 }
2316                 view.options.not_interactible_on_create = true;
2317             }
2318             views.push(view);
2319         });
2320         this.views = views;
2321
2322         this.viewmanager = new openerp.web.ViewManager(this, this.dataset, views, {});
2323         this.viewmanager.template = 'One2Many.viewmanager';
2324         this.viewmanager.registry = openerp.web.views.extend({
2325             list: 'openerp.web.form.One2ManyListView',
2326             form: 'openerp.web.form.One2ManyFormView',
2327             page: 'openerp.web.PageView'
2328         });
2329         var once = $.Deferred().then(function() {
2330             self.init_form_last_update.resolve();
2331         });
2332         var def = $.Deferred().then(function() {
2333             self.initial_is_loaded.resolve();
2334         });
2335         this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2336             if (view_type == "list") {
2337                 controller.o2m = self;
2338                 if (self.is_readonly())
2339                     controller.set_editable(false);
2340             } else if (view_type == "form" || view_type == 'page') {
2341                 if (view_type == 'page' || self.is_readonly()) {
2342                     $(".oe_form_buttons", controller.$element).children().remove();
2343                 }
2344                 controller.on_record_loaded.add_last(function() {
2345                     once.resolve();
2346                 });
2347                 controller.on_pager_action.add_first(function() {
2348                     self.save_any_view();
2349                 });
2350             } else if (view_type == "graph") {
2351                 self.reload_current_view()
2352             }
2353             def.resolve();
2354         });
2355         this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2356             $.when(self.save_any_view()).then(function() {
2357                 if(n_mode === "list")
2358                     $.async_when().then(function() {self.reload_current_view();});
2359             });
2360         });
2361         this.is_setted.then(function() {
2362             $.async_when().then(function () {
2363                 self.viewmanager.appendTo(self.$element);
2364             });
2365         });
2366         return def;
2367     },
2368     reload_current_view: function() {
2369         var self = this;
2370         return self.is_loaded = self.is_loaded.pipe(function() {
2371             var active_view = self.viewmanager.active_view;
2372             var view = self.viewmanager.views[active_view].controller;
2373             if(active_view === "list") {
2374                 return view.reload_content();
2375             } else if (active_view === "form" || active_view === 'page') {
2376                 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2377                     self.dataset.index = 0;
2378                 }
2379                 var act = function() {
2380                     return view.do_show();
2381                 };
2382                 self.form_last_update = self.form_last_update.pipe(act, act);
2383                 return self.form_last_update;
2384             } else if (active_view === "graph") {
2385                 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2386             }
2387         }, undefined);
2388     },
2389     set_value: function(value) {
2390         value = value || [];
2391         var self = this;
2392         this.dataset.reset_ids([]);
2393         if(value.length >= 1 && value[0] instanceof Array) {
2394             var ids = [];
2395             _.each(value, function(command) {
2396                 var obj = {values: command[2]};
2397                 switch (command[0]) {
2398                     case commands.CREATE:
2399                         obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2400                         obj.defaults = {};
2401                         self.dataset.to_create.push(obj);
2402                         self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2403                         ids.push(obj.id);
2404                         return;
2405                     case commands.UPDATE:
2406                         obj['id'] = command[1];
2407                         self.dataset.to_write.push(obj);
2408                         self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2409                         ids.push(obj.id);
2410                         return;
2411                     case commands.DELETE:
2412                         self.dataset.to_delete.push({id: command[1]});
2413                         return;
2414                     case commands.LINK_TO:
2415                         ids.push(command[1]);
2416                         return;
2417                     case commands.DELETE_ALL:
2418                         self.dataset.delete_all = true;
2419                         return;
2420                 }
2421             });
2422             this._super(ids);
2423             this.dataset.set_ids(ids);
2424         } else if (value.length >= 1 && typeof(value[0]) === "object") {
2425             var ids = [];
2426             this.dataset.delete_all = true;
2427             _.each(value, function(command) {
2428                 var obj = {values: command};
2429                 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2430                 obj.defaults = {};
2431                 self.dataset.to_create.push(obj);
2432                 self.dataset.cache.push(_.clone(obj));
2433                 ids.push(obj.id);
2434             });
2435             this._super(ids);
2436             this.dataset.set_ids(ids);
2437         } else {
2438             this._super(value);
2439             this.dataset.reset_ids(value);
2440         }
2441         if (this.dataset.index === null && this.dataset.ids.length > 0) {
2442             this.dataset.index = 0;
2443         }
2444         self.is_setted.resolve();
2445         return self.reload_current_view();
2446     },
2447     get_value: function() {
2448         var self = this;
2449         if (!this.dataset)
2450             return [];
2451         this.save_any_view();
2452         var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2453         val = val.concat(_.map(this.dataset.ids, function(id) {
2454             var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2455             if (alter_order) {
2456                 return commands.create(alter_order.values);
2457             }
2458             alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2459             if (alter_order) {
2460                 return commands.update(alter_order.id, alter_order.values);
2461             }
2462             return commands.link_to(id);
2463         }));
2464         return val.concat(_.map(
2465             this.dataset.to_delete, function(x) {
2466                 return commands['delete'](x.id);}));
2467     },
2468     save_any_view: function() {
2469         if (this.doing_on_change)
2470             return false;
2471         return this.session.synchronized_mode(_.bind(function() {
2472                 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2473                     this.viewmanager.views[this.viewmanager.active_view] &&
2474                     this.viewmanager.views[this.viewmanager.active_view].controller) {
2475                     var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2476                     if (this.viewmanager.active_view === "form") {
2477                         if (!view.is_initialized.isResolved()) {
2478                             return false;
2479                         }
2480                         var res = $.when(view.do_save());
2481                         if (!res.isResolved() && !res.isRejected()) {
2482                             console.warn("Asynchronous get_value() is not supported in form view.");
2483                         }
2484                         return res;
2485                     } else if (this.viewmanager.active_view === "list") {
2486                         var res = $.when(view.ensure_saved());
2487                         if (!res.isResolved() && !res.isRejected()) {
2488                             console.warn("Asynchronous get_value() is not supported in list view.");
2489                         }
2490                         return res;
2491                     }
2492                 }
2493                 return false;
2494             }, this));
2495     },
2496     is_valid: function() {
2497         this.validate();
2498         return this._super();
2499     },
2500     validate: function() {
2501         this.invalid = false;
2502         if (!this.viewmanager.views[this.viewmanager.active_view])
2503             return;
2504         var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2505         if (this.viewmanager.active_view === "form") {
2506             for (var f in view.fields) {
2507                 f = view.fields[f];
2508                 if (!f.is_valid()) {
2509                     this.invalid = true;
2510                     return;
2511                 }
2512             }
2513         }
2514     },
2515     is_dirty: function() {
2516         this.save_any_view();
2517         return this._super();
2518     },
2519     update_dom: function() {
2520         this._super.apply(this, arguments);
2521         var self = this;
2522         if (this.previous_readonly !== this.readonly) {
2523             this.previous_readonly = this.readonly;
2524             if (this.viewmanager) {
2525                 this.is_loaded = this.is_loaded.pipe(function() {
2526                     self.viewmanager.stop();
2527                     return $.when(self.load_views()).then(function() {
2528                         self.reload_current_view();
2529                     });
2530                 });
2531             }
2532         }
2533     }
2534 });
2535
2536 openerp.web.form.One2ManyDataSet = openerp.web.BufferedDataSet.extend({
2537     get_context: function() {
2538         this.context = this.o2m.build_context([this.o2m.name]);
2539         return this.context;
2540     }
2541 });
2542
2543 openerp.web.form.One2ManyListView = openerp.web.ListView.extend({
2544     _template: 'One2Many.listview',
2545     do_add_record: function () {
2546         if (this.options.editable) {
2547             this._super.apply(this, arguments);
2548         } else {
2549             var self = this;
2550             var pop = new openerp.web.form.SelectCreatePopup(this);
2551             pop.on_default_get.add(self.dataset.on_default_get);
2552             pop.select_element(
2553                 self.o2m.field.relation,
2554                 {
2555                     title: _t("Create: ") + self.name,
2556                     initial_view: "form",
2557                     alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2558                     create_function: function(data, callback, error_callback) {
2559                         return self.o2m.dataset.create(data).then(function(r) {
2560                             self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2561                             self.o2m.dataset.on_change();
2562                         }).then(callback, error_callback);
2563                     },
2564                     read_function: function() {
2565                         return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2566                     },
2567                     parent_view: self.o2m.view,
2568                     child_name: self.o2m.name,
2569                     form_view_options: {'not_interactible_on_create':true}
2570                 },
2571                 self.o2m.build_domain(),
2572                 self.o2m.build_context()
2573             );
2574             pop.on_select_elements.add_last(function() {
2575                 self.o2m.reload_current_view();
2576             });
2577         }
2578     },
2579     do_activate_record: function(index, id) {
2580         var self = this;
2581         var pop = new openerp.web.form.FormOpenPopup(self.o2m.view);
2582         pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2583             title: _t("Open: ") + self.name,
2584             auto_write: false,
2585             alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2586             parent_view: self.o2m.view,
2587             child_name: self.o2m.name,
2588             read_function: function() {
2589                 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2590             },
2591             form_view_options: {'not_interactible_on_create':true},
2592             readonly: self.o2m.is_readonly()
2593         });
2594         pop.on_write.add(function(id, data) {
2595             self.o2m.dataset.write(id, data, {}, function(r) {
2596                 self.o2m.reload_current_view();
2597             });
2598         });
2599     },
2600     do_button_action: function (name, id, callback) {
2601         var self = this;
2602         var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
2603         return this._super(name, id, _.bind(def.resolve, def));
2604     }
2605 });
2606
2607 openerp.web.form.One2ManyFormView = openerp.web.FormView.extend({
2608     form_template: 'One2Many.formview',
2609     on_loaded: function(data) {
2610         this._super(data);
2611         var self = this;
2612         this.$form_header.find('button.oe_form_button_create').click(function() {
2613             self.do_save().then(self.on_button_new);
2614         });
2615     }
2616 });
2617
2618 openerp.web.form.FieldMany2Many = openerp.web.form.Field.extend({
2619     template: 'FieldMany2Many',
2620     multi_selection: false,
2621     init: function(view, node) {
2622         this._super(view, node);
2623         this.list_id = _.uniqueId("many2many");
2624         this.is_loaded = $.Deferred();
2625         this.initial_is_loaded = this.is_loaded;
2626         this.is_setted = $.Deferred();
2627     },
2628     start: function() {
2629         this._super.apply(this, arguments);
2630
2631         var self = this;
2632
2633         this.dataset = new openerp.web.form.Many2ManyDataSet(this, this.field.relation);
2634         this.dataset.m2m = this;
2635         this.dataset.on_unlink.add_last(function(ids) {
2636             self.on_ui_change();
2637         });
2638         
2639         this.is_setted.then(function() {
2640             self.load_view();
2641         });
2642     },
2643     set_value: function(value) {
2644         value = value || [];
2645         if (value.length >= 1 && value[0] instanceof Array) {
2646             value = value[0][2];
2647         }
2648         this._super(value);
2649         this.dataset.set_ids(value);
2650         var self = this;
2651         self.reload_content();
2652         this.is_setted.resolve();
2653     },
2654     get_value: function() {
2655         return [commands.replace_with(this.dataset.ids)];
2656     },
2657     validate: function() {
2658         this.invalid = false;
2659     },
2660     is_readonly: function() {
2661         return this.readonly || this.force_readonly;
2662     },
2663     load_view: function() {
2664         var self = this;
2665         this.list_view = new openerp.web.form.Many2ManyListView(this, this.dataset, false, {
2666                     'addable': self.is_readonly() ? null : _t("Add"),
2667                     'deletable': self.is_readonly() ? false : true,
2668                     'selectable': self.multi_selection,
2669                     'isClarkGable': self.is_readonly() ? false : true
2670             });
2671         var embedded = (this.field.views || {}).tree;
2672         if (embedded) {
2673             this.list_view.set_embedded_view(embedded);
2674         }
2675         this.list_view.m2m_field = this;
2676         var loaded = $.Deferred();
2677         this.list_view.on_loaded.add_last(function() {
2678             self.initial_is_loaded.resolve();
2679             loaded.resolve();
2680         });
2681         $.async_when().then(function () {
2682             self.list_view.appendTo($("#" + self.list_id));
2683         });
2684         return loaded;
2685     },
2686     reload_content: function() {
2687         var self = this;
2688         this.is_loaded = this.is_loaded.pipe(function() {
2689             return self.list_view.reload_content();
2690         });
2691     },
2692     update_dom: function() {
2693         this._super.apply(this, arguments);
2694         var self = this;
2695         if (this.previous_readonly !== this.readonly) {
2696             this.previous_readonly = this.readonly;
2697             if (this.list_view) {
2698                 this.is_loaded = this.is_loaded.pipe(function() {
2699                     self.list_view.stop();
2700                     return $.when(self.load_view()).then(function() {
2701                         self.reload_content();
2702                     });
2703                 });
2704             }
2705         }
2706     }
2707 });
2708
2709 openerp.web.form.Many2ManyDataSet = openerp.web.DataSetStatic.extend({
2710     get_context: function() {
2711         this.context = this.m2m.build_context();
2712         return this.context;
2713     }
2714 });
2715
2716 /**
2717  * @class
2718  * @extends openerp.web.ListView
2719  */
2720 openerp.web.form.Many2ManyListView = openerp.web.ListView.extend(/** @lends openerp.web.form.Many2ManyListView# */{
2721     do_add_record: function () {
2722         var pop = new openerp.web.form.SelectCreatePopup(this);
2723         pop.select_element(
2724             this.model,
2725             {
2726                 title: _t("Add: ") + this.name
2727             },
2728             new openerp.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
2729             this.m2m_field.build_context()
2730         );
2731         var self = this;
2732         pop.on_select_elements.add(function(element_ids) {
2733             _.each(element_ids, function(element_id) {
2734                 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
2735                     self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
2736                     self.m2m_field.on_ui_change();
2737                     self.reload_content();
2738                 }
2739             });
2740         });
2741     },
2742     do_activate_record: function(index, id) {
2743         var self = this;
2744         var pop = new openerp.web.form.FormOpenPopup(this);
2745         pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
2746             title: _t("Open: ") + this.name,
2747             readonly: this.widget_parent.is_readonly()
2748         });
2749         pop.on_write_completed.add_last(function() {
2750             self.reload_content();
2751         });
2752     }
2753 });
2754
2755 /**
2756  * @class
2757  * @extends openerp.web.OldWidget
2758  */
2759 openerp.web.form.SelectCreatePopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.SelectCreatePopup# */{
2760     template: "SelectCreatePopup",
2761     /**
2762      * options:
2763      * - initial_ids
2764      * - initial_view: form or search (default search)
2765      * - disable_multiple_selection
2766      * - alternative_form_view
2767      * - create_function (defaults to a naive saving behavior)
2768      * - parent_view
2769      * - child_name
2770      * - form_view_options
2771      * - list_view_options
2772      * - read_function
2773      */
2774     select_element: function(model, options, domain, context) {
2775         var self = this;
2776         this.model = model;
2777         this.domain = domain || [];
2778         this.context = context || {};
2779         this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
2780             return self.create_row.apply(self, arguments);
2781         }, read_function: null});
2782         this.initial_ids = this.options.initial_ids;
2783         this.created_elements = [];
2784         this.render_element();
2785         openerp.web.form.dialog(this.$element, {
2786             close: function() {
2787                 self.check_exit();
2788             },
2789             title: options.title || ""
2790         });
2791         this.start();
2792     },
2793     start: function() {
2794         this._super();
2795         var self = this;
2796         this.dataset = new openerp.web.ProxyDataSet(this, this.model,
2797             this.context);
2798         this.dataset.create_function = function() {
2799             return self.options.create_function.apply(null, arguments).then(function(r) {
2800                 self.created_elements.push(r.result);
2801             });
2802         };
2803         this.dataset.write_function = function() {
2804             return self.write_row.apply(self, arguments);
2805         };
2806         this.dataset.read_function = this.options.read_function;
2807         this.dataset.parent_view = this.options.parent_view;
2808         this.dataset.child_name = this.options.child_name;
2809         this.dataset.on_default_get.add(this.on_default_get);
2810         if (this.options.initial_view == "search") {
2811             self.rpc('/web/session/eval_domain_and_context', {
2812                 domains: [],
2813                 contexts: [this.context]
2814             }, function (results) {
2815                 var search_defaults = {};
2816                 _.each(results.context, function (value, key) {
2817                     var match = /^search_default_(.*)$/.exec(key);
2818                     if (match) {
2819                         search_defaults[match[1]] = value;
2820                     }
2821                 });
2822                 self.setup_search_view(search_defaults);
2823             });
2824         } else { // "form"
2825             this.new_object();
2826         }
2827     },
2828     setup_search_view: function(search_defaults) {
2829         var self = this;
2830         if (this.searchview) {
2831             this.searchview.stop();
2832         }
2833         this.searchview = new openerp.web.SearchView(this,
2834                 this.dataset, false,  search_defaults);
2835         this.searchview.on_search.add(function(domains, contexts, groupbys) {
2836             if (self.initial_ids) {
2837                 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
2838                     contexts, groupbys);
2839                 self.initial_ids = undefined;
2840             } else {
2841                 self.do_search(domains.concat([self.domain]), contexts.concat(self.context), groupbys);
2842             }
2843         });
2844         this.searchview.on_loaded.add_last(function () {
2845             self.view_list = new openerp.web.form.SelectCreateListView(self,
2846                     self.dataset, false,
2847                     _.extend({'deletable': false,
2848                         'selectable': !self.options.disable_multiple_selection
2849                     }, self.options.list_view_options || {}));
2850             self.view_list.popup = self;
2851             self.view_list.appendTo($("#" + self.element_id + "_view_list")).pipe(function() {
2852                 self.view_list.do_show();
2853             }).pipe(function() {
2854                 self.searchview.do_search();
2855             });
2856             self.view_list.on_loaded.add_last(function() {
2857                 var $buttons = self.view_list.$element.find(".oe-actions");
2858                 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
2859                 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
2860                 $cbutton.click(function() {
2861                     self.stop();
2862                 });
2863                 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
2864                 if(self.options.disable_multiple_selection) {
2865                     $sbutton.hide();
2866                 }
2867                 $sbutton.click(function() {
2868                     self.on_select_elements(self.selected_ids);
2869                     self.stop();
2870                 });
2871             });
2872         });
2873         this.searchview.appendTo($("#" + this.element_id + "_search"));
2874     },
2875     do_search: function(domains, contexts, groupbys) {
2876         var self = this;
2877         this.rpc('/web/session/eval_domain_and_context', {
2878             domains: domains || [],
2879             contexts: contexts || [],
2880             group_by_seq: groupbys || []
2881         }, function (results) {
2882             self.view_list.do_search(results.domain, results.context, results.group_by);
2883         });
2884     },
2885     create_row: function() {
2886         var self = this;
2887         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2888         wdataset.parent_view = this.options.parent_view;
2889         wdataset.child_name = this.options.child_name;
2890         return wdataset.create.apply(wdataset, arguments);
2891     },
2892     write_row: function() {
2893         var self = this;
2894         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2895         wdataset.parent_view = this.options.parent_view;
2896         wdataset.child_name = this.options.child_name;
2897         return wdataset.write.apply(wdataset, arguments);
2898     },
2899     on_select_elements: function(element_ids) {
2900     },
2901     on_click_element: function(ids) {
2902         this.selected_ids = ids || [];
2903         if(this.selected_ids.length > 0) {
2904             this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
2905         } else {
2906             this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
2907         }
2908     },
2909     new_object: function() {
2910         var self = this;
2911         if (this.searchview) {
2912             this.searchview.hide();
2913         }
2914         if (this.view_list) {
2915             this.view_list.$element.hide();
2916         }
2917         this.dataset.index = null;
2918         this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
2919         if (this.options.alternative_form_view) {
2920             this.view_form.set_embedded_view(this.options.alternative_form_view);
2921         }
2922         this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2923         this.view_form.on_loaded.add_last(function() {
2924             var $buttons = self.view_form.$element.find(".oe_form_buttons");
2925             $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
2926             var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
2927             $nbutton.click(function() {
2928                 $.when(self.view_form.do_save()).then(function() {
2929                     self.view_form.reload_mutex.exec(function() {
2930                         self.view_form.on_button_new();
2931                     });
2932                 });
2933             });
2934             var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
2935             $nbutton.click(function() {
2936                 $.when(self.view_form.do_save()).then(function() {
2937                     self.view_form.reload_mutex.exec(function() {
2938                         self.check_exit();
2939                     });
2940                 });
2941             });
2942             var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
2943             $cbutton.click(function() {
2944                 self.check_exit();
2945             });
2946         });
2947         this.view_form.do_show();
2948     },
2949     check_exit: function() {
2950         if (this.created_elements.length > 0) {
2951             this.on_select_elements(this.created_elements);
2952         }
2953         this.stop();
2954     },
2955     on_default_get: function(res) {}
2956 });
2957
2958 openerp.web.form.SelectCreateListView = openerp.web.ListView.extend({
2959     do_add_record: function () {
2960         this.popup.new_object();
2961     },
2962     select_record: function(index) {
2963         this.popup.on_select_elements([this.dataset.ids[index]]);
2964         this.popup.stop();
2965     },
2966     do_select: function(ids, records) {
2967         this._super(ids, records);
2968         this.popup.on_click_element(ids);
2969     }
2970 });
2971
2972 /**
2973  * @class
2974  * @extends openerp.web.OldWidget
2975  */
2976 openerp.web.form.FormOpenPopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.FormOpenPopup# */{
2977     template: "FormOpenPopup",
2978     /**
2979      * options:
2980      * - alternative_form_view
2981      * - auto_write (default true)
2982      * - read_function
2983      * - parent_view
2984      * - child_name
2985      * - form_view_options
2986      * - readonly
2987      */
2988     show_element: function(model, row_id, context, options) {
2989         this.model = model;
2990         this.row_id = row_id;
2991         this.context = context || {};
2992         this.options = _.defaults(options || {}, {"auto_write": true});
2993         this.render_element();
2994         this.$element.dialog({
2995             title: options.title || '',
2996             modal: true,
2997             width: 960,
2998             height: 600
2999         });
3000         this.start();
3001     },
3002     start: function() {
3003         this._super();
3004         this.dataset = new openerp.web.form.FormOpenDataset(this, this.model, this.context);
3005         this.dataset.fop = this;
3006         this.dataset.ids = [this.row_id];
3007         this.dataset.index = 0;
3008         this.dataset.parent_view = this.options.parent_view;
3009         this.dataset.child_name = this.options.child_name;
3010         this.setup_form_view();
3011     },
3012     on_write: function(id, data) {
3013         if (!this.options.auto_write)
3014             return;
3015         var self = this;
3016         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
3017         wdataset.parent_view = this.options.parent_view;
3018         wdataset.child_name = this.options.child_name;
3019         wdataset.write(id, data, {}, function(r) {
3020             self.on_write_completed();
3021         });
3022     },
3023     on_write_completed: function() {},
3024     setup_form_view: function() {
3025         var self = this;
3026         var FormClass = this.options.readonly
3027                 ? openerp.web.views.get_object('page')
3028                 : openerp.web.views.get_object('form');
3029         this.view_form = new FormClass(this, this.dataset, false, self.options.form_view_options);
3030         if (this.options.alternative_form_view) {
3031             this.view_form.set_embedded_view(this.options.alternative_form_view);
3032         }
3033         this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
3034         this.view_form.on_loaded.add_last(function() {
3035             var $buttons = self.view_form.$element.find(".oe_form_buttons");
3036             $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
3037             var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
3038             $nbutton.click(function() {
3039                 self.view_form.do_save().then(function() {
3040                     self.stop();
3041                 });
3042             });
3043             var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
3044             $cbutton.click(function() {
3045                 self.stop();
3046             });
3047             if (self.options.readonly) {
3048                 $nbutton.hide();
3049                 $cbutton.text(_t("Close"));
3050             }
3051             self.view_form.do_show();
3052         });
3053         this.dataset.on_write.add(this.on_write);
3054     }
3055 });
3056
3057 openerp.web.form.FormOpenDataset = openerp.web.ProxyDataSet.extend({
3058     read_ids: function() {
3059         if (this.fop.options.read_function) {
3060             return this.fop.options.read_function.apply(null, arguments);
3061         } else {
3062             return this._super.apply(this, arguments);
3063         }
3064     }
3065 });
3066
3067 openerp.web.form.FieldReference = openerp.web.form.Field.extend({
3068     template: 'FieldReference',
3069     init: function(view, node) {
3070         this._super(view, node);
3071         this.fields_view = {
3072             fields: {
3073                 selection: {
3074                     selection: view.fields_view.fields[this.name].selection
3075                 },
3076                 m2o: {
3077                     relation: null
3078                 }
3079             }
3080         };
3081         this.get_fields_values = view.get_fields_values;
3082         this.get_selected_ids = view.get_selected_ids;
3083         this.do_onchange = this.on_form_changed = this.on_nop;
3084         this.dataset = this.view.dataset;
3085         this.widgets_counter = 0;
3086         this.view_id = 'reference_' + _.uniqueId();
3087         this.widgets = {};
3088         this.fields = {};
3089         this.fields_order = [];
3090         this.selection = new openerp.web.form.FieldSelection(this, { attrs: {
3091             name: 'selection',
3092             widget: 'selection'
3093         }});
3094         this.reference_ready = true;
3095         this.selection.on_value_changed.add_last(this.on_selection_changed);
3096         this.m2o = new openerp.web.form.FieldMany2One(this, { attrs: {
3097             name: 'm2o',
3098             widget: 'many2one'
3099         }});
3100         this.m2o.on_ui_change.add_last(this.on_ui_change);
3101     },
3102     on_nop: function() {
3103     },
3104     on_selection_changed: function() {
3105         if (this.reference_ready) {
3106             var sel = this.selection.get_value();
3107             this.m2o.field.relation = sel;
3108             this.m2o.set_value(null);
3109             this.m2o.$element.toggle(sel !== false);
3110         }
3111     },
3112     start: function() {
3113         this._super();
3114         this.selection.start();
3115         this.m2o.start();
3116     },
3117     is_valid: function() {
3118         return this.required === false || typeof(this.get_value()) === 'string';
3119     },
3120     is_dirty: function() {
3121         return this.selection.is_dirty() || this.m2o.is_dirty();
3122     },
3123     set_value: function(value) {
3124         this._super(value);
3125         this.reference_ready = false;
3126         var vals = [], sel_val, m2o_val;
3127         if (typeof(value) === 'string') {
3128             vals = value.split(',');
3129         }
3130         sel_val = vals[0] || false;
3131         m2o_val = vals[1] ? parseInt(vals[1], 10) : false;
3132         this.selection.set_value(sel_val);
3133         this.m2o.field.relation = sel_val;
3134         this.m2o.set_value(m2o_val);
3135         this.m2o.$element.toggle(sel_val !== false);
3136         this.reference_ready = true;
3137     },
3138     get_value: function() {
3139         var model = this.selection.get_value(),
3140             id = this.m2o.get_value();
3141         if (typeof(model) === 'string' && typeof(id) === 'number') {
3142             return model + ',' + id;
3143         } else {
3144             return false;
3145         }
3146     }
3147 });
3148
3149 openerp.web.form.FieldBinary = openerp.web.form.Field.extend({
3150     init: function(view, node) {
3151         this._super(view, node);
3152         this.iframe = this.element_id + '_iframe';
3153         this.binary_value = false;
3154     },
3155     start: function() {
3156         this._super.apply(this, arguments);
3157         this.$element.find('input.oe-binary-file').change(this.on_file_change);
3158         this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
3159         this.$element.find('.oe-binary-file-clear').click(this.on_clear);
3160     },
3161     human_filesize : function(size) {
3162         var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
3163         var i = 0;
3164         while (size >= 1024) {
3165             size /= 1024;
3166             ++i;
3167         }
3168         return size.toFixed(2) + ' ' + units[i];
3169     },
3170     on_file_change: function(e) {
3171         // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
3172         // http://www.html5rocks.com/tutorials/file/dndfiles/
3173         // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
3174         window[this.iframe] = this.on_file_uploaded;
3175         if ($(e.target).val() != '') {
3176             this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
3177             this.$element.find('form.oe-binary-form').submit();
3178             this.$element.find('.oe-binary-progress').show();
3179             this.$element.find('.oe-binary').hide();
3180         }
3181     },
3182     on_file_uploaded: function(size, name, content_type, file_base64) {
3183         delete(window[this.iframe]);
3184         if (size === false) {
3185             this.do_warn("File Upload", "There was a problem while uploading your file");
3186             // TODO: use openerp web crashmanager
3187             console.warn("Error while uploading file : ", name);
3188         } else {
3189             this.on_file_uploaded_and_valid.apply(this, arguments);
3190             this.on_ui_change();
3191         }
3192         this.$element.find('.oe-binary-progress').hide();
3193         this.$element.find('.oe-binary').show();
3194     },
3195     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3196     },
3197     on_save_as: function() {
3198         $.blockUI();
3199         this.session.get_file({
3200             url: '/web/binary/saveas_ajax',
3201             data: {data: JSON.stringify({
3202                 model: this.view.dataset.model,
3203                 id: (this.view.datarecord.id || ''),
3204                 field: this.name,
3205                 filename_field: (this.node.attrs.filename || ''),
3206                 context: this.view.dataset.get_context()
3207             })},
3208             complete: $.unblockUI,
3209             error: openerp.webclient.crashmanager.on_rpc_error
3210         });
3211     },
3212     on_clear: function() {
3213         if (this.value !== false) {
3214             this.value = false;
3215             this.binary_value = false;
3216             this.on_ui_change();
3217         }
3218         return false;
3219     }
3220 });
3221
3222 openerp.web.form.FieldBinaryFile = openerp.web.form.FieldBinary.extend({
3223     template: 'FieldBinaryFile',
3224     update_dom: function() {
3225         this._super.apply(this, arguments);
3226         this.$element.find('.oe-binary-file-set, .oe-binary-file-clear').toggle(!this.readonly);
3227         this.$element.find('input[type=text]').prop('readonly', this.readonly);
3228     },
3229     set_value: function(value) {
3230         this._super.apply(this, arguments);
3231         var show_value;
3232         if (this.node.attrs.filename) {
3233             show_value = this.view.datarecord[this.node.attrs.filename] || '';
3234         } else {
3235             show_value = (value != null && value !== false) ? value : '';
3236         }
3237         this.$element.find('input').eq(0).val(show_value);
3238     },
3239     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3240         this.value = file_base64;
3241         this.binary_value = true;
3242         var show_value = name + " (" + this.human_filesize(size) + ")";
3243         this.$element.find('input').eq(0).val(show_value);
3244         this.set_filename(name);
3245     },
3246     set_filename: function(value) {
3247         var filename = this.node.attrs.filename;
3248         if (this.view.fields[filename]) {
3249             this.view.fields[filename].set_value(value);
3250             this.view.fields[filename].on_ui_change();
3251         }
3252     },
3253     on_clear: function() {
3254         this._super.apply(this, arguments);
3255         this.$element.find('input').eq(0).val('');
3256         this.set_filename('');
3257     }
3258 });
3259
3260 openerp.web.form.FieldBinaryImage = openerp.web.form.FieldBinary.extend({
3261     template: 'FieldBinaryImage',
3262     start: function() {
3263         this._super.apply(this, arguments);
3264         this.$image = this.$element.find('img.oe-binary-image');
3265     },
3266     update_dom: function() {
3267         this._super.apply(this, arguments);
3268         this.$element.find('.oe-binary').toggle(!this.readonly);
3269     },
3270     set_value: function(value) {
3271         this._super.apply(this, arguments);
3272         this.set_image_maxwidth();
3273         var url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
3274             this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
3275         this.$image.attr('src', url);
3276     },
3277     set_image_maxwidth: function() {
3278         this.$image.css('max-width', this.$element.width());
3279     },
3280     on_file_change: function() {
3281         this.set_image_maxwidth();
3282         this._super.apply(this, arguments);
3283     },
3284     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3285         this.value = file_base64;
3286         this.binary_value = true;
3287         this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
3288     },
3289     on_clear: function() {
3290         this._super.apply(this, arguments);
3291         this.$image.attr('src', '/web/static/src/img/placeholder.png');
3292     }
3293 });
3294
3295 openerp.web.form.FieldStatus = openerp.web.form.Field.extend({
3296     template: "EmptyComponent",
3297     start: function() {
3298         this._super();
3299         this.selected_value = null;
3300
3301         this.render_list();
3302     },
3303     set_value: function(value) {
3304         this._super(value);
3305         this.selected_value = value;
3306
3307         this.render_list();
3308     },
3309     render_list: function() {
3310         var self = this;
3311         var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
3312             function(x) { return _.str.trim(x); });
3313         shown = _.select(shown, function(x) { return x.length > 0; });
3314
3315         if (shown.length == 0) {
3316             this.to_show = this.field.selection;
3317         } else {
3318             this.to_show = _.select(this.field.selection, function(x) {
3319                 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
3320             });
3321         }
3322
3323         var content = openerp.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3324         this.$element.html(content);
3325
3326         var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3327         var color = colors[this.selected_value];
3328         if (color) {
3329             var elem = this.$element.find("li.oe-arrow-list-selected span");
3330             elem.css("border-color", color);
3331             if (this.check_white(color))
3332                 elem.css("color", "white");
3333             elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3334             elem.css("border-left-color", "rgba(0,0,0,0)");
3335             elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3336             elem.css("border-color", "rgba(0,0,0,0)");
3337             elem.css("border-left-color", color);
3338         }
3339     },
3340     check_white: function(color) {
3341         var div = $("<div></div>");
3342         div.css("display", "none");
3343         div.css("color", color);
3344         div.appendTo($("body"));
3345         var ncolor = div.css("color");
3346         div.remove();
3347         var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3348         if (!res) {
3349             return false;
3350         }
3351         var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3352         var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3353         if (lum < 128) {
3354             return true;
3355         }
3356         return false;
3357     }
3358 });
3359
3360 openerp.web.form.WidgetHtml = openerp.web.form.Widget.extend({
3361     render: function () {
3362         var $root = $('<div class="oe_form_html_view">');
3363         this.render_children(this, $root);
3364         return $root.html();
3365     },
3366     render_children: function (object, $into) {
3367         var self = this,
3368             fields = this.view.fields_view.fields;
3369         _(object.children).each(function (child) {
3370             if (typeof child === 'string') {
3371                 $into.text(child);
3372             } else if (child.tag === 'field') {
3373                 $into.append(
3374                     new (self.view.registry.get_object('frame'))(
3375                         self.view, {tag: 'ueule', attrs: {}, children: [child] })
3376                             .render());
3377             } else {
3378                 var $child = $(document.createElement(child.tag))
3379                         .attr(child.attrs)
3380                         .appendTo($into);
3381                 self.render_children(child, $child);
3382             }
3383         });
3384     }
3385 });
3386
3387
3388 /**
3389  * Registry of form widgets, called by :js:`openerp.web.FormView`
3390  */
3391 openerp.web.form.widgets = new openerp.web.Registry({
3392     'frame' : 'openerp.web.form.WidgetFrame',
3393     'group' : 'openerp.web.form.WidgetGroup',
3394     'notebook' : 'openerp.web.form.WidgetNotebook',
3395     'notebookpage' : 'openerp.web.form.WidgetNotebookPage',
3396     'separator' : 'openerp.web.form.WidgetSeparator',
3397     'label' : 'openerp.web.form.WidgetLabel',
3398     'button' : 'openerp.web.form.WidgetButton',
3399     'char' : 'openerp.web.form.FieldChar',
3400     'id' : 'openerp.web.form.FieldID',
3401     'email' : 'openerp.web.form.FieldEmail',
3402     'url' : 'openerp.web.form.FieldUrl',
3403     'text' : 'openerp.web.form.FieldText',
3404     'date' : 'openerp.web.form.FieldDate',
3405     'datetime' : 'openerp.web.form.FieldDatetime',
3406     'selection' : 'openerp.web.form.FieldSelection',
3407     'many2one' : 'openerp.web.form.FieldMany2One',
3408     'many2many' : 'openerp.web.form.FieldMany2Many',
3409     'one2many' : 'openerp.web.form.FieldOne2Many',
3410     'one2many_list' : 'openerp.web.form.FieldOne2Many',
3411     'reference' : 'openerp.web.form.FieldReference',
3412     'boolean' : 'openerp.web.form.FieldBoolean',
3413     'float' : 'openerp.web.form.FieldFloat',
3414     'integer': 'openerp.web.form.FieldFloat',
3415     'float_time': 'openerp.web.form.FieldFloat',
3416     'progressbar': 'openerp.web.form.FieldProgressBar',
3417     'image': 'openerp.web.form.FieldBinaryImage',
3418     'binary': 'openerp.web.form.FieldBinaryFile',
3419     'statusbar': 'openerp.web.form.FieldStatus',
3420     'html': 'openerp.web.form.WidgetHtml'
3421 });
3422
3423
3424 };
3425
3426 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: