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