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