summaryrefslogtreecommitdiffstats
path: root/web/js/labitrack.d/03-labitrack.js
blob: 6da295e9a76e9a45f229c61ff219189d6fd5ef4d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
(function(){
	λ.label = function(){
		var mindata = {
			id: "???",
			name: "Name",
			desc: "Description",
			tags: []
		};

		var render;

		function label()
		{
			this.canvas = null;
			this.bitmap = null;
			this.data = null;
			this.busy = false;
			this.set_template('standard');
			this.renderpreview = new λ.ratelimiter(50, render, this);
		}
		var labelpt = label.prototype;

		labelpt.set_template = function(tmpl){
			this.template = λ.templates.get(tmpl);
			this.update_canvas();
		};

		labelpt.set_canvas = function(canvas){
			this.canvas = canvas;
			this.update_canvas();
		};

		labelpt.set_data = function(data){
			this.data = data;
			this.render();
		};

		render = function(callback, preview){
			if (preview === undef) preview = true;
			var t = this;
			var data = null;
			var params = $.extend({}, mindata, t.data);
			var time = labitrack.utils.time(function(){
				t.busy = true;
				data = t.template.draw(params, preview);
				if (!preview) {
					labitrack.utils.convert_to_monochrome(data);
				} else {
					t.bitmap = data;
					t.update_canvas();
				}
				t.busy = false;
			});
			if (callback) {
				callback.apply(t, [data, time]);
			}
		};

		labelpt.render = function(callback, preview){
			if (preview === false) {
				return render.apply(this, [callback, preview]);
			}
			return this.renderpreview(callback);
		};

		labelpt.update_canvas = function(){
			var bitmap = this.bitmap;
			var canvas = this.canvas;
			if (bitmap !== null && canvas !== null) {
				canvas.width = bitmap.width;
				canvas.height = bitmap.height;
				var ctx = canvas.getContext('2d');
				ctx.putImageData(bitmap, 0, 0);
			}
		};

		labelpt.print = function(){
			console.log("Print label on server");
			this.render(function(data){
				var ctx = labitrack.utils.new_context(data.width, data.height);
				ctx.putImageData(data, 0, 0);
				$.post('/print.json',
					{
						image: ctx.canvas.toDataURL('image/png')
					}, function(data) { console.log('uploaded');}, 'json');
			}, false);
		};

		return label;
	}();

	λ.templates = function(){
		var templates = {};

		return {
			'register': function(key, value){
				templates[key] = value;
			},
			'get': function(key){
				return templates[key];
			}
		};
	}();
}());