[merge]
[odoo/odoo.git] / addons / base / static / src / js / form.js
1 openerp.base.form = function (openerp) {
2
3 openerp.base.views.add('form', 'openerp.base.FormView');
4 openerp.base.FormView =  openerp.base.View.extend( /** @lends openerp.base.FormView# */{
5     /**
6      * Indicates that this view is not searchable, and thus that no search
7      * view should be displayed (if there is one active).
8      */
9     searchable: false,
10     template: "FormView",
11     /**
12      * @constructs
13      * @param {openerp.base.Session} session the current openerp session
14      * @param {String} element_id this view's root element id
15      * @param {openerp.base.DataSet} dataset the dataset this view will work with
16      * @param {String} view_id the identifier of the OpenERP view object
17      *
18      * @property {openerp.base.Registry} registry=openerp.base.form.widgets widgets registry for this form view instance
19      */
20     init: function(view_manager, session, element_id, dataset, view_id) {
21         this._super(session, element_id);
22         this.view_manager = view_manager || new openerp.base.NullViewManager();
23         this.dataset = dataset;
24         this.model = dataset.model;
25         this.view_id = view_id;
26         this.fields_view = {};
27         this.widgets = {};
28         this.widgets_counter = 0;
29         this.fields = {};
30         this.datarecord = {};
31         this.ready = false;
32         this.show_invalid = true;
33         this.touched = false;
34         this.flags = this.view_manager.flags || {};
35         this.default_focus_field = null;
36         this.default_focus_button = null;
37         this.registry = openerp.base.form.widgets;
38         this.has_been_loaded = $.Deferred();
39         this.$form_header = null;
40     },
41     start: function() {
42         //this.log('Starting FormView '+this.model+this.view_id)
43         if (this.embedded_view) {
44             return $.Deferred().then(this.on_loaded).resolve({fields_view: this.embedded_view});
45         } else {
46             var context = new openerp.base.CompoundContext(this.dataset.context);
47             if (this.view_manager.action && this.view_manager.action.context) {
48                 context.add(this.view_manager.action.context);
49             }
50             return this.rpc("/base/formview/load", {"model": this.model, "view_id": this.view_id,
51                 toolbar:!!this.flags.sidebar, context: context}, this.on_loaded);
52         }
53     },
54     on_loaded: function(data) {
55         var self = this;
56         this.fields_view = data.fields_view;
57         var frame = new (this.registry.get_object('frame'))(this, this.fields_view.arch);
58
59         this.$element.html(QWeb.render(this.template, { 'frame': frame, 'view': this }));
60         _.each(this.widgets, function(w) {
61             w.start();
62         });
63         this.$form_header = this.$element.find('#' + this.element_id + '_header');
64         this.$form_header.find('div.oe_form_pager button[data-pager-action]').click(function() {
65             var action = $(this).data('pager-action');
66             self.on_pager_action(action);
67         });
68
69         this.$form_header.find('button.oe_form_button_save').click(this.do_save);
70         this.$form_header.find('button.oe_form_button_save_edit').click(this.do_save_edit);
71         this.$form_header.find('button.oe_form_button_cancel').click(this.do_cancel);
72         this.$form_header.find('button.oe_form_button_new').click(this.on_button_new);
73
74         this.view_manager.sidebar.set_toolbar(data.fields_view.toolbar);
75         this.has_been_loaded.resolve();
76     },
77     do_show: function () {
78         var self = this;
79         if (this.dataset.index === null) {
80             // null index means we should start a new record
81             this.on_button_new();
82         } else {
83             this.dataset.read_index(_.keys(this.fields_view.fields), this.on_record_loaded);
84         }
85         self.$element.show();
86         this.view_manager.sidebar.do_refresh(true);
87     },
88     do_hide: function () {
89         this.$element.hide();
90     },
91     on_record_loaded: function(record) {
92         if (!record) {
93             throw("Form: No record received");
94         }
95         if (!record.id) {
96             this.$form_header.find('.oe_form_on_create').show();
97             this.$form_header.find('.oe_form_on_update').hide();
98             this.$form_header.find('button.oe_form_button_new').hide();
99         } else {
100             this.$form_header.find('.oe_form_on_create').hide();
101             this.$form_header.find('.oe_form_on_update').show();
102             this.$form_header.find('button.oe_form_button_new').show();
103         }
104         this.touched = false;
105         this.datarecord = record;
106         for (var f in this.fields) {
107             var field = this.fields[f];
108             field.touched = false;
109             field.set_value(this.datarecord[f] || false);
110             field.validate();
111         }
112         if (!record.id) {
113             // New record: Second pass in order to trigger the onchanges
114             this.touched = true;
115             this.show_invalid = false;
116             for (var f in record) {
117                 var field = this.fields[f];
118                 if (field) {
119                     field.touched = true;
120                     this.do_onchange(field);
121                 }
122             }
123         }
124         this.on_form_changed();
125         this.show_invalid = this.ready = true;
126         this.do_update_pager(record.id == null);
127         this.do_update_sidebar();
128         if (this.default_focus_field) {
129             this.default_focus_field.focus();
130         }
131     },
132     on_form_changed: function() {
133         for (var w in this.widgets) {
134             w = this.widgets[w];
135             w.process_attrs();
136             w.update_dom();
137         }
138     },
139     on_pager_action: function(action) {
140         switch (action) {
141             case 'first':
142                 this.dataset.index = 0;
143                 break;
144             case 'previous':
145                 this.dataset.previous();
146                 break;
147             case 'next':
148                 this.dataset.next();
149                 break;
150             case 'last':
151                 this.dataset.index = this.dataset.ids.length - 1;
152                 break;
153         }
154         this.reload();
155     },
156     do_update_pager: function(hide_index) {
157         var $pager = this.$element.find('#' + this.element_id + '_header div.oe_form_pager');
158         var index = hide_index ? '-' : this.dataset.index + 1;
159         $pager.find('span.oe_pager_index').html(index);
160         $pager.find('span.oe_pager_count').html(this.dataset.ids.length);
161     },
162     do_onchange: function(widget, processed) {
163         processed = processed || [];
164         if (widget.node.attrs.on_change) {
165             var self = this;
166             this.ready = false;
167             var onchange = _.trim(widget.node.attrs.on_change);
168             var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
169             console.log("Onchange triggered for field '%s' -> %s", widget.name, onchange);
170             if (call) {
171                 var method = call[1], args = [];
172                 var argument_replacement = {
173                     'False' : false,
174                     'True' : true,
175                     'None' : null
176                 }
177                 var parent_fields = null;
178                 _.each(call[2].split(','), function(a) {
179                     var field = _.trim(a);
180                     if (field in argument_replacement) {
181                         args.push(argument_replacement[field]);
182                         return;
183                     } else if (self.fields[field]) {
184                         var value = self.fields[field].get_on_change_value();
185                         args.push(value == null ? false : value);
186                         return;
187                     } else {
188                         var splitted = field.split('.');
189                         if (splitted.length > 1 && _.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
190                             if (parent_fields === null) {
191                                 parent_fields = self.dataset.parent_view.get_fields_values();
192                             }
193                             var p_val = parent_fields[_.trim(splitted[1])];
194                             if (p_val !== undefined) {
195                                 args.push(value ? value : false);
196                                 return;
197                             }
198                         }
199                     }
200                     throw "Could not get field with name '" + field +
201                         "' for onchange '" + onchange + "'";
202                 });
203                 var ajax = {
204                     url: '/base/dataset/call',
205                     async: false
206                 };
207                 return this.rpc(ajax, {
208                     model: this.dataset.model,
209                     method: method,
210                     args: [(this.datarecord.id == null ? [] : [this.datarecord.id])].concat(args)
211                 }, function(response) {
212                     self.on_processed_onchange(response, processed);
213                 });
214             } else {
215                 this.log("Wrong on_change format", on_change);
216             }
217         }
218     },
219     on_processed_onchange: function(response, processed) {
220         var result = response.result;
221         if (result.value) {
222             console.log("      |-> Onchange Response :", result.value);
223             for (var f in result.value) {
224                 var field = this.fields[f];
225                 if (field) {
226                     var value = result.value[f];
227                     processed.push(field.name);
228                     if (field.get_value() != value) {
229                         console.log("          |-> Onchange Action :  change '%s' value from '%s' to '%s'", field.name, field.get_value(), value);
230                         field.set_value(value);
231                         field.touched = true;
232                         if (_.indexOf(processed, field.name) < 0) {
233                             this.do_onchange(field, processed);
234                         }
235                     }
236                 } else {
237                     // this is a common case, the normal behavior should be to ignore it
238                     this.log("on_processed_onchange can't find field " + f, result);
239                 }
240             }
241             this.on_form_changed();
242         }
243         if (result.warning) {
244             $(QWeb.render("DialogWarning", result.warning)).dialog({
245                 modal: true,
246                 buttons: {
247                     Ok: function() {
248                         $(this).dialog("close");
249                     }
250                 }
251             });
252         }
253         if (result.domain) {
254             // Will be removed ?
255         }
256         this.ready = true;
257     },
258     on_button_new: function() {
259         var self = this;
260         $.when(this.has_been_loaded).then(function() {
261             self.dataset.default_get(_.keys(self.fields_view.fields), function(result) {
262                 self.on_record_loaded(result.result);
263             });
264         });
265     },
266     /**
267      * Triggers saving the form's record. Chooses between creating a new
268      * record or saving an existing one depending on whether the record
269      * already has an id property.
270      *
271      * @param {Function} success callback on save success
272      * @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)
273      */
274     do_save: function(success, prepend_on_create) {
275         var self = this;
276         if (!this.ready) {
277             return false;
278         }
279         var invalid = false,
280             values = {},
281             first_invalid_field = null;
282         for (var f in this.fields) {
283             f = this.fields[f];
284             if (f.invalid) {
285                 invalid = true;
286                 f.update_dom();
287                 if (!first_invalid_field) {
288                     first_invalid_field = f;
289                 }
290             } else if (f.touched) {
291                 values[f.name] = f.get_value();
292             }
293         }
294         if (invalid) {
295             first_invalid_field.focus();
296             this.on_invalid();
297             return false;
298         } else {
299             this.log("About to save", values);
300             if (!this.datarecord.id) {
301                 this.dataset.create(values, function(r) {
302                     self.on_created(r, success, prepend_on_create);
303                 });
304             } else {
305                 this.dataset.write(this.datarecord.id, values, function(r) {
306                     self.on_saved(r, success);
307                 });
308             }
309             return true;
310         }
311     },
312     do_save_edit: function() {
313         this.do_save();
314         //this.switch_readonly(); Use promises
315     },
316     switch_readonly: function() {
317     },
318     switch_editable: function() {
319     },
320     on_invalid: function() {
321         var msg = "<ul>";
322         _.each(this.fields, function(f) {
323             if (f.invalid) {
324                 msg += "<li>" + f.string + "</li>";
325             }
326         });
327         msg += "</ul>";
328         this.notification.warn("The following fields are invalid :", msg);
329     },
330     on_saved: function(r, success) {
331         if (!r.result) {
332             this.notification.warn("Record not saved", "Problem while saving record.");
333         } else {
334             this.notification.notify("Record saved", "The record #" + this.datarecord.id + " has been saved.");
335             if (success) {
336                 success(r);
337             }
338             this.reload();
339         }
340     },
341     /**
342      * Updates the form' dataset to contain the new record:
343      *
344      * * Adds the newly created record to the current dataset (at the end by
345      *   default)
346      * * Selects that record (sets the dataset's index to point to the new
347      *   record's id).
348      * * Updates the pager and sidebar displays
349      *
350      * @param {Object} r
351      * @param {Function} success callback to execute after having updated the dataset
352      * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
353      */
354     on_created: function(r, success, prepend_on_create) {
355         if (!r.result) {
356             this.notification.warn("Record not created", "Problem while creating record.");
357         } else {
358             this.datarecord.id = r.result;
359             if (!prepend_on_create) {
360                 this.dataset.ids.push(this.datarecord.id);
361                 this.dataset.index = this.dataset.ids.length - 1;
362             } else {
363                 this.dataset.ids.unshift(this.datarecord.id);
364                 this.dataset.index = 0;
365             }
366             this.do_update_pager();
367             this.do_update_sidebar();
368             this.notification.notify("Record created", "The record has been created with id #" + this.datarecord.id);
369             if (success) {
370                 success(_.extend(r, {created: true}));
371             }
372             this.reload();
373         }
374     },
375     do_search: function (domains, contexts, groupbys) {
376         this.notification.notify("Searching form");
377     },
378     on_action: function (action) {
379         this.notification.notify('Executing action ' + action);
380     },
381     do_cancel: function () {
382         this.notification.notify("Cancelling form");
383     },
384     do_update_sidebar: function() {
385         if (this.flags.sidebar === false) {
386             return;
387         }
388         if (!this.datarecord.id) {
389             this.on_attachments_loaded([]);
390         } else {
391             // TODO fme: modify this so it doesn't try to load attachments when there is not sidebar
392             /*this.rpc('/base/dataset/search_read', {
393                 model: 'ir.attachment',
394                 fields: ['name', 'url', 'type'],
395                 domain: [['res_model', '=', this.dataset.model], ['res_id', '=', this.datarecord.id], ['type', 'in', ['binary', 'url']]],
396                 context: this.dataset.context
397             }, this.on_attachments_loaded);*/
398         }
399     },
400     on_attachments_loaded: function(attachments) {
401         this.$sidebar = this.view_manager.sidebar.$element.find('.sidebar-attachments');
402         this.attachments = attachments;
403         this.$sidebar.html(QWeb.render('FormView.sidebar.attachments', this));
404         this.$sidebar.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
405         this.$sidebar.find('.oe-binary-file').change(this.on_attachment_changed);
406     },
407     on_attachment_changed: function(e) {
408         window[this.element_id + '_iframe'] = this.do_update_sidebar;
409         var $e = $(e.target);
410         if ($e.val() != '') {
411             this.$sidebar.find('form.oe-binary-form').submit();
412             $e.parent().find('input[type=file]').attr('disabled', 'true');
413             $e.parent().find('button').attr('disabled', 'true').find('img, span').toggle();
414         }
415     },
416     on_attachment_delete: function(e) {
417         var self = this, $e = $(e.currentTarget);
418         var name = _.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
419         if (confirm("Do you really want to delete the attachment " + name + " ?")) {
420             this.rpc('/base/dataset/unlink', {
421                 model: 'ir.attachment',
422                 ids: [parseInt($e.attr('data-id'))]
423             }, function(r) {
424                 $e.parent().remove();
425                 self.notification.notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
426             });
427         }
428     },
429     reload: function() {
430         if (this.datarecord.id) {
431             this.dataset.read_index(_.keys(this.fields_view.fields), this.on_record_loaded);
432         } else {
433             this.on_button_new();
434         }
435     },
436     get_fields_values: function() {
437         var values = {};
438         _.each(this.fields, function(value, key) {
439             values[key] = value.get_value();
440         });
441         return values;
442     }
443 });
444
445 /** @namespace */
446 openerp.base.form = {};
447
448 openerp.base.form.compute_domain = function(expr, fields) {
449     var stack = [];
450     for (var i = expr.length - 1; i >= 0; i--) {
451         var ex = expr[i];
452         if (ex.length == 1) {
453             var top = stack.pop();
454             switch (ex) {
455                 case '|':
456                     stack.push(stack.pop() || top);
457                     continue;
458                 case '&':
459                     stack.push(stack.pop() && top);
460                     continue;
461                 case '!':
462                     stack.push(!top);
463                     continue;
464                 default:
465                     throw new Error('Unknown domain operator ' + ex);
466             }
467         }
468
469         var field = fields[ex[0]].get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
470         var op = ex[1];
471         var val = ex[2];
472
473         switch (op.toLowerCase()) {
474             case '=':
475             case '==':
476                 stack.push(field == val);
477                 break;
478             case '!=':
479             case '<>':
480                 stack.push(field != val);
481                 break;
482             case '<':
483                 stack.push(field < val);
484                 break;
485             case '>':
486                 stack.push(field > val);
487                 break;
488             case '<=':
489                 stack.push(field <= val);
490                 break;
491             case '>=':
492                 stack.push(field >= val);
493                 break;
494             case 'in':
495                 stack.push(_(val).contains(field));
496                 break;
497             case 'not in':
498                 stack.push(!_(val).contains(field));
499                 break;
500             default:
501                 this.log("Unsupported operator in attrs :", op);
502         }
503     }
504     return _.all(stack);
505 };
506
507 openerp.base.form.Widget = openerp.base.Controller.extend({
508     template: 'Widget',
509     init: function(view, node) {
510         this.view = view;
511         this.node = node;
512         this.attrs = JSON.parse(this.node.attrs.attrs || '{}');
513         this.type = this.type || node.tag;
514         this.element_name = this.element_name || this.type;
515         this.element_id = [this.view.element_id, this.element_name, this.view.widgets_counter++].join("_");
516
517         this._super(this.view.session, this.element_id);
518
519         this.view.widgets[this.element_id] = this;
520         this.children = node.children;
521         this.colspan = parseInt(node.attrs.colspan || 1);
522
523         this.string = this.string || node.attrs.string;
524         this.help = this.help || node.attrs.help;
525         this.invisible = (node.attrs.invisible == '1');
526     },
527     start: function() {
528         this.$element = $('#' + this.element_id);
529     },
530     process_attrs: function() {
531         var compute_domain = openerp.base.form.compute_domain;
532         for (var a in this.attrs) {
533             this[a] = compute_domain(this.attrs[a], this.view.fields);
534         }
535     },
536     update_dom: function() {
537         this.$element.toggle(!this.invisible);
538     },
539     render: function() {
540         var template = this.template;
541         return QWeb.render(template, { "widget": this });
542     }
543 });
544
545 openerp.base.form.WidgetFrame = openerp.base.form.Widget.extend({
546     template: 'WidgetFrame',
547     init: function(view, node) {
548         this._super(view, node);
549         this.columns = node.attrs.col || 4;
550         this.x = 0;
551         this.y = 0;
552         this.table = [];
553         this.add_row();
554         for (var i = 0; i < node.children.length; i++) {
555             var n = node.children[i];
556             if (n.tag == "newline") {
557                 this.add_row();
558             } else {
559                 this.handle_node(n);
560             }
561         }
562         this.set_row_cells_with(this.table[this.table.length - 1]);
563     },
564     add_row: function(){
565         if (this.table.length) {
566             this.set_row_cells_with(this.table[this.table.length - 1]);
567         }
568         var row = [];
569         this.table.push(row);
570         this.x = 0;
571         this.y += 1;
572         return row;
573     },
574     set_row_cells_with: function(row) {
575         for (var i = 0; i < row.length; i++) {
576             var w = row[i];
577             if (w.is_field_label) {
578                 w.width = "1%";
579                 if (row[i + 1]) {
580                     row[i + 1].width = Math.round((100 / this.columns) * (w.colspan + 1) - 1) + '%';
581                 }
582             } else if (w.width === undefined) {
583                 w.width = Math.round((100 / this.columns) * w.colspan) + '%';
584             }
585         }
586     },
587     handle_node: function(node) {
588         var type = this.view.fields_view.fields[node.attrs.name] || {};
589         var widget = new (this.view.registry.get_any(
590                 [node.attrs.widget, type.type, node.tag])) (this.view, node);
591         if (node.tag == 'field') {
592             if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
593                 this.view.default_focus_field = widget;
594             }
595             if (node.attrs.nolabel != '1') {
596                 var label = new (this.view.registry.get_object('label')) (this.view, node);
597                 label["for"] = widget;
598                 this.add_widget(label);
599             }
600         }
601         this.add_widget(widget);
602     },
603     add_widget: function(widget) {
604         var current_row = this.table[this.table.length - 1];
605         if (current_row.length && (this.x + widget.colspan) > this.columns) {
606             current_row = this.add_row();
607         }
608         current_row.push(widget);
609         this.x += widget.colspan;
610         return widget;
611     }
612 });
613
614 openerp.base.form.WidgetNotebook = openerp.base.form.Widget.extend({
615     init: function(view, node) {
616         this._super(view, node);
617         this.template = "WidgetNotebook";
618         this.pages = [];
619         for (var i = 0; i < node.children.length; i++) {
620             var n = node.children[i];
621             if (n.tag == "page") {
622                 var page = new openerp.base.form.WidgetFrame(this.view, n);
623                 this.pages.push(page);
624             }
625         }
626     },
627     start: function() {
628         this._super.apply(this, arguments);
629         this.$element.tabs();
630     }
631 });
632
633 openerp.base.form.WidgetSeparator = openerp.base.form.Widget.extend({
634     init: function(view, node) {
635         this._super(view, node);
636         this.template = "WidgetSeparator";
637     }
638 });
639
640 openerp.base.form.WidgetButton = openerp.base.form.Widget.extend({
641     init: function(view, node) {
642         this._super(view, node);
643         this.template = "WidgetButton";
644         if (node.attrs.default_focus == '1') {
645             // TODO fme: provide enter key binding to widgets
646             this.view.default_focus_button = this;
647         }
648     },
649     start: function() {
650         this._super.apply(this, arguments);
651         this.$element.click(this.on_click);
652     },
653     on_click: function(saved) {
654         var self = this;
655         if (!this.node.attrs.special && this.view.touched && saved !== true) {
656             this.view.do_save(function() {
657                 self.on_click(true);
658             });
659         } else {
660             if (this.node.attrs.confirm) {
661                 var dialog = $('<div>' + this.node.attrs.confirm + '</div>').dialog({
662                     title: 'Confirm',
663                     modal: true,
664                     buttons: {
665                         Ok: function() {
666                             self.on_confirmed();
667                             $(this).dialog("close");
668                         },
669                         Cancel: function() {
670                             $(this).dialog("close");
671                         }
672                     }
673                 });
674             } else {
675                 this.on_confirmed();
676             }
677         }
678     },
679     on_confirmed: function() {
680         var self = this;
681
682         this.view.execute_action(
683             this.node.attrs, this.view.dataset, this.session.action_manager,
684             this.view.datarecord.id, function (result) {
685                 self.log("Button returned", result);
686                 self.view.reload();
687             }, function() {
688                 self.view.reload();
689             });
690     }
691 });
692
693 openerp.base.form.WidgetLabel = openerp.base.form.Widget.extend({
694     init: function(view, node) {
695         this.element_name = 'label_' + node.attrs.name;
696
697         this._super(view, node);
698
699         // TODO fme: support for attrs.align
700         if (this.node.tag == 'label' && this.node.attrs.colspan) {
701             this.is_field_label = false;
702             this.template = "WidgetParagraph";
703         } else {
704             this.is_field_label = true;
705             this.template = "WidgetLabel";
706         }
707         this.colspan = 1;
708     },
709     render: function () {
710         if (this['for'] && this.type !== 'label') {
711             return QWeb.render(this.template, {widget: this['for']});
712         }
713         // Actual label widgets should not have a false and have type label
714         return QWeb.render(this.template, {widget: this});
715     }
716 });
717
718 openerp.base.form.Field = openerp.base.form.Widget.extend({
719     init: function(view, node) {
720         this.name = node.attrs.name;
721         this.value = undefined;
722         view.fields[this.name] = this;
723         this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
724         this.element_name = "field_" + this.name + "_" + this.type;
725
726         this._super(view, node);
727
728         if (node.attrs.nolabel != '1' && this.colspan > 1) {
729             this.colspan--;
730         }
731         this.field = view.fields_view.fields[node.attrs.name] || {};
732         this.string = node.attrs.string || this.field.string;
733         this.help = node.attrs.help || this.field.help;
734         this.invisible = (this.invisible || this.field.invisible == '1');
735         this.nolabel = (this.field.nolabel || node.attrs.nolabel) == '1';
736         this.readonly = (this.field.readonly || node.attrs.readonly) == '1';
737         this.required = (this.field.required || node.attrs.required) == '1';
738         this.invalid = false;
739         this.touched = false;
740     },
741     set_value: function(value) {
742         this.value = value;
743         this.invalid = false;
744         this.update_dom();
745     },
746     set_value_from_ui: function() {
747         this.value = undefined;
748     },
749     get_value: function() {
750         return this.value;
751     },
752     get_on_change_value: function() {
753         return this.get_value();
754     },
755     update_dom: function() {
756         this._super.apply(this, arguments);
757         this.$element.toggleClass('disabled', this.readonly);
758         this.$element.toggleClass('required', this.required);
759         if (this.view.show_invalid) {
760             this.$element.toggleClass('invalid', this.invalid);
761         }
762     },
763     on_ui_change: function() {
764         this.touched = this.view.touched = true;
765         this.validate();
766         if (!this.invalid) {
767             this.set_value_from_ui();
768             this.view.do_onchange(this);
769             this.view.on_form_changed();
770         } else {
771             this.update_dom();
772         }
773     },
774     validate: function() {
775         this.invalid = false;
776     },
777     focus: function() {
778     }
779 });
780
781 openerp.base.form.FieldChar = openerp.base.form.Field.extend({
782     init: function(view, node) {
783         this._super(view, node);
784         this.template = "FieldChar";
785     },
786     start: function() {
787         this._super.apply(this, arguments);
788         this.$element.find('input').change(this.on_ui_change);
789     },
790     set_value: function(value) {
791         this._super.apply(this, arguments);
792         var show_value = (value != null && value !== false) ? value : '';
793         this.$element.find('input').val(show_value);
794     },
795     update_dom: function() {
796         this._super.apply(this, arguments);
797         this.$element.find('input').attr('disabled', this.readonly);
798     },
799     set_value_from_ui: function() {
800         this.value = this.$element.find('input').val();
801     },
802     validate: function() {
803         this.invalid = false;
804         var value = this.$element.find('input').val();
805         if (value === "") {
806             this.invalid = this.required;
807         } else if (this.validation_regex) {
808             this.invalid = !this.validation_regex.test(value);
809         }
810     },
811     focus: function() {
812         this.$element.find('input').focus();
813     }
814 });
815
816 openerp.base.form.FieldEmail = openerp.base.form.FieldChar.extend({
817     init: function(view, node) {
818         this._super(view, node);
819         this.template = "FieldEmail";
820         this.validation_regex = /@/;
821     },
822     start: function() {
823         this._super.apply(this, arguments);
824         this.$element.find('button').click(this.on_button_clicked);
825     },
826     on_button_clicked: function() {
827         if (!this.value || this.invalid) {
828             this.notification.warn("E-mail error", "Can't send email to invalid e-mail address");
829         } else {
830             location.href = 'mailto:' + this.value;
831         }
832     },
833     set_value: function(value) {
834         this._super.apply(this, arguments);
835         var show_value = (value != null && value !== false) ? value : '';
836         this.$element.find('a').attr('href', 'mailto:' + show_value);
837     }
838 });
839
840 openerp.base.form.FieldUrl = openerp.base.form.FieldChar.extend({
841     init: function(view, node) {
842         this._super(view, node);
843         this.template = "FieldUrl";
844     },
845     start: function() {
846         this._super.apply(this, arguments);
847         this.$element.find('button').click(this.on_button_clicked);
848     },
849     on_button_clicked: function() {
850         if (!this.value) {
851             this.notification.warn("Resource error", "This resource is empty");
852         } else {
853             window.open(this.value);
854         }
855     }
856 });
857
858 openerp.base.form.FieldFloat = openerp.base.form.FieldChar.extend({
859     init: function(view, node) {
860         this._super(view, node);
861         this.validation_regex = /^-?\d+(\.\d+)?$/;
862     },
863     set_value: function(value) {
864         this._super.apply(this, [value]);
865         if (value === false || value === undefined) {
866             // As in GTK client, floats default to 0
867             value = 0;
868         }
869         var show_value = value.toFixed(2);
870         this.$element.find('input').val(show_value);
871     },
872     set_value_from_ui: function() {
873         this.value = Number(this.$element.find('input').val().replace(/,/g, '.'));
874     }
875 });
876
877 openerp.base.form.FieldDatetime = openerp.base.form.Field.extend({
878     init: function(view, node) {
879         this._super(view, node);
880         this.template = "FieldDate";
881         this.jqueryui_object = 'datetimepicker';
882         this.validation_regex = /^\d+-\d+-\d+( \d+:\d+(:\d+)?)?$/;
883     },
884     start: function() {
885         this._super.apply(this, arguments);
886         this.$element.find('input').change(this.on_ui_change)[this.jqueryui_object]({
887             dateFormat: 'yy-mm-dd',
888             timeFormat: 'hh:mm:ss',
889             showOn: 'button',
890             buttonImage: '/base/static/src/img/ui/field_calendar.png',
891             buttonImageOnly: true,
892             constrainInput: false
893         });
894     },
895     set_value: function(value) {
896         this._super.apply(this, arguments);
897         if (value == null || value == false) {
898             this.$element.find('input').val('');
899         } else {
900             this.$element.find('input').unbind('change');
901             // jQuery UI date picker wrongly call on_change event herebelow
902             this.$element.find('input')[this.jqueryui_object]('setDate', this.parse(value));
903             this.$element.find('input').change(this.on_ui_change);
904         }
905     },
906     set_value_from_ui: function() {
907         this.value = this.$element.find('input')[this.jqueryui_object]('getDate') || false;
908         if (this.value) {
909             this.value = this.format(this.value);
910         }
911     },
912     update_dom: function() {
913         this._super.apply(this, arguments);
914         this.$element.find('input').attr('disabled', this.readonly);
915     },
916     validate: function() {
917         this.invalid = false;
918         var value = this.$element.find('input').val();
919         if (value === "") {
920             this.invalid = this.required;
921         } else if (this.validation_regex) {
922             this.invalid = !this.validation_regex.test(value);
923         } else {
924             this.invalid = !this.$element.find('input')[this.jqueryui_object]('getDate');
925         }
926     },
927     focus: function() {
928         this.$element.find('input').focus();
929     },
930     parse: openerp.base.parse_datetime,
931     format: openerp.base.format_datetime
932 });
933
934 openerp.base.form.FieldDate = openerp.base.form.FieldDatetime.extend({
935     init: function(view, node) {
936         this._super(view, node);
937         this.jqueryui_object = 'datepicker';
938         this.validation_regex = /^\d+-\d+-\d+$/;
939     },
940     parse: openerp.base.parse_date,
941     format: openerp.base.format_date
942 });
943
944 openerp.base.form.FieldFloatTime = openerp.base.form.FieldChar.extend({
945     init: function(view, node) {
946         this._super(view, node);
947         this.validation_regex = /^\d+:\d+$/;
948     },
949     set_value: function(value) {
950         this._super.apply(this, [value]);
951         if (value === false || value === undefined) {
952             // As in GTK client, floats default to 0
953             value = 0;
954         }
955         var show_value = _.sprintf("%02d:%02d", Math.floor(value), Math.round((value % 1) * 60));
956         this.$element.find('input').val(show_value);
957     },
958     set_value_from_ui: function() {
959         var time = this.$element.find('input').val().split(':');
960         this.set_value(parseInt(time[0], 10) + parseInt(time[1], 10) / 60);
961     }
962 });
963
964 openerp.base.form.FieldText = openerp.base.form.Field.extend({
965     init: function(view, node) {
966         this._super(view, node);
967         this.template = "FieldText";
968         this.validation_regex = null;
969     },
970     start: function() {
971         this._super.apply(this, arguments);
972         this.$element.find('textarea').change(this.on_ui_change);
973     },
974     set_value: function(value) {
975         this._super.apply(this, arguments);
976         var show_value = (value != null && value !== false) ? value : '';
977         this.$element.find('textarea').val(show_value);
978     },
979     update_dom: function() {
980         this._super.apply(this, arguments);
981         this.$element.find('textarea').attr('disabled', this.readonly);
982     },
983     set_value_from_ui: function() {
984         this.value = this.$element.find('textarea').val();
985     },
986     validate: function() {
987         this.invalid = false;
988         var value = this.$element.find('textarea').val();
989         if (value === "") {
990             this.invalid = this.required;
991         } else if (this.validation_regex) {
992             this.invalid = !this.validation_regex.test(value);
993         }
994     },
995     focus: function() {
996         this.$element.find('textarea').focus();
997     }
998 });
999
1000 openerp.base.form.FieldBoolean = openerp.base.form.Field.extend({
1001     init: function(view, node) {
1002         this._super(view, node);
1003         this.template = "FieldBoolean";
1004     },
1005     start: function() {
1006         var self = this;
1007         this._super.apply(this, arguments);
1008         this.$element.find('input').click(function() {
1009             if ($(this).is(':checked') != self.value) {
1010                 self.on_ui_change();
1011             }
1012         });
1013     },
1014     set_value: function(value) {
1015         this._super.apply(this, arguments);
1016         this.$element.find('input')[0].checked = value;
1017     },
1018     set_value_from_ui: function() {
1019         this.value = this.$element.find('input').is(':checked');
1020     },
1021     update_dom: function() {
1022         this._super.apply(this, arguments);
1023         this.$element.find('input').attr('disabled', this.readonly);
1024     },
1025     validate: function() {
1026         this.invalid = this.required && !this.$element.find('input').is(':checked');
1027     },
1028     focus: function() {
1029         this.$element.find('input').focus();
1030     }
1031 });
1032
1033 openerp.base.form.FieldProgressBar = openerp.base.form.Field.extend({
1034     init: function(view, node) {
1035         this._super(view, node);
1036         this.template = "FieldProgressBar";
1037     },
1038     start: function() {
1039         this._super.apply(this, arguments);
1040         this.$element.find('div').progressbar({
1041             value: this.value,
1042             disabled: this.readonly
1043         });
1044     },
1045     set_value: function(value) {
1046         this._super.apply(this, arguments);
1047         var show_value = Number(value);
1048         if (show_value === NaN) {
1049             show_value = 0;
1050         }
1051         this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(show_value + '%');
1052     }
1053 });
1054
1055 openerp.base.form.FieldTextXml = openerp.base.form.Field.extend({
1056 // to replace view editor
1057 });
1058
1059 openerp.base.form.FieldSelection = openerp.base.form.Field.extend({
1060     init: function(view, node) {
1061         this._super(view, node);
1062         this.template = "FieldSelection";
1063     },
1064     start: function() {
1065         this._super.apply(this, arguments);
1066         this.$element.find('select').change(this.on_ui_change);
1067     },
1068     set_value: function(value) {
1069         this._super.apply(this, arguments);
1070         if (value != null && value !== false) {
1071             this.$element.find('select').val(value);
1072         } else {
1073             this.$element.find('select').val('false');
1074         }
1075     },
1076     set_value_from_ui: function() {
1077         this.value = this.$element.find('select').val();
1078     },
1079     update_dom: function() {
1080         this._super.apply(this, arguments);
1081         this.$element.find('select').attr('disabled', this.readonly);
1082     },
1083     validate: function() {
1084         this.invalid = this.required && this.$element.find('select').val() === "";
1085     },
1086     focus: function() {
1087         this.$element.find('select').focus();
1088     }
1089 });
1090
1091 // jquery autocomplete tweak to allow html
1092 (function() {
1093     var proto = $.ui.autocomplete.prototype,
1094         initSource = proto._initSource;
1095
1096     function filter( array, term ) {
1097         var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1098         return $.grep( array, function(value) {
1099             return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1100         });
1101     }
1102
1103     $.extend( proto, {
1104         _initSource: function() {
1105             if ( this.options.html && $.isArray(this.options.source) ) {
1106                 this.source = function( request, response ) {
1107                     response( filter( this.options.source, request.term ) );
1108                 };
1109             } else {
1110                 initSource.call( this );
1111             }
1112         },
1113
1114         _renderItem: function( ul, item) {
1115             return $( "<li></li>" )
1116                 .data( "item.autocomplete", item )
1117                 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1118                 .appendTo( ul );
1119         }
1120     });
1121 })();
1122
1123 var build_view_fields_values = function(view) {
1124     var a_dataset = view.dataset || {};
1125     var fields_values = view.get_fields_values();
1126     var parent_values = a_dataset.parent_view ? a_dataset.parent_view.get_fields_values() : {};
1127     fields_values.parent = parent_values;
1128     return fields_values;
1129 }
1130 /**
1131  * Builds a new context usable for operations related to fields by merging
1132  * the fields'context with the action's context.
1133  */
1134 var build_relation_context = function(relation_field) {
1135     var a_context = relation_field.view.dataset.get_context() || {};
1136     var fields_values = build_view_fields_values(relation_field.view);
1137     var f_context = relation_field.field.context || {};
1138     var v_context = new openerp.base.CompoundContext(relation_field.node.attrs.default_get || {},
1139         relation_field.node.attrs.context || {}).set_eval_context(fields_values);
1140     var ctx = new openerp.base.CompoundContext(a_context, f_context, v_context);
1141     return ctx;
1142 }
1143 var build_relation_domain = function(relation_field) {
1144     var fields_values = build_view_fields_values(relation_field.view);
1145     var f_domain = relation_field.field.domain || [];
1146     var v_domain = new openerp.base.CompoundDomain(relation_field.node.attrs.domain || []).set_eval_context(fields_values);
1147     return new openerp.base.CompoundDomain(f_domain, v_domain);
1148 }
1149
1150 openerp.base.form.FieldMany2One = openerp.base.form.Field.extend({
1151     init: function(view, node) {
1152         this._super(view, node);
1153         this.template = "FieldMany2One";
1154         this.limit = 7;
1155         this.value = null;
1156         this.cm_id = _.uniqueId('m2o_cm_');
1157         this.last_search = [];
1158         this.tmp_value = undefined;
1159     },
1160     start: function() {
1161         this._super();
1162         var self = this;
1163         this.$input = this.$element.find("input");
1164         this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1165         this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1166
1167         // context menu
1168         var bindings = {};
1169         bindings[this.cm_id + "_search"] = function() {
1170             self._search_create_popup("search");
1171         };
1172         bindings[this.cm_id + "_create"] = function() {
1173             self._search_create_popup("form");
1174         };
1175         bindings[this.cm_id + "_open"] = function() {
1176             if (!self.value) {
1177                 return;
1178             }
1179             self.session.action_manager.do_action({
1180                 "res_model": self.field.relation,
1181                 "views":[[false,"form"]],
1182                 "res_id": self.value[0],
1183                 "type":"ir.actions.act_window",
1184                 "target":"new",
1185                 "context": build_relation_context(self)
1186             });
1187         };
1188         var cmenu = this.$menu_btn.contextMenu(this.cm_id, {'leftClickToo': true,
1189             bindings: bindings, itemStyle: {"color": ""},
1190             onContextMenu: function() {
1191                 if(self.value) {
1192                     $("#" + self.cm_id + "_open").removeClass("oe-m2o-disabled-cm");
1193                 } else {
1194                     $("#" + self.cm_id + "_open").addClass("oe-m2o-disabled-cm");
1195                 }
1196                 return true;
1197             }
1198         });
1199
1200         // some behavior for input
1201         this.$input.keyup(function() {
1202             if (self.$input.val() === "") {
1203                 self._change_int_value(null);
1204             } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1205                 self._change_int_value(undefined);
1206             }
1207         });
1208         this.$drop_down.click(function() {
1209             if (self.$input.autocomplete("widget").is(":visible")) {
1210                 self.$input.autocomplete("close");
1211             } else {
1212                 if (self.value) {
1213                     self.$input.autocomplete("search", "");
1214                 } else {
1215                     self.$input.autocomplete("search");
1216                 }
1217                 self.$input.focus();
1218             }
1219         });
1220         var anyoneLoosesFocus = function() {
1221             if (!self.$input.is(":focus") &&
1222                     !self.$input.autocomplete("widget").is(":visible") &&
1223                     !self.value) {
1224                 if(self.value === undefined && self.last_search.length > 0) {
1225                     self._change_int_ext_value(self.last_search[0]);
1226                 } else {
1227                     self._change_int_ext_value(null);
1228                 }
1229             }
1230         }
1231         this.$input.focusout(anyoneLoosesFocus);
1232
1233         // autocomplete
1234         this.$input.autocomplete({
1235             source: function(req, resp) { self.get_search_result(req, resp); },
1236             select: function(event, ui) {
1237                 var item = ui.item;
1238                 if (item.id) {
1239                     self._change_int_value([item.id, item.name]);
1240                 } else if (item.action) {
1241                     self._change_int_value(undefined);
1242                     item.action();
1243                     return false;
1244                 }
1245             },
1246             focus: function(e, ui) {
1247                 e.preventDefault();
1248             },
1249             html: true,
1250             close: anyoneLoosesFocus,
1251             minLength: 0,
1252             delay: 0
1253         });
1254     },
1255     // autocomplete component content handling
1256     get_search_result: function(request, response) {
1257         var search_val = request.term;
1258         var self = this;
1259
1260         var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, build_relation_context(self));
1261
1262         dataset.name_search(search_val, build_relation_domain(self), 'ilike',
1263                 this.limit + 1, function(data) {
1264             self.last_search = data.result;
1265             // possible selections for the m2o
1266             var values = _.map(data.result, function(x) {
1267                 return {label: $('<span />').text(x[1]).html(), name:x[1], id:x[0]};
1268             });
1269
1270             // search more... if more results that max
1271             if (values.length > self.limit) {
1272                 values = values.slice(0, self.limit);
1273                 values.push({label: "<em>   Search More...</em>", action: function() {
1274                     dataset.name_search(search_val, build_relation_domain(self), 'ilike'
1275                     , false, function(data) {
1276                         self._change_int_value(null);
1277                         self._search_create_popup("search", data.result);
1278                     });
1279                 }});
1280             }
1281             // quick create
1282             var raw_result = _(data.result).map(function(x) {return x[1];})
1283             if (search_val.length > 0 &&
1284                 !_.include(raw_result, search_val) &&
1285                 (!self.value || search_val !== self.value[1])) {
1286                 values.push({label: '<em>   Create "<strong>' +
1287                         $('<span />').text(search_val).html() + '</strong>"</em>', action: function() {
1288                     self._quick_create(search_val);
1289                 }});
1290             }
1291             // create...
1292             values.push({label: "<em>   Create and Edit...</em>", action: function() {
1293                 self._change_int_value(null);
1294                 self._search_create_popup("form");
1295             }});
1296
1297             response(values);
1298         });
1299     },
1300     _quick_create: function(name) {
1301         var self = this;
1302         var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, build_relation_context(self));
1303         dataset.name_create(name, function(data) {
1304             self._change_int_ext_value(data.result);
1305         }).fail(function(error, event) {
1306             event.preventDefault();
1307             self._change_int_value(null);
1308             self._search_create_popup("form", undefined, {"default_name": name});
1309         });
1310     },
1311     // all search/create popup handling
1312     _search_create_popup: function(view, ids, context) {
1313         var self = this;
1314         var pop = new openerp.base.form.SelectCreatePopup(null, self.view.session);
1315         pop.select_element(self.field.relation,{
1316                 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
1317                 initial_view: view,
1318                 disable_multiple_selection: true
1319                 }, build_relation_domain(self),
1320                 new openerp.base.CompoundContext(build_relation_context(self), context || {}));
1321         pop.on_select_elements.add(function(element_ids) {
1322             var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, build_relation_context(self));
1323             dataset.name_get([element_ids[0]], function(data) {
1324                 self._change_int_ext_value(data.result[0]);
1325                 pop.stop();
1326             });
1327         });
1328     },
1329     _change_int_ext_value: function(value) {
1330         this._change_int_value(value);
1331         this.$input.val(this.value ? this.value[1] : "");
1332     },
1333     _change_int_value: function(value) {
1334         this.value = value;
1335         var back_orig_value = this.original_value;
1336         if (this.value === null || this.value) {
1337             this.original_value = this.value;
1338         }
1339         if (back_orig_value === undefined) { // first use after a set_value()
1340             return;
1341         }
1342         if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
1343                 !== (this.value ? this.value[0] : null))) {
1344             this.on_ui_change();
1345         }
1346     },
1347     set_value_from_ui: function() {},
1348     set_value: function(value) {
1349         value = value || null;
1350         var self = this;
1351         var _super = this._super;
1352         this.tmp_value = value;
1353         var real_set_value = function(rval) {
1354             self.tmp_value = undefined;
1355             _super.apply(self, rval);
1356             self.original_value = undefined;
1357             self._change_int_ext_value(rval);
1358         };
1359         if(typeof(value) === "number") {
1360             var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, build_relation_context(self));
1361             dataset.name_get([value], function(data) {
1362                 real_set_value(data.result[0]);
1363             }).fail(function() {self.tmp_value = undefined;});
1364         } else {
1365             setTimeout(function() {real_set_value(value);}, 0);
1366         }
1367     },
1368     get_value: function() {
1369         if (this.tmp_value !== undefined) {
1370             if (this.tmp_value instanceof Array) {
1371                 return this.tmp_value[0];
1372             }
1373             return this.tmp_value ? this.tmp_value : false;
1374         }
1375         if (this.value === undefined)
1376             return this.original_value ? this.original_value[0] : false;
1377         return this.value ? this.value[0] : false;
1378     },
1379     validate: function() {
1380         this.invalid = false;
1381         if (this.value === null) {
1382             this.invalid = this.required;
1383         }
1384     }
1385 });
1386
1387 /*
1388 # Values: (0, 0,  { fields })    create
1389 #         (1, ID, { fields })    update
1390 #         (2, ID)                remove (delete)
1391 #         (3, ID)                unlink one (target id or target of relation)
1392 #         (4, ID)                link
1393 #         (5)                    unlink all (only valid for one2many)
1394 */
1395 var commands = {
1396     // (0, _, {values})
1397     CREATE: 0,
1398     'create': function (values) {
1399         return [commands.CREATE, false, values];
1400     },
1401     // (1, id, {values})
1402     UPDATE: 1,
1403     'update': function (id, values) {
1404         return [commands.UPDATE, id, values];
1405     },
1406     // (2, id[, _])
1407     DELETE: 2,
1408     'delete': function (id) {
1409         return [commands.DELETE, id, false];
1410     },
1411     // (3, id[, _]) removes relation, but not linked record itself
1412     FORGET: 3,
1413     'forget': function (id) {
1414         return [commands.FORGET, id, false];
1415     },
1416     // (4, id[, _])
1417     LINK_TO: 4,
1418     'link_to': function (id) {
1419         return [commands.LINK_TO, id, false];
1420     },
1421     // (5[, _[, _]])
1422     DELETE_ALL: 5,
1423     'delete_all': function () {
1424         return [5, false, false];
1425     },
1426     // (6, _, ids) replaces all linked records with provided ids
1427     REPLACE_WITH: 6,
1428     'replace_with': function (ids) {
1429         return [6, false, ids];
1430     }
1431 };
1432 openerp.base.form.FieldOne2Many = openerp.base.form.Field.extend({
1433     init: function(view, node) {
1434         this._super(view, node);
1435         this.template = "FieldOne2Many";
1436         this.is_started = $.Deferred();
1437     },
1438     start: function() {
1439         this._super.apply(this, arguments);
1440
1441         var self = this;
1442
1443         this.dataset = new openerp.base.form.One2ManyDataSet(this.session, this.field.relation);
1444         this.dataset.o2m = this;
1445         this.dataset.parent_view = this.view;
1446         this.dataset.on_change.add_last(function() {
1447             self.on_ui_change();
1448         });
1449
1450         var modes = this.node.attrs.mode;
1451         modes = !!modes ? modes.split(",") : ["tree", "form"];
1452         var views = [];
1453         _.each(modes, function(mode) {
1454             var view = {view_id: false, view_type: mode == "tree" ? "list" : mode};
1455             if (self.field.views && self.field.views[mode]) {
1456                 view.embedded_view = self.field.views[mode];
1457             }
1458             if(view.view_type === "list") {
1459                 view.options = {
1460                 };
1461             }
1462             views.push(view);
1463         });
1464         this.views = views;
1465
1466         this.viewmanager = new openerp.base.ViewManager(this.view.session,
1467             this.element_id, this.dataset, views);
1468         this.viewmanager.registry = openerp.base.views.clone({
1469             list: 'openerp.base.form.One2ManyListView'
1470         });
1471
1472         this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
1473             if (view_type == "list") {
1474                 controller.o2m = self;
1475             } else if (view_type == "form") {
1476                 // TODO niv
1477             }
1478             self.is_started.resolve();
1479         });
1480         this.viewmanager.start();
1481     },
1482     reload_current_view: function() {
1483         var self = this;
1484         var view = self.viewmanager.views[self.viewmanager.active_view].controller;
1485         if(self.viewmanager.active_view === "list") {
1486             view.reload_content();
1487         } else if (self.viewmanager.active_view === "form") {
1488             // TODO niv: implement
1489         }
1490     },
1491     set_value_from_ui: function() {},
1492     set_value: function(value) {
1493         value = value || [];
1494         var self = this;
1495         this.dataset.reset_ids([]);
1496         if(value.length >= 1 && value[0] instanceof Array) {
1497             var ids = [];
1498             _.each(value, function(command) {
1499                 var obj = {values: command[2]};
1500                 switch (command[0]) {
1501                     case commands.CREATE:
1502                         obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
1503                         self.dataset.to_create.push(obj);
1504                         self.dataset.cache.push(_.clone(obj));
1505                         ids.push(obj.id);
1506                         return;
1507                     case commands.UPDATE:
1508                         obj['id'] = command[1];
1509                         self.dataset.to_write.push(obj);
1510                         self.dataset.cache.push(_.clone(obj));
1511                         ids.push(obj.id);
1512                         return;
1513                     case commands.DELETE:
1514                         self.dataset.to_delete.push({id: command[1]});
1515                         return;
1516                     case commands.LINK_TO:
1517                         ids.push(command[1]);
1518                         return;
1519                     case commands.DELETE_ALL:
1520                         self.dataset.delete_all = true;
1521                         return;
1522                 }
1523             });
1524             this._super(ids);
1525             this.dataset.set_ids(ids);
1526         } else if (value.length >= 1 && typeof(value[0]) === "object") {
1527             var ids = [];
1528             this.dataset.delete_all = true;
1529             _.each(value, function(command) {
1530                 var obj = {values: command};
1531                 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
1532                 self.dataset.to_create.push(obj);
1533                 self.dataset.cache.push(_.clone(obj));
1534                 ids.push(obj.id);
1535             });
1536             this._super(ids);
1537             this.dataset.set_ids(ids);
1538         } else {
1539             this._super(value);
1540             this.dataset.reset_ids(value);
1541         }
1542         $.when(this.is_started).then(function() {
1543             self.reload_current_view();
1544         });
1545     },
1546     get_value: function() {
1547         var self = this;
1548         if (!this.dataset)
1549             return [];
1550         var val = this.dataset.delete_all ? [commands.delete_all()] : [];
1551         val = val.concat(_.map(this.dataset.ids, function(id) {
1552             var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
1553             if (alter_order) {
1554                 return commands.create(alter_order.values);
1555             }
1556             alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
1557             if (alter_order) {
1558                 return commands.update(alter_order.id, alter_order.values);
1559             }
1560             return commands.link_to(id);
1561         }));
1562         return val.concat(_.map(
1563             this.dataset.to_delete, function(x) {
1564                 return commands['delete'](x.id);}));
1565     },
1566     validate: function() {
1567         this.invalid = false;
1568         // TODO niv
1569     }
1570 });
1571
1572 openerp.base.form.One2ManyDataSet = openerp.base.BufferedDataSet.extend({
1573     get_context: function() {
1574         this.context = build_relation_context(this.o2m);
1575         return this.context;
1576     }
1577 });
1578
1579 openerp.base.form.One2ManyListView = openerp.base.ListView.extend({
1580     do_add_record: function () {
1581         var self = this;
1582         var pop = new openerp.base.form.SelectCreatePopup(null, self.o2m.view.session);
1583         pop.select_element(self.o2m.field.relation,{
1584             initial_view: "form",
1585             alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
1586             auto_create: false,
1587             parent_view: self.o2m.view
1588         }, build_relation_domain(self.o2m), build_relation_context(self.o2m));
1589         pop.on_create.add(function(data) {
1590             self.o2m.dataset.create(data, function(r) {
1591                 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
1592                 self.o2m.dataset.on_change();
1593                 pop.stop();
1594                 self.o2m.reload_current_view();
1595             });
1596         });
1597     }
1598 });
1599
1600 openerp.base.form.FieldMany2Many = openerp.base.form.Field.extend({
1601     init: function(view, node) {
1602         this._super(view, node);
1603         this.template = "FieldMany2Many";
1604         this.list_id = _.uniqueId("many2many");
1605         this.is_started = $.Deferred();
1606     },
1607     start: function() {
1608         this._super.apply(this, arguments);
1609
1610         var self = this;
1611
1612         this.dataset = new openerp.base.DataSetStatic(
1613                 this.session, this.field.relation);
1614         this.dataset.on_unlink.add_last(function(ids) {
1615             //TODO niv: should check this for other cases
1616             self.on_ui_change();
1617         });
1618
1619         this.list_view = new openerp.base.form.Many2ManyListView(
1620                 null, this.view.session, this.list_id, this.dataset, false, {
1621                     'addable': 'Add'
1622             });
1623         this.list_view.m2m_field = this;
1624         this.list_view.on_loaded.add_last(function() {
1625             self.is_started.resolve();
1626         });
1627         this.list_view.start();
1628     },
1629     set_value: function(value) {
1630         value = value || [];
1631         if (value.length >= 1 && value[0] instanceof Array) {
1632             value = value[0][2];
1633         }
1634         this._super(value);
1635         this.dataset.set_ids(value);
1636         var self = this;
1637         $.when(this.is_started).then(function() {
1638             self.list_view.reload_content();
1639         });
1640     },
1641     get_value: function() {
1642         return [commands.replace_with(this.dataset.ids)];
1643     }
1644 });
1645
1646 openerp.base.form.Many2ManyListView = openerp.base.ListView.extend({
1647     do_add_record: function () {
1648         var pop = new openerp.base.form.SelectCreatePopup(
1649                 null, this.m2m_field.view.session);
1650         pop.select_element(this.model);
1651         var self = this;
1652         pop.on_select_elements.add(function(element_ids) {
1653             _.each(element_ids, function(element_id) {
1654                 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
1655                     self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
1656                     self.reload_content();
1657                 }
1658             });
1659             pop.stop();
1660         });
1661     },
1662     do_activate_record: function(index, id) {
1663         this.m2m_field.view.session.action_manager.do_action({
1664             "res_model": this.dataset.model,
1665             "views":[[false,"form"]],
1666             "res_id": id,
1667             "type":"ir.actions.act_window",
1668             "view_type":"form",
1669             "view_mode":"form",
1670             "target":"new"
1671         });
1672     }
1673 });
1674
1675 openerp.base.form.SelectCreatePopup = openerp.base.BaseWidget.extend({
1676     identifier_prefix: "selectcreatepopup",
1677     template: "SelectCreatePopup",
1678     /**
1679      * options:
1680      * - initial_ids
1681      * - initial_view: form or search (default search)
1682      * - disable_multiple_selection
1683      * - alternative_form_view
1684      * - auto_create (default true)
1685      * - parent_view
1686      */
1687     select_element: function(model, options, domain, context) {
1688         this.model = model;
1689         this.domain = domain || [];
1690         this.context = context || {};
1691         this.options = _.defaults(options || {}, {"initial_view": "search", "auto_create": true});
1692         this.initial_ids = this.options.initial_ids;
1693         jQuery(this.render()).dialog({title: '',
1694                     modal: true,
1695                     minWidth: 800});
1696         this.start();
1697     },
1698     start: function() {
1699         this._super();
1700         this.dataset = new openerp.base.ReadOnlyDataSetSearch(this.session, this.model,
1701             this.context, this.domain);
1702         this.dataset.parent_view = this.options.parent_view;
1703         if (this.options.initial_view == "search") {
1704             this.setup_search_view();
1705         } else { // "form"
1706             this.new_object();
1707         }
1708     },
1709     setup_search_view: function() {
1710         var self = this;
1711         if (this.searchview) {
1712             this.searchview.stop();
1713         }
1714         this.searchview = new openerp.base.SearchView(null, this.session,
1715                 this.element_id + "_search", this.dataset, false, {
1716                     "selectable": !this.options.disable_multiple_selection,
1717                     "deletable": false
1718                 });
1719         this.searchview.on_search.add(function(domains, contexts, groupbys) {
1720             if (self.initial_ids) {
1721                 self.view_list.do_search.call(self, domains.concat([[["id", "in", self.initial_ids]]]),
1722                     contexts, groupbys);
1723                 self.initial_ids = undefined;
1724             } else {
1725                 self.view_list.do_search.call(self, domains, contexts, groupbys);
1726             }
1727         });
1728         this.searchview.on_loaded.add_last(function () {
1729             var $buttons = self.searchview.$element.find(".oe_search-view-buttons");
1730             $buttons.append(QWeb.render("SelectCreatePopup.search.buttons"));
1731             var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
1732             $cbutton.click(function() {
1733                 self.stop();
1734             });
1735             var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
1736             if(self.options.disable_multiple_selection) {
1737                 $sbutton.hide();
1738             }
1739             $sbutton.click(function() {
1740                 self.on_select_elements(self.selected_ids);
1741             });
1742             self.view_list = new openerp.base.form.SelectCreateListView( null, self.session,
1743                     self.element_id + "_view_list", self.dataset, false,
1744                     {'deletable': false});
1745             self.view_list.popup = self;
1746             self.view_list.do_show();
1747             self.view_list.start().then(function() {
1748                 self.searchview.do_search();
1749             });
1750         });
1751         this.searchview.start();
1752     },
1753     on_create: function(data) {
1754         if (!this.options.auto_create)
1755             return;
1756         var self = this;
1757         var wdataset = new openerp.base.DataSetSearch(this.session, this.model, this.context, this.domain);
1758         wdataset = this.options.parent_view;
1759         wdataset.create(data, function(r) {
1760             self.on_select_elements([r.result]);
1761         });
1762     },
1763     on_select_elements: function(element_ids) {
1764     },
1765     on_click_element: function(ids) {
1766         this.selected_ids = ids || [];
1767         if(this.selected_ids.length > 0) {
1768             this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
1769         } else {
1770             this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
1771         }
1772     },
1773     new_object: function() {
1774         var self = this;
1775         if (this.searchview) {
1776             this.searchview.hide();
1777         }
1778         if (this.view_list) {
1779             this.view_list.$element.hide();
1780         }
1781         this.dataset.index = null;
1782         this.view_form = new openerp.base.FormView(null, this.session,
1783                 this.element_id + "_view_form", this.dataset, false);
1784         if (this.options.alternative_form_view) {
1785             this.view_form.set_embedded_view(this.options.alternative_form_view);
1786         }
1787         this.view_form.start();
1788         this.view_form.on_loaded.add_last(function() {
1789             var $buttons = self.view_form.$element.find(".oe_form_buttons");
1790             $buttons.html(QWeb.render("SelectCreatePopup.form.buttons"));
1791             var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
1792             $nbutton.click(function() {
1793                 self.view_form.do_save();
1794             });
1795             var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
1796             $cbutton.click(function() {
1797                 self.stop();
1798             });
1799         });
1800         this.dataset.on_create.add(this.on_create);
1801         this.view_form.do_show();
1802     }
1803 });
1804
1805 openerp.base.form.SelectCreateListView = openerp.base.ListView.extend({
1806     do_add_record: function () {
1807         this.popup.new_object();
1808     },
1809     select_record: function(index) {
1810         this.popup.on_select_elements([this.dataset.ids[index]]);
1811     },
1812     do_select: function(ids, records) {
1813         this._super(ids, records);
1814         this.popup.on_click_element(ids);
1815     }
1816 });
1817
1818 openerp.base.form.FieldReference = openerp.base.form.Field.extend({
1819     init: function(view, node) {
1820         this._super(view, node);
1821         this.template = "FieldReference";
1822     }
1823 });
1824
1825 openerp.base.form.FieldBinary = openerp.base.form.Field.extend({
1826     init: function(view, node) {
1827         this._super(view, node);
1828         this.iframe = this.element_id + '_iframe';
1829         this.binary_value = false;
1830     },
1831     start: function() {
1832         this._super.apply(this, arguments);
1833         this.$element.find('input.oe-binary-file').change(this.on_file_change);
1834         this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
1835         this.$element.find('.oe-binary-file-clear').click(this.on_clear);
1836     },
1837     set_value_from_ui: function() {
1838     },
1839     human_filesize : function(size) {
1840         var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
1841         var i = 0;
1842         while (size >= 1024) {
1843             size /= 1024;
1844             ++i;
1845         }
1846         return size.toFixed(2) + ' ' + units[i];
1847     },
1848     on_file_change: function(e) {
1849         // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
1850         // http://www.html5rocks.com/tutorials/file/dndfiles/
1851         // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
1852         window[this.iframe] = this.on_file_uploaded;
1853         if ($(e.target).val() != '') {
1854             this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
1855             this.$element.find('form.oe-binary-form').submit();
1856             this.toggle_progress();
1857         }
1858     },
1859     toggle_progress: function() {
1860         this.$element.find('.oe-binary-progress, .oe-binary').toggle();
1861     },
1862     on_file_uploaded: function(size, name, content_type, file_base64) {
1863         delete(window[this.iframe]);
1864         if (size === false) {
1865             this.notification.warn("File Upload", "There was a problem while uploading your file");
1866             // TODO: use openerp web exception handler
1867             console.log("Error while uploading file : ", name);
1868         } else {
1869             this.on_file_uploaded_and_valid.apply(this, arguments);
1870             this.on_ui_change();
1871         }
1872         this.toggle_progress();
1873     },
1874     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
1875     },
1876     on_save_as: function() {
1877         if (!this.view.datarecord.id) {
1878             this.notification.warn("Can't save file", "The record has not yet been saved");
1879         } else {
1880             var url = '/base/binary/saveas?session_id=' + this.session.session_id + '&model=' +
1881                 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name +
1882                 '&fieldname=' + (this.node.attrs.filename || '') + '&t=' + (new Date().getTime())
1883             window.open(url);
1884         }
1885     },
1886     on_clear: function() {
1887         if (this.value !== false) {
1888             this.value = false;
1889             this.binary_value = false;
1890             this.on_ui_change();
1891         }
1892         return false;
1893     }
1894 });
1895
1896 openerp.base.form.FieldBinaryFile = openerp.base.form.FieldBinary.extend({
1897     init: function(view, node) {
1898         this._super(view, node);
1899         this.template = "FieldBinaryFile";
1900     },
1901     set_value: function(value) {
1902         this._super.apply(this, arguments);
1903         var show_value = (value != null && value !== false) ? value : '';
1904         this.$element.find('input').eq(0).val(show_value);
1905     },
1906     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
1907         this.value = file_base64;
1908         this.binary_value = true;
1909         var show_value = this.human_filesize(size);
1910         this.$element.find('input').eq(0).val(show_value);
1911         this.set_filename(name);
1912     },
1913     set_filename: function(value) {
1914         var filename = this.node.attrs.filename;
1915         if (this.view.fields[filename]) {
1916             this.view.fields[filename].set_value(value);
1917             this.view.fields[filename].on_ui_change();
1918         }
1919     },
1920     on_clear: function() {
1921         this._super.apply(this, arguments);
1922         this.$element.find('input').eq(0).val('');
1923         this.set_filename('');
1924     }
1925 });
1926
1927 openerp.base.form.FieldBinaryImage = openerp.base.form.FieldBinary.extend({
1928     init: function(view, node) {
1929         this._super(view, node);
1930         this.template = "FieldBinaryImage";
1931     },
1932     start: function() {
1933         this._super.apply(this, arguments);
1934         this.$image = this.$element.find('img.oe-binary-image');
1935     },
1936     set_image_maxwidth: function() {
1937         this.$image.css('max-width', this.$element.width());
1938     },
1939     on_file_change: function() {
1940         this.set_image_maxwidth();
1941         this._super.apply(this, arguments);
1942     },
1943     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
1944         this.value = file_base64;
1945         this.binary_value = true;
1946         this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
1947     },
1948     on_clear: function() {
1949         this._super.apply(this, arguments);
1950         this.$image.attr('src', '/base/static/src/img/placeholder.png');
1951     },
1952     set_value: function(value) {
1953         this._super.apply(this, arguments);
1954         this.set_image_maxwidth();
1955         var url = '/base/binary/image?session_id=' + this.session.session_id + '&model=' +
1956             this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime())
1957         this.$image.attr('src', url);
1958     }
1959 });
1960
1961 /**
1962  * Registry of form widgets, called by :js:`openerp.base.FormView`
1963  */
1964 openerp.base.form.widgets = new openerp.base.Registry({
1965     'frame' : 'openerp.base.form.WidgetFrame',
1966     'group' : 'openerp.base.form.WidgetFrame',
1967     'notebook' : 'openerp.base.form.WidgetNotebook',
1968     'separator' : 'openerp.base.form.WidgetSeparator',
1969     'label' : 'openerp.base.form.WidgetLabel',
1970     'button' : 'openerp.base.form.WidgetButton',
1971     'char' : 'openerp.base.form.FieldChar',
1972     'email' : 'openerp.base.form.FieldEmail',
1973     'url' : 'openerp.base.form.FieldUrl',
1974     'text' : 'openerp.base.form.FieldText',
1975     'text_wiki' : 'openerp.base.form.FieldText',
1976     'date' : 'openerp.base.form.FieldDate',
1977     'datetime' : 'openerp.base.form.FieldDatetime',
1978     'selection' : 'openerp.base.form.FieldSelection',
1979     'many2one' : 'openerp.base.form.FieldMany2One',
1980     'many2many' : 'openerp.base.form.FieldMany2Many',
1981     'one2many' : 'openerp.base.form.FieldOne2Many',
1982     'one2many_list' : 'openerp.base.form.FieldOne2Many',
1983     'reference' : 'openerp.base.form.FieldReference',
1984     'boolean' : 'openerp.base.form.FieldBoolean',
1985     'float' : 'openerp.base.form.FieldFloat',
1986     'integer': 'openerp.base.form.FieldFloat',
1987     'progressbar': 'openerp.base.form.FieldProgressBar',
1988     'float_time': 'openerp.base.form.FieldFloatTime',
1989     'image': 'openerp.base.form.FieldBinaryImage',
1990     'binary': 'openerp.base.form.FieldBinaryFile'
1991 });
1992
1993 };
1994
1995 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: