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