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