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