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