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