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