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