[REM] Refactored Dataset. Removed callbacks for #read_ids, #read_slice, #read_index...
[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     var dialog = new openerp.web.Dialog(null, options, content).open();
1702     return dialog.$element;
1703 };
1704
1705 openerp.web.form.FieldMany2One = openerp.web.form.Field.extend({
1706     template: 'FieldMany2One',
1707     init: function(view, node) {
1708         this._super(view, node);
1709         this.limit = 7;
1710         this.value = null;
1711         this.cm_id = _.uniqueId('m2o_cm_');
1712         this.last_search = [];
1713         this.tmp_value = undefined;
1714     },
1715     start: function() {
1716         this._super();
1717         var self = this;
1718         this.$input = this.$element.find("input");
1719         this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1720         this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1721
1722         // context menu
1723         var init_context_menu_def = $.Deferred().then(function(e) {
1724             var rdataset = new openerp.web.DataSetStatic(self, "ir.values", self.build_context());
1725             rdataset.call("get", ['action', 'client_action_relate',
1726                 [[self.field.relation, false]], false, rdataset.get_context()], false, 0)
1727                 .then(function(result) {
1728                 self.related_entries = result;
1729
1730                 var $cmenu = $("#" + self.cm_id);
1731                 $cmenu.append(QWeb.render("FieldMany2One.context_menu", {widget: self}));
1732                 var bindings = {};
1733                 bindings[self.cm_id + "_search"] = function() {
1734                     self._search_create_popup("search");
1735                 };
1736                 bindings[self.cm_id + "_create"] = function() {
1737                     self._search_create_popup("form");
1738                 };
1739                 bindings[self.cm_id + "_open"] = function() {
1740                     if (!self.value) {
1741                         return;
1742                     }
1743                     var pop = new openerp.web.form.FormOpenPopup(self.view);
1744                     pop.show_element(
1745                         self.field.relation,
1746                         self.value[0],
1747                         self.build_context(),
1748                         {
1749                             title: _t("Open: ") + (self.string || self.name)
1750                         }
1751                     );
1752                     pop.on_write_completed.add_last(function() {
1753                         self.set_value(self.value[0]);
1754                     });
1755                 };
1756                 _.each(_.range(self.related_entries.length), function(i) {
1757                     bindings[self.cm_id + "_related_" + i] = function() {
1758                         self.open_related(self.related_entries[i]);
1759                     };
1760                 });
1761                 var cmenu = self.$menu_btn.contextMenu(self.cm_id, {'leftClickToo': true,
1762                     bindings: bindings, itemStyle: {"color": ""},
1763                     onContextMenu: function() {
1764                         if(self.value) {
1765                             $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").removeClass("oe-m2o-disabled-cm");
1766                         } else {
1767                             $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").addClass("oe-m2o-disabled-cm");
1768                         }
1769                         if (!self.readonly) {
1770                             $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").removeClass("oe-m2o-disabled-cm");
1771                         } else {
1772                             $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").addClass("oe-m2o-disabled-cm");
1773                         }
1774                         return true;
1775                     }, menuStyle: {width: "200px"}
1776                 });
1777                 $.async_when().then(function() {self.$menu_btn.trigger(e);});
1778             });
1779         });
1780         var ctx_callback = function(e) {init_context_menu_def.resolve(e); e.preventDefault()};
1781         this.$menu_btn.bind('contextmenu', ctx_callback);
1782         this.$menu_btn.click(ctx_callback);
1783
1784         // some behavior for input
1785         this.$input.keyup(function() {
1786             if (self.$input.val() === "") {
1787                 self._change_int_value(null);
1788             } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1789                 self._change_int_value(undefined);
1790             }
1791         });
1792         this.$drop_down.click(function() {
1793             if (self.readonly)
1794                 return;
1795             if (self.$input.autocomplete("widget").is(":visible")) {
1796                 self.$input.autocomplete("close");
1797             } else {
1798                 if (self.value) {
1799                     self.$input.autocomplete("search", "");
1800                 } else {
1801                     self.$input.autocomplete("search");
1802                 }
1803                 self.$input.focus();
1804             }
1805         });
1806         var anyoneLoosesFocus = function() {
1807             if (!self.$input.is(":focus") &&
1808                     !self.$input.autocomplete("widget").is(":visible") &&
1809                     !self.value) {
1810                 if (self.value === undefined && self.last_search.length > 0) {
1811                     self._change_int_ext_value(self.last_search[0]);
1812                 } else {
1813                     self._change_int_ext_value(null);
1814                 }
1815             }
1816         };
1817         this.$input.focusout(anyoneLoosesFocus);
1818
1819         var isSelecting = false;
1820         // autocomplete
1821         this.$input.autocomplete({
1822             source: function(req, resp) { self.get_search_result(req, resp); },
1823             select: function(event, ui) {
1824                 isSelecting = true;
1825                 var item = ui.item;
1826                 if (item.id) {
1827                     self._change_int_value([item.id, item.name]);
1828                 } else if (item.action) {
1829                     self._change_int_value(undefined);
1830                     item.action();
1831                     return false;
1832                 }
1833             },
1834             focus: function(e, ui) {
1835                 e.preventDefault();
1836             },
1837             html: true,
1838             close: anyoneLoosesFocus,
1839             minLength: 0,
1840             delay: 0
1841         });
1842         // used to correct a bug when selecting an element by pushing 'enter' in an editable list
1843         this.$input.keyup(function(e) {
1844             if (e.which === 13) {
1845                 if (isSelecting)
1846                     e.stopPropagation();
1847             }
1848             isSelecting = false;
1849         });
1850     },
1851     // autocomplete component content handling
1852     get_search_result: function(request, response) {
1853         var search_val = request.term;
1854         var self = this;
1855
1856         var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1857
1858         dataset.name_search(search_val, self.build_domain(), 'ilike',
1859                 this.limit + 1, function(data) {
1860             self.last_search = data;
1861             // possible selections for the m2o
1862             var values = _.map(data, function(x) {
1863                 return {label: $('<span />').text(x[1]).html(), name:x[1], id:x[0]};
1864             });
1865
1866             // search more... if more results that max
1867             if (values.length > self.limit) {
1868                 values = values.slice(0, self.limit);
1869                 values.push({label: _t("<em>   Search More...</em>"), action: function() {
1870                     dataset.name_search(search_val, self.build_domain(), 'ilike'
1871                     , false, function(data) {
1872                         self._change_int_value(null);
1873                         self._search_create_popup("search", data);
1874                     });
1875                 }});
1876             }
1877             // quick create
1878             var raw_result = _(data.result).map(function(x) {return x[1];});
1879             if (search_val.length > 0 &&
1880                 !_.include(raw_result, search_val) &&
1881                 (!self.value || search_val !== self.value[1])) {
1882                 values.push({label: _.str.sprintf(_t('<em>   Create "<strong>%s</strong>"</em>'),
1883                         $('<span />').text(search_val).html()), action: function() {
1884                     self._quick_create(search_val);
1885                 }});
1886             }
1887             // create...
1888             values.push({label: _t("<em>   Create and Edit...</em>"), action: function() {
1889                 self._change_int_value(null);
1890                 self._search_create_popup("form", undefined, {"default_name": search_val});
1891             }});
1892
1893             response(values);
1894         });
1895     },
1896     _quick_create: function(name) {
1897         var self = this;
1898         var slow_create = function() {
1899             self._change_int_value(null);
1900             self._search_create_popup("form", undefined, {"default_name": name});
1901         }
1902         if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
1903             var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1904             dataset.name_create(name, function(data) {
1905                 self._change_int_ext_value(data);
1906             }).fail(function(error, event) {
1907                 event.preventDefault();
1908                 slow_create();
1909             });
1910         } else
1911             slow_create();
1912     },
1913     // all search/create popup handling
1914     _search_create_popup: function(view, ids, context) {
1915         var self = this;
1916         var pop = new openerp.web.form.SelectCreatePopup(this);
1917         pop.select_element(
1918             self.field.relation,
1919             {
1920                 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
1921                 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
1922                 initial_view: view,
1923                 disable_multiple_selection: true
1924             },
1925             self.build_domain(),
1926             new openerp.web.CompoundContext(self.build_context(), context || {})
1927         );
1928         pop.on_select_elements.add(function(element_ids) {
1929             var dataset = new openerp.web.DataSetStatic(self, self.field.relation, self.build_context());
1930             dataset.name_get([element_ids[0]], function(data) {
1931                 self._change_int_ext_value(data[0]);
1932             });
1933         });
1934     },
1935     _change_int_ext_value: function(value) {
1936         this._change_int_value(value);
1937         this.$input.val(this.value ? this.value[1] : "");
1938     },
1939     _change_int_value: function(value) {
1940         this.value = value;
1941         var back_orig_value = this.original_value;
1942         if (this.value === null || this.value) {
1943             this.original_value = this.value;
1944         }
1945         if (back_orig_value === undefined) { // first use after a set_value()
1946             return;
1947         }
1948         if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
1949                 !== (this.value ? this.value[0] : null))) {
1950             this.on_ui_change();
1951         }
1952     },
1953     set_value: function(value) {
1954         value = value || null;
1955         this.invalid = false;
1956         var self = this;
1957         this.tmp_value = value;
1958         self.update_dom();
1959         self.on_value_changed();
1960         var real_set_value = function(rval) {
1961             self.tmp_value = undefined;
1962             self.value = rval;
1963             self.original_value = undefined;
1964             self._change_int_ext_value(rval);
1965         };
1966         if (value && !(value instanceof Array)) {
1967             // name_get in a m2o does not use the context of the field
1968             var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
1969             dataset.name_get([value], function(data) {
1970                 real_set_value(data[0]);
1971             }).fail(function() {self.tmp_value = undefined;});
1972         } else {
1973             $.async_when().then(function() {real_set_value(value);});
1974         }
1975     },
1976     get_value: function() {
1977         if (this.tmp_value !== undefined) {
1978             if (this.tmp_value instanceof Array) {
1979                 return this.tmp_value[0];
1980             }
1981             return this.tmp_value ? this.tmp_value : false;
1982         }
1983         if (this.value === undefined)
1984             return this.original_value ? this.original_value[0] : false;
1985         return this.value ? this.value[0] : false;
1986     },
1987     validate: function() {
1988         this.invalid = false;
1989         var val = this.tmp_value !== undefined ? this.tmp_value : this.value;
1990         if (val === null) {
1991             this.invalid = this.required;
1992         }
1993     },
1994     open_related: function(related) {
1995         var self = this;
1996         if (!self.value)
1997             return;
1998         var additional_context = {
1999                 active_id: self.value[0],
2000                 active_ids: [self.value[0]],
2001                 active_model: self.field.relation
2002         };
2003         self.rpc("/web/action/load", {
2004             action_id: related[2].id,
2005             context: additional_context
2006         }, function(result) {
2007             result.result.context = _.extend(result.result.context || {}, additional_context);
2008             self.do_action(result.result);
2009         });
2010     },
2011     focus: function () {
2012         this.$input.focus();
2013     },
2014     update_dom: function() {
2015         this._super.apply(this, arguments);
2016         this.$input.prop('disabled', this.readonly);
2017     }
2018 });
2019
2020 /*
2021 # Values: (0, 0,  { fields })    create
2022 #         (1, ID, { fields })    update
2023 #         (2, ID)                remove (delete)
2024 #         (3, ID)                unlink one (target id or target of relation)
2025 #         (4, ID)                link
2026 #         (5)                    unlink all (only valid for one2many)
2027 */
2028 var commands = {
2029     // (0, _, {values})
2030     CREATE: 0,
2031     'create': function (values) {
2032         return [commands.CREATE, false, values];
2033     },
2034     // (1, id, {values})
2035     UPDATE: 1,
2036     'update': function (id, values) {
2037         return [commands.UPDATE, id, values];
2038     },
2039     // (2, id[, _])
2040     DELETE: 2,
2041     'delete': function (id) {
2042         return [commands.DELETE, id, false];
2043     },
2044     // (3, id[, _]) removes relation, but not linked record itself
2045     FORGET: 3,
2046     'forget': function (id) {
2047         return [commands.FORGET, id, false];
2048     },
2049     // (4, id[, _])
2050     LINK_TO: 4,
2051     'link_to': function (id) {
2052         return [commands.LINK_TO, id, false];
2053     },
2054     // (5[, _[, _]])
2055     DELETE_ALL: 5,
2056     'delete_all': function () {
2057         return [5, false, false];
2058     },
2059     // (6, _, ids) replaces all linked records with provided ids
2060     REPLACE_WITH: 6,
2061     'replace_with': function (ids) {
2062         return [6, false, ids];
2063     }
2064 };
2065 openerp.web.form.FieldOne2Many = openerp.web.form.Field.extend({
2066     template: 'FieldOne2Many',
2067     multi_selection: false,
2068     init: function(view, node) {
2069         this._super(view, node);
2070         this.is_loaded = $.Deferred();
2071         this.initial_is_loaded = this.is_loaded;
2072         this.is_setted = $.Deferred();
2073         this.form_last_update = $.Deferred();
2074         this.init_form_last_update = this.form_last_update;
2075         this.disable_utility_classes = true;
2076     },
2077     start: function() {
2078         this._super.apply(this, arguments);
2079
2080         var self = this;
2081
2082         this.dataset = new openerp.web.form.One2ManyDataSet(this, this.field.relation);
2083         this.dataset.o2m = this;
2084         this.dataset.parent_view = this.view;
2085         this.dataset.child_name = this.name;
2086         //this.dataset.child_name = 
2087         this.dataset.on_change.add_last(function() {
2088             self.trigger_on_change();
2089         });
2090
2091         this.is_setted.then(function() {
2092             self.load_views();
2093         });
2094     },
2095     trigger_on_change: function() {
2096         var tmp = this.doing_on_change;
2097         this.doing_on_change = true;
2098         this.on_ui_change();
2099         this.doing_on_change = tmp;
2100     },
2101     is_readonly: function() {
2102         return this.readonly || this.force_readonly;
2103     },
2104     load_views: function() {
2105         var self = this;
2106         
2107         var modes = this.node.attrs.mode;
2108         modes = !!modes ? modes.split(",") : ["tree"];
2109         var views = [];
2110         _.each(modes, function(mode) {
2111             var view = {
2112                 view_id: false,
2113                 view_type: mode == "tree" ? "list" : mode,
2114                 options: { sidebar : false }
2115             };
2116             if (self.field.views && self.field.views[mode]) {
2117                 view.embedded_view = self.field.views[mode];
2118             }
2119             if(view.view_type === "list") {
2120                 view.options.selectable = self.multi_selection;
2121                 if (self.is_readonly()) {
2122                     view.options.addable = null;
2123                     view.options.deletable = null;
2124                     view.options.isClarkGable = false;
2125                 }
2126             } else if (view.view_type === "form") {
2127                 if (self.is_readonly()) {
2128                     view.view_type = 'page';
2129                 }
2130                 view.options.not_interactible_on_create = true;
2131             }
2132             views.push(view);
2133         });
2134         this.views = views;
2135
2136         this.viewmanager = new openerp.web.ViewManager(this, this.dataset, views, {});
2137         this.viewmanager.template = 'One2Many.viewmanager';
2138         this.viewmanager.registry = openerp.web.views.clone({
2139             list: 'openerp.web.form.One2ManyListView',
2140             form: 'openerp.web.form.One2ManyFormView',
2141             page: 'openerp.web.PageView'
2142         });
2143         var once = $.Deferred().then(function() {
2144             self.init_form_last_update.resolve();
2145         });
2146         var def = $.Deferred().then(function() {
2147             self.initial_is_loaded.resolve();
2148         });
2149         this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2150             if (view_type == "list") {
2151                 controller.o2m = self;
2152                 if (self.is_readonly())
2153                     controller.set_editable(false);
2154             } else if (view_type == "form" || view_type == 'page') {
2155                 if (view_type == 'page' || self.is_readonly()) {
2156                     $(".oe_form_buttons", controller.$element).children().remove();
2157                 }
2158                 controller.on_record_loaded.add_last(function() {
2159                     once.resolve();
2160                 });
2161                 controller.on_pager_action.add_first(function() {
2162                     self.save_any_view();
2163                 });
2164             } else if (view_type == "graph") {
2165                 self.reload_current_view()
2166             }
2167             def.resolve();
2168         });
2169         this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2170             $.when(self.save_any_view()).then(function() {
2171                 if(n_mode === "list")
2172                     $.async_when().then(function() {self.reload_current_view();});
2173             });
2174         });
2175         this.is_setted.then(function() {
2176             $.async_when().then(function () {
2177                 self.viewmanager.appendTo(self.$element);
2178             });
2179         });
2180         return def;
2181     },
2182     reload_current_view: function() {
2183         var self = this;
2184         return self.is_loaded = self.is_loaded.pipe(function() {
2185             var active_view = self.viewmanager.active_view;
2186             var view = self.viewmanager.views[active_view].controller;
2187             if(active_view === "list") {
2188                 return view.reload_content();
2189             } else if (active_view === "form" || active_view === 'page') {
2190                 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2191                     self.dataset.index = 0;
2192                 }
2193                 var act = function() {
2194                     return view.do_show();
2195                 };
2196                 self.form_last_update = self.form_last_update.pipe(act, act);
2197                 return self.form_last_update;
2198             } else if (active_view === "graph") {
2199                 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2200             }
2201         }, undefined);
2202     },
2203     set_value: function(value) {
2204         value = value || [];
2205         var self = this;
2206         this.dataset.reset_ids([]);
2207         if(value.length >= 1 && value[0] instanceof Array) {
2208             var ids = [];
2209             _.each(value, function(command) {
2210                 var obj = {values: command[2]};
2211                 switch (command[0]) {
2212                     case commands.CREATE:
2213                         obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2214                         obj.defaults = {};
2215                         self.dataset.to_create.push(obj);
2216                         self.dataset.cache.push(_.clone(obj));
2217                         ids.push(obj.id);
2218                         return;
2219                     case commands.UPDATE:
2220                         obj['id'] = command[1];
2221                         self.dataset.to_write.push(obj);
2222                         self.dataset.cache.push(_.clone(obj));
2223                         ids.push(obj.id);
2224                         return;
2225                     case commands.DELETE:
2226                         self.dataset.to_delete.push({id: command[1]});
2227                         return;
2228                     case commands.LINK_TO:
2229                         ids.push(command[1]);
2230                         return;
2231                     case commands.DELETE_ALL:
2232                         self.dataset.delete_all = true;
2233                         return;
2234                 }
2235             });
2236             this._super(ids);
2237             this.dataset.set_ids(ids);
2238         } else if (value.length >= 1 && typeof(value[0]) === "object") {
2239             var ids = [];
2240             this.dataset.delete_all = true;
2241             _.each(value, function(command) {
2242                 var obj = {values: command};
2243                 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2244                 obj.defaults = {};
2245                 self.dataset.to_create.push(obj);
2246                 self.dataset.cache.push(_.clone(obj));
2247                 ids.push(obj.id);
2248             });
2249             this._super(ids);
2250             this.dataset.set_ids(ids);
2251         } else {
2252             this._super(value);
2253             this.dataset.reset_ids(value);
2254         }
2255         if (this.dataset.index === null && this.dataset.ids.length > 0) {
2256             this.dataset.index = 0;
2257         }
2258         self.is_setted.resolve();
2259         return self.reload_current_view();
2260     },
2261     get_value: function() {
2262         var self = this;
2263         if (!this.dataset)
2264             return [];
2265         this.save_any_view();
2266         var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2267         val = val.concat(_.map(this.dataset.ids, function(id) {
2268             var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2269             if (alter_order) {
2270                 return commands.create(alter_order.values);
2271             }
2272             alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2273             if (alter_order) {
2274                 return commands.update(alter_order.id, alter_order.values);
2275             }
2276             return commands.link_to(id);
2277         }));
2278         return val.concat(_.map(
2279             this.dataset.to_delete, function(x) {
2280                 return commands['delete'](x.id);}));
2281     },
2282     save_any_view: function() {
2283         if (this.doing_on_change)
2284             return false;
2285         return this.session.synchronized_mode(_.bind(function() {
2286                 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2287                     this.viewmanager.views[this.viewmanager.active_view] &&
2288                     this.viewmanager.views[this.viewmanager.active_view].controller) {
2289                     var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2290                     if (this.viewmanager.active_view === "form") {
2291                         if (!view.is_initialized.isResolved()) {
2292                             return false;
2293                         }
2294                         var res = $.when(view.do_save());
2295                         if (!res.isResolved() && !res.isRejected()) {
2296                             console.warn("Asynchronous get_value() is not supported in form view.");
2297                         }
2298                         return res;
2299                     } else if (this.viewmanager.active_view === "list") {
2300                         var res = $.when(view.ensure_saved());
2301                         if (!res.isResolved() && !res.isRejected()) {
2302                             console.warn("Asynchronous get_value() is not supported in list view.");
2303                         }
2304                         return res;
2305                     }
2306                 }
2307                 return false;
2308             }, this));
2309     },
2310     is_valid: function() {
2311         this.validate();
2312         return this._super();
2313     },
2314     validate: function() {
2315         this.invalid = false;
2316         if (!this.viewmanager.views[this.viewmanager.active_view])
2317             return;
2318         var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2319         if (this.viewmanager.active_view === "form") {
2320             for (var f in view.fields) {
2321                 f = view.fields[f];
2322                 if (!f.is_valid()) {
2323                     this.invalid = true;
2324                     return;
2325                 }
2326             }
2327         }
2328     },
2329     is_dirty: function() {
2330         this.save_any_view();
2331         return this._super();
2332     },
2333     update_dom: function() {
2334         this._super.apply(this, arguments);
2335         var self = this;
2336         if (this.previous_readonly !== this.readonly) {
2337             this.previous_readonly = this.readonly;
2338             if (this.viewmanager) {
2339                 this.is_loaded = this.is_loaded.pipe(function() {
2340                     self.viewmanager.stop();
2341                     return $.when(self.load_views()).then(function() {
2342                         self.reload_current_view();
2343                     });
2344                 });
2345             }
2346         }
2347     }
2348 });
2349
2350 openerp.web.form.One2ManyDataSet = openerp.web.BufferedDataSet.extend({
2351     get_context: function() {
2352         this.context = this.o2m.build_context([this.o2m.name]);
2353         return this.context;
2354     }
2355 });
2356
2357 openerp.web.form.One2ManyListView = openerp.web.ListView.extend({
2358     _template: 'One2Many.listview',
2359     do_add_record: function () {
2360         if (this.options.editable) {
2361             this._super.apply(this, arguments);
2362         } else {
2363             var self = this;
2364             var pop = new openerp.web.form.SelectCreatePopup(this);
2365             pop.on_default_get.add(self.dataset.on_default_get);
2366             pop.select_element(
2367                 self.o2m.field.relation,
2368                 {
2369                     title: _t("Create: ") + self.name,
2370                     initial_view: "form",
2371                     alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2372                     create_function: function(data, callback, error_callback) {
2373                         return self.o2m.dataset.create(data).then(function(r) {
2374                             self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2375                             self.o2m.dataset.on_change();
2376                         }).then(callback, error_callback);
2377                     },
2378                     read_function: function() {
2379                         return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2380                     },
2381                     parent_view: self.o2m.view,
2382                     child_name: self.o2m.name,
2383                     form_view_options: {'not_interactible_on_create':true}
2384                 },
2385                 self.o2m.build_domain(),
2386                 self.o2m.build_context()
2387             );
2388             pop.on_select_elements.add_last(function() {
2389                 self.o2m.reload_current_view();
2390             });
2391         }
2392     },
2393     do_activate_record: function(index, id) {
2394         var self = this;
2395         var pop = new openerp.web.form.FormOpenPopup(self.o2m.view);
2396         pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2397             title: _t("Open: ") + self.name,
2398             auto_write: false,
2399             alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2400             parent_view: self.o2m.view,
2401             child_name: self.o2m.name,
2402             read_function: function() {
2403                 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2404             },
2405             form_view_options: {'not_interactible_on_create':true},
2406             readonly: self.o2m.is_readonly()
2407         });
2408         pop.on_write.add(function(id, data) {
2409             self.o2m.dataset.write(id, data, {}, function(r) {
2410                 self.o2m.reload_current_view();
2411             });
2412         });
2413     },
2414     do_button_action: function (name, id, callback) {
2415         var self = this;
2416         var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
2417         return this._super(name, id, _.bind(def.resolve, def));
2418     },
2419 });
2420
2421 openerp.web.form.One2ManyFormView = openerp.web.FormView.extend({
2422     form_template: 'One2Many.formview',
2423     on_loaded: function(data) {
2424         this._super(data);
2425         this.$form_header.find('button.oe_form_button_create').click(this.on_button_new);
2426     }
2427 });
2428
2429 openerp.web.form.FieldMany2Many = openerp.web.form.Field.extend({
2430     template: 'FieldMany2Many',
2431     multi_selection: false,
2432     init: function(view, node) {
2433         this._super(view, node);
2434         this.list_id = _.uniqueId("many2many");
2435         this.is_loaded = $.Deferred();
2436         this.initial_is_loaded = this.is_loaded;
2437         this.is_setted = $.Deferred();
2438     },
2439     start: function() {
2440         this._super.apply(this, arguments);
2441
2442         var self = this;
2443
2444         this.dataset = new openerp.web.form.Many2ManyDataSet(this, this.field.relation);
2445         this.dataset.m2m = this;
2446         this.dataset.on_unlink.add_last(function(ids) {
2447             self.on_ui_change();
2448         });
2449         
2450         this.is_setted.then(function() {
2451             self.load_view();
2452         });
2453     },
2454     set_value: function(value) {
2455         value = value || [];
2456         if (value.length >= 1 && value[0] instanceof Array) {
2457             value = value[0][2];
2458         }
2459         this._super(value);
2460         this.dataset.set_ids(value);
2461         var self = this;
2462         self.reload_content();
2463         this.is_setted.resolve();
2464     },
2465     get_value: function() {
2466         return [commands.replace_with(this.dataset.ids)];
2467     },
2468     validate: function() {
2469         this.invalid = false;
2470     },
2471     is_readonly: function() {
2472         return this.readonly || this.force_readonly;
2473     },
2474     load_view: function() {
2475         var self = this;
2476         this.list_view = new openerp.web.form.Many2ManyListView(this, this.dataset, false, {
2477                     'addable': self.is_readonly() ? null : _t("Add"),
2478                     'deletable': self.is_readonly() ? false : true,
2479                     'selectable': self.multi_selection,
2480                     'isClarkGable': self.is_readonly() ? false : true
2481             });
2482         var embedded = (this.field.views || {}).tree;
2483         if (embedded) {
2484             this.list_view.set_embedded_view(embedded);
2485         }
2486         this.list_view.m2m_field = this;
2487         var loaded = $.Deferred();
2488         this.list_view.on_loaded.add_last(function() {
2489             self.initial_is_loaded.resolve();
2490             loaded.resolve();
2491         });
2492         $.async_when().then(function () {
2493             self.list_view.appendTo($("#" + self.list_id));
2494         });
2495         return loaded;
2496     },
2497     reload_content: function() {
2498         var self = this;
2499         this.is_loaded = this.is_loaded.pipe(function() {
2500             return self.list_view.reload_content();
2501         });
2502     },
2503     update_dom: function() {
2504         this._super.apply(this, arguments);
2505         var self = this;
2506         if (this.previous_readonly !== this.readonly) {
2507             this.previous_readonly = this.readonly;
2508             if (this.list_view) {
2509                 this.is_loaded = this.is_loaded.pipe(function() {
2510                     self.list_view.stop();
2511                     return $.when(self.load_view()).then(function() {
2512                         self.reload_content();
2513                     });
2514                 });
2515             }
2516         }
2517     }
2518 });
2519
2520 openerp.web.form.Many2ManyDataSet = openerp.web.DataSetStatic.extend({
2521     get_context: function() {
2522         this.context = this.m2m.build_context();
2523         return this.context;
2524     }
2525 });
2526
2527 /**
2528  * @class
2529  * @extends openerp.web.ListView
2530  */
2531 openerp.web.form.Many2ManyListView = openerp.web.ListView.extend(/** @lends openerp.web.form.Many2ManyListView# */{
2532     do_add_record: function () {
2533         var pop = new openerp.web.form.SelectCreatePopup(this);
2534         pop.select_element(
2535             this.model,
2536             {
2537                 title: _t("Add: ") + this.name
2538             },
2539             new openerp.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
2540             this.m2m_field.build_context()
2541         );
2542         var self = this;
2543         pop.on_select_elements.add(function(element_ids) {
2544             _.each(element_ids, function(element_id) {
2545                 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
2546                     self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
2547                     self.m2m_field.on_ui_change();
2548                     self.reload_content();
2549                 }
2550             });
2551         });
2552     },
2553     do_activate_record: function(index, id) {
2554         var self = this;
2555         var pop = new openerp.web.form.FormOpenPopup(this);
2556         pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
2557             title: _t("Open: ") + this.name,
2558             readonly: this.widget_parent.is_readonly()
2559         });
2560         pop.on_write_completed.add_last(function() {
2561             self.reload_content();
2562         });
2563     }
2564 });
2565
2566 /**
2567  * @class
2568  * @extends openerp.web.OldWidget
2569  */
2570 openerp.web.form.SelectCreatePopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.SelectCreatePopup# */{
2571     identifier_prefix: "selectcreatepopup",
2572     template: "SelectCreatePopup",
2573     /**
2574      * options:
2575      * - initial_ids
2576      * - initial_view: form or search (default search)
2577      * - disable_multiple_selection
2578      * - alternative_form_view
2579      * - create_function (defaults to a naive saving behavior)
2580      * - parent_view
2581      * - child_name
2582      * - form_view_options
2583      * - list_view_options
2584      * - read_function
2585      */
2586     select_element: function(model, options, domain, context) {
2587         var self = this;
2588         this.model = model;
2589         this.domain = domain || [];
2590         this.context = context || {};
2591         this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
2592             return self.create_row.apply(self, arguments);
2593         }, read_function: null});
2594         this.initial_ids = this.options.initial_ids;
2595         this.created_elements = [];
2596         this.render_element();
2597         openerp.web.form.dialog(this.$element, {
2598             close: function() {
2599                 self.check_exit();
2600             },
2601             title: options.title || ""
2602         });
2603         this.start();
2604     },
2605     start: function() {
2606         this._super();
2607         var self = this;
2608         this.dataset = new openerp.web.ProxyDataSet(this, this.model,
2609             this.context);
2610         this.dataset.create_function = function() {
2611             return self.options.create_function.apply(null, arguments).then(function(r) {
2612                 self.created_elements.push(r.result);
2613             });
2614         };
2615         this.dataset.write_function = function() {
2616             return self.write_row.apply(self, arguments);
2617         };
2618         this.dataset.read_function = this.options.read_function;
2619         this.dataset.parent_view = this.options.parent_view;
2620         this.dataset.child_name = this.options.child_name;
2621         this.dataset.on_default_get.add(this.on_default_get);
2622         if (this.options.initial_view == "search") {
2623             self.rpc('/web/session/eval_domain_and_context', {
2624                 domains: [],
2625                 contexts: [this.context]
2626             }, function (results) {
2627                 var search_defaults = {};
2628                 _.each(results.context, function (value, key) {
2629                     var match = /^search_default_(.*)$/.exec(key);
2630                     if (match) {
2631                         search_defaults[match[1]] = value;
2632                     }
2633                 });
2634                 self.setup_search_view(search_defaults);
2635             });
2636         } else { // "form"
2637             this.new_object();
2638         }
2639     },
2640     setup_search_view: function(search_defaults) {
2641         var self = this;
2642         if (this.searchview) {
2643             this.searchview.stop();
2644         }
2645         this.searchview = new openerp.web.SearchView(this,
2646                 this.dataset, false,  search_defaults);
2647         this.searchview.on_search.add(function(domains, contexts, groupbys) {
2648             if (self.initial_ids) {
2649                 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
2650                     contexts, groupbys);
2651                 self.initial_ids = undefined;
2652             } else {
2653                 self.do_search(domains.concat([self.domain]), contexts, groupbys);
2654             }
2655         });
2656         this.searchview.on_loaded.add_last(function () {
2657             self.view_list = new openerp.web.form.SelectCreateListView(self,
2658                     self.dataset, false,
2659                     _.extend({'deletable': false,
2660                         'selectable': !self.options.disable_multiple_selection
2661                     }, self.options.list_view_options || {}));
2662             self.view_list.popup = self;
2663             self.view_list.appendTo($("#" + self.element_id + "_view_list")).pipe(function() {
2664                 self.view_list.do_show();
2665             }).pipe(function() {
2666                 self.searchview.do_search();
2667             });
2668             self.view_list.on_loaded.add_last(function() {
2669                 var $buttons = self.view_list.$element.find(".oe-actions");
2670                 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
2671                 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
2672                 $cbutton.click(function() {
2673                     self.stop();
2674                 });
2675                 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
2676                 if(self.options.disable_multiple_selection) {
2677                     $sbutton.hide();
2678                 }
2679                 $sbutton.click(function() {
2680                     self.on_select_elements(self.selected_ids);
2681                     self.stop();
2682                 });
2683             });
2684         });
2685         this.searchview.appendTo($("#" + this.element_id + "_search"));
2686     },
2687     do_search: function(domains, contexts, groupbys) {
2688         var self = this;
2689         this.rpc('/web/session/eval_domain_and_context', {
2690             domains: domains || [],
2691             contexts: contexts || [],
2692             group_by_seq: groupbys || []
2693         }, function (results) {
2694             self.view_list.do_search(results.domain, results.context, results.group_by);
2695         });
2696     },
2697     create_row: function() {
2698         var self = this;
2699         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2700         wdataset.parent_view = this.options.parent_view;
2701         wdataset.child_name = this.options.child_name;
2702         return wdataset.create.apply(wdataset, arguments);
2703     },
2704     write_row: function() {
2705         var self = this;
2706         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2707         wdataset.parent_view = this.options.parent_view;
2708         wdataset.child_name = this.options.child_name;
2709         return wdataset.write.apply(wdataset, arguments);
2710     },
2711     on_select_elements: function(element_ids) {
2712     },
2713     on_click_element: function(ids) {
2714         this.selected_ids = ids || [];
2715         if(this.selected_ids.length > 0) {
2716             this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
2717         } else {
2718             this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
2719         }
2720     },
2721     new_object: function() {
2722         var self = this;
2723         if (this.searchview) {
2724             this.searchview.hide();
2725         }
2726         if (this.view_list) {
2727             this.view_list.$element.hide();
2728         }
2729         this.dataset.index = null;
2730         this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
2731         if (this.options.alternative_form_view) {
2732             this.view_form.set_embedded_view(this.options.alternative_form_view);
2733         }
2734         this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2735         this.view_form.on_loaded.add_last(function() {
2736             var $buttons = self.view_form.$element.find(".oe_form_buttons");
2737             $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
2738             var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
2739             $nbutton.click(function() {
2740                 $.when(self.view_form.do_save()).then(function() {
2741                     self.view_form.reload_mutex.exec(function() {
2742                         self.view_form.on_button_new();
2743                     });
2744                 });
2745             });
2746             var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
2747             $nbutton.click(function() {
2748                 $.when(self.view_form.do_save()).then(function() {
2749                     self.view_form.reload_mutex.exec(function() {
2750                         self.check_exit();
2751                     });
2752                 });
2753             });
2754             var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
2755             $cbutton.click(function() {
2756                 self.check_exit();
2757             });
2758         });
2759         this.view_form.do_show();
2760     },
2761     check_exit: function() {
2762         if (this.created_elements.length > 0) {
2763             this.on_select_elements(this.created_elements);
2764         }
2765         this.stop();
2766     },
2767     on_default_get: function(res) {}
2768 });
2769
2770 openerp.web.form.SelectCreateListView = openerp.web.ListView.extend({
2771     do_add_record: function () {
2772         this.popup.new_object();
2773     },
2774     select_record: function(index) {
2775         this.popup.on_select_elements([this.dataset.ids[index]]);
2776         this.popup.stop();
2777     },
2778     do_select: function(ids, records) {
2779         this._super(ids, records);
2780         this.popup.on_click_element(ids);
2781     }
2782 });
2783
2784 /**
2785  * @class
2786  * @extends openerp.web.OldWidget
2787  */
2788 openerp.web.form.FormOpenPopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.FormOpenPopup# */{
2789     identifier_prefix: "formopenpopup",
2790     template: "FormOpenPopup",
2791     /**
2792      * options:
2793      * - alternative_form_view
2794      * - auto_write (default true)
2795      * - read_function
2796      * - parent_view
2797      * - child_name
2798      * - form_view_options
2799      * - readonly
2800      */
2801     show_element: function(model, row_id, context, options) {
2802         this.model = model;
2803         this.row_id = row_id;
2804         this.context = context || {};
2805         this.options = _.defaults(options || {}, {"auto_write": true});
2806         this.render_element();
2807         this.$element.dialog({
2808             title: options.title || '',
2809             modal: true,
2810             width: 960,
2811             height: 600
2812         });
2813         this.start();
2814     },
2815     start: function() {
2816         this._super();
2817         this.dataset = new openerp.web.form.FormOpenDataset(this, this.model, this.context);
2818         this.dataset.fop = this;
2819         this.dataset.ids = [this.row_id];
2820         this.dataset.index = 0;
2821         this.dataset.parent_view = this.options.parent_view;
2822         this.dataset.child_name = this.options.child_name;
2823         this.setup_form_view();
2824     },
2825     on_write: function(id, data) {
2826         if (!this.options.auto_write)
2827             return;
2828         var self = this;
2829         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2830         wdataset.parent_view = this.options.parent_view;
2831         wdataset.child_name = this.options.child_name;
2832         wdataset.write(id, data, {}, function(r) {
2833             self.on_write_completed();
2834         });
2835     },
2836     on_write_completed: function() {},
2837     setup_form_view: function() {
2838         var self = this;
2839         var FormClass = this.options.readonly
2840                 ? openerp.web.views.get_object('page')
2841                 : openerp.web.views.get_object('form');
2842         this.view_form = new FormClass(this, this.dataset, false, self.options.form_view_options);
2843         if (this.options.alternative_form_view) {
2844             this.view_form.set_embedded_view(this.options.alternative_form_view);
2845         }
2846         this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2847         this.view_form.on_loaded.add_last(function() {
2848             var $buttons = self.view_form.$element.find(".oe_form_buttons");
2849             $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
2850             var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
2851             $nbutton.click(function() {
2852                 self.view_form.do_save().then(function() {
2853                     self.stop();
2854                 });
2855             });
2856             var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
2857             $cbutton.click(function() {
2858                 self.stop();
2859             });
2860             if (self.options.readonly) {
2861                 $nbutton.hide();
2862                 $cbutton.text(_t("Close"));
2863             }
2864             self.view_form.do_show();
2865         });
2866         this.dataset.on_write.add(this.on_write);
2867     }
2868 });
2869
2870 openerp.web.form.FormOpenDataset = openerp.web.ProxyDataSet.extend({
2871     read_ids: function() {
2872         if (this.fop.options.read_function) {
2873             return this.fop.options.read_function.apply(null, arguments);
2874         } else {
2875             return this._super.apply(this, arguments);
2876         }
2877     }
2878 });
2879
2880 openerp.web.form.FieldReference = openerp.web.form.Field.extend({
2881     template: 'FieldReference',
2882     init: function(view, node) {
2883         this._super(view, node);
2884         this.fields_view = {
2885             fields: {
2886                 selection: {
2887                     selection: view.fields_view.fields[this.name].selection
2888                 },
2889                 m2o: {
2890                     relation: null
2891                 }
2892             }
2893         };
2894         this.get_fields_values = view.get_fields_values;
2895         this.do_onchange = this.on_form_changed = this.on_nop;
2896         this.dataset = this.view.dataset;
2897         this.widgets_counter = 0;
2898         this.view_id = 'reference_' + _.uniqueId();
2899         this.widgets = {};
2900         this.fields = {};
2901         this.fields_order = [];
2902         this.selection = new openerp.web.form.FieldSelection(this, { attrs: {
2903             name: 'selection',
2904             widget: 'selection'
2905         }});
2906         this.reference_ready = true;
2907         this.selection.on_value_changed.add_last(this.on_selection_changed);
2908         this.m2o = new openerp.web.form.FieldMany2One(this, { attrs: {
2909             name: 'm2o',
2910             widget: 'many2one'
2911         }});
2912     },
2913     on_nop: function() {
2914     },
2915     on_selection_changed: function() {
2916         if (this.reference_ready) {
2917             var sel = this.selection.get_value();
2918             this.m2o.field.relation = sel;
2919             this.m2o.set_value(null);
2920             this.m2o.$element.toggle(sel !== false);
2921         }
2922     },
2923     start: function() {
2924         this._super();
2925         this.selection.start();
2926         this.m2o.start();
2927     },
2928     is_valid: function() {
2929         return this.required === false || typeof(this.get_value()) === 'string';
2930     },
2931     is_dirty: function() {
2932         return this.selection.is_dirty() || this.m2o.is_dirty();
2933     },
2934     set_value: function(value) {
2935         this._super(value);
2936         this.reference_ready = false;
2937         var vals = [], sel_val, m2o_val;
2938         if (typeof(value) === 'string') {
2939             vals = value.split(',');
2940         }
2941         sel_val = vals[0] || false;
2942         m2o_val = vals[1] ? parseInt(vals[1], 10) : false;
2943         this.selection.set_value(sel_val);
2944         this.m2o.field.relation = sel_val;
2945         this.m2o.set_value(m2o_val);
2946         this.m2o.$element.toggle(sel_val !== false);
2947         this.reference_ready = true;
2948     },
2949     get_value: function() {
2950         var model = this.selection.get_value(),
2951             id = this.m2o.get_value();
2952         if (typeof(model) === 'string' && typeof(id) === 'number') {
2953             return model + ',' + id;
2954         } else {
2955             return false;
2956         }
2957     }
2958 });
2959
2960 openerp.web.form.FieldBinary = openerp.web.form.Field.extend({
2961     init: function(view, node) {
2962         this._super(view, node);
2963         this.iframe = this.element_id + '_iframe';
2964         this.binary_value = false;
2965     },
2966     start: function() {
2967         this._super.apply(this, arguments);
2968         this.$element.find('input.oe-binary-file').change(this.on_file_change);
2969         this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
2970         this.$element.find('.oe-binary-file-clear').click(this.on_clear);
2971     },
2972     human_filesize : function(size) {
2973         var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
2974         var i = 0;
2975         while (size >= 1024) {
2976             size /= 1024;
2977             ++i;
2978         }
2979         return size.toFixed(2) + ' ' + units[i];
2980     },
2981     on_file_change: function(e) {
2982         // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
2983         // http://www.html5rocks.com/tutorials/file/dndfiles/
2984         // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
2985         window[this.iframe] = this.on_file_uploaded;
2986         if ($(e.target).val() != '') {
2987             this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
2988             this.$element.find('form.oe-binary-form').submit();
2989             this.$element.find('.oe-binary-progress').show();
2990             this.$element.find('.oe-binary').hide();
2991         }
2992     },
2993     on_file_uploaded: function(size, name, content_type, file_base64) {
2994         delete(window[this.iframe]);
2995         if (size === false) {
2996             this.do_warn("File Upload", "There was a problem while uploading your file");
2997             // TODO: use openerp web crashmanager
2998             console.warn("Error while uploading file : ", name);
2999         } else {
3000             this.on_file_uploaded_and_valid.apply(this, arguments);
3001             this.on_ui_change();
3002         }
3003         this.$element.find('.oe-binary-progress').hide();
3004         this.$element.find('.oe-binary').show();
3005     },
3006     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3007     },
3008     on_save_as: function() {
3009         var url = '/web/binary/saveas?session_id=' + this.session.session_id + '&model=' +
3010             this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name +
3011             '&filename_field=' + (this.node.attrs.filename || '') + '&t=' + (new Date().getTime());
3012         window.open(url);
3013     },
3014     on_clear: function() {
3015         if (this.value !== false) {
3016             this.value = false;
3017             this.binary_value = false;
3018             this.on_ui_change();
3019         }
3020         return false;
3021     }
3022 });
3023
3024 openerp.web.form.FieldBinaryFile = openerp.web.form.FieldBinary.extend({
3025     template: 'FieldBinaryFile',
3026     update_dom: function() {
3027         this._super.apply(this, arguments);
3028         this.$element.find('.oe-binary-file-set, .oe-binary-file-clear').toggle(!this.readonly);
3029         this.$element.find('input[type=text]').prop('disabled', this.readonly);
3030     },
3031     set_value: function(value) {
3032         this._super.apply(this, arguments);
3033         var show_value;
3034         if (this.node.attrs.filename) {
3035             show_value = this.view.datarecord[this.node.attrs.filename] || '';
3036         } else {
3037             show_value = (value != null && value !== false) ? value : '';
3038         }
3039         this.$element.find('input').eq(0).val(show_value);
3040     },
3041     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3042         this.value = file_base64;
3043         this.binary_value = true;
3044         var show_value = name + " (" + this.human_filesize(size) + ")";
3045         this.$element.find('input').eq(0).val(show_value);
3046         this.set_filename(name);
3047     },
3048     set_filename: function(value) {
3049         var filename = this.node.attrs.filename;
3050         if (this.view.fields[filename]) {
3051             this.view.fields[filename].set_value(value);
3052             this.view.fields[filename].on_ui_change();
3053         }
3054     },
3055     on_clear: function() {
3056         this._super.apply(this, arguments);
3057         this.$element.find('input').eq(0).val('');
3058         this.set_filename('');
3059     }
3060 });
3061
3062 openerp.web.form.FieldBinaryImage = openerp.web.form.FieldBinary.extend({
3063     template: 'FieldBinaryImage',
3064     start: function() {
3065         this._super.apply(this, arguments);
3066         this.$image = this.$element.find('img.oe-binary-image');
3067     },
3068     update_dom: function() {
3069         this._super.apply(this, arguments);
3070         this.$element.find('.oe-binary').toggle(!this.readonly);
3071     },
3072     set_value: function(value) {
3073         this._super.apply(this, arguments);
3074         this.set_image_maxwidth();
3075         var url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
3076             this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
3077         this.$image.attr('src', url);
3078     },
3079     set_image_maxwidth: function() {
3080         this.$image.css('max-width', this.$element.width());
3081     },
3082     on_file_change: function() {
3083         this.set_image_maxwidth();
3084         this._super.apply(this, arguments);
3085     },
3086     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3087         this.value = file_base64;
3088         this.binary_value = true;
3089         this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
3090     },
3091     on_clear: function() {
3092         this._super.apply(this, arguments);
3093         this.$image.attr('src', '/web/static/src/img/placeholder.png');
3094     }
3095 });
3096
3097 openerp.web.form.FieldStatus = openerp.web.form.Field.extend({
3098     template: "EmptyComponent",
3099     start: function() {
3100         this._super();
3101         this.selected_value = null;
3102
3103         this.render_list();
3104     },
3105     set_value: function(value) {
3106         this._super(value);
3107         this.selected_value = value;
3108
3109         this.render_list();
3110     },
3111     render_list: function() {
3112         var self = this;
3113         var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
3114             function(x) { return _.str.trim(x); });
3115         shown = _.select(shown, function(x) { return x.length > 0; });
3116
3117         if (shown.length == 0) {
3118             this.to_show = this.field.selection;
3119         } else {
3120             this.to_show = _.select(this.field.selection, function(x) {
3121                 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
3122             });
3123         }
3124
3125         var content = openerp.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3126         this.$element.html(content);
3127
3128         var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3129         var color = colors[this.selected_value];
3130         if (color) {
3131             var elem = this.$element.find("li.oe-arrow-list-selected span");
3132             elem.css("border-color", color);
3133             if (this.check_white(color))
3134                 elem.css("color", "white");
3135             elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3136             elem.css("border-left-color", "rgba(0,0,0,0)");
3137             elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3138             elem.css("border-color", "rgba(0,0,0,0)");
3139             elem.css("border-left-color", color);
3140         }
3141     },
3142     check_white: function(color) {
3143         var div = $("<div></div>");
3144         div.css("display", "none");
3145         div.css("color", color);
3146         div.appendTo($("body"));
3147         var ncolor = div.css("color");
3148         div.remove();
3149         var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3150         if (!res) {
3151             return false;
3152         }
3153         var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3154         var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3155         if (lum < 128) {
3156             return true;
3157         }
3158         return false;
3159     }
3160 });
3161
3162 openerp.web.form.WidgetHtml = openerp.web.form.Widget.extend({
3163     render: function () {
3164         var $root = $('<div class="oe_form_html_view">');
3165         this.render_children(this, $root);
3166         return $root.html();
3167     },
3168     render_children: function (object, $into) {
3169         var self = this,
3170             fields = this.view.fields_view.fields;
3171         _(object.children).each(function (child) {
3172             if (typeof child === 'string') {
3173                 $into.text(child);
3174             } else if (child.tag === 'field') {
3175                 $into.append(
3176                     new (self.view.registry.get_object('frame'))(
3177                         self.view, {tag: 'ueule', attrs: {}, children: [child] })
3178                             .render());
3179             } else {
3180                 var $child = $(document.createElement(child.tag))
3181                         .attr(child.attrs)
3182                         .appendTo($into);
3183                 self.render_children(child, $child);
3184             }
3185         });
3186     }
3187 });
3188
3189
3190 /**
3191  * Registry of form widgets, called by :js:`openerp.web.FormView`
3192  */
3193 openerp.web.form.widgets = new openerp.web.Registry({
3194     'frame' : 'openerp.web.form.WidgetFrame',
3195     'group' : 'openerp.web.form.WidgetGroup',
3196     'notebook' : 'openerp.web.form.WidgetNotebook',
3197     'notebookpage' : 'openerp.web.form.WidgetNotebookPage',
3198     'separator' : 'openerp.web.form.WidgetSeparator',
3199     'label' : 'openerp.web.form.WidgetLabel',
3200     'button' : 'openerp.web.form.WidgetButton',
3201     'char' : 'openerp.web.form.FieldChar',
3202     'email' : 'openerp.web.form.FieldEmail',
3203     'url' : 'openerp.web.form.FieldUrl',
3204     'text' : 'openerp.web.form.FieldText',
3205     'text_wiki' : 'openerp.web.form.FieldText',
3206     'date' : 'openerp.web.form.FieldDate',
3207     'datetime' : 'openerp.web.form.FieldDatetime',
3208     'selection' : 'openerp.web.form.FieldSelection',
3209     'many2one' : 'openerp.web.form.FieldMany2One',
3210     'many2many' : 'openerp.web.form.FieldMany2Many',
3211     'one2many' : 'openerp.web.form.FieldOne2Many',
3212     'one2many_list' : 'openerp.web.form.FieldOne2Many',
3213     'reference' : 'openerp.web.form.FieldReference',
3214     'boolean' : 'openerp.web.form.FieldBoolean',
3215     'float' : 'openerp.web.form.FieldFloat',
3216     'integer': 'openerp.web.form.FieldFloat',
3217     'float_time': 'openerp.web.form.FieldFloat',
3218     'progressbar': 'openerp.web.form.FieldProgressBar',
3219     'image': 'openerp.web.form.FieldBinaryImage',
3220     'binary': 'openerp.web.form.FieldBinaryFile',
3221     'statusbar': 'openerp.web.form.FieldStatus',
3222     'html': 'openerp.web.form.WidgetHtml'
3223 });
3224
3225
3226 };
3227
3228 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: