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