]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/xul/staff_client/chrome/content/util/print.js
LP#1129318: fix exception thrown when printing circ receipts
[working/Evergreen.git] / Open-ILS / xul / staff_client / chrome / content / util / print.js
1 dump('entering util/print.js\n');
2
3 if (typeof util == 'undefined') util = {};
4 util.print = function (context) {
5
6     JSAN.use('util.error'); this.error = new util.error();
7     JSAN.use('OpenILS.data'); this.data = new OpenILS.data(); this.data.init( { 'via':'stash' } );
8     JSAN.use('util.window'); this.win = new util.window();
9     JSAN.use('util.functional');
10     JSAN.use('util.file');
11
12     this.set_context(context, true);
13
14     try {
15         var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces['nsIPrefBranch']);
16
17         if (prefs.prefHasUserValue('print.always_print_silent')) {
18             if (! prefs.getBoolPref('print.always_print_silent')) {
19                 prefs.clearUserPref('print.always_print_silent');
20             }
21         }
22     } catch(E) {
23         dump('Error in print.js trying to clear print.always_print_silent\n');
24     }
25
26     return this;
27 };
28
29 util.print.prototype = {
30
31     'set_context' : function(context, set_default) {
32         this.context = context || 'default';
33         if(set_default) this.default_context = this.context;
34     
35         var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces['nsIPrefBranch']);
36         var key = 'oils.printer.external.cmd.' + this.context;
37         var has_key = prefs.prefHasUserValue(key);
38         if(!has_key && this.context != 'default') {
39             key = 'oils.printer.external.cmd.default';
40             has_key = prefs.prefHasUserValue(key);
41         }
42         this.oils_printer_external_cmd = has_key ? prefs.getCharPref(key) : '';
43     },
44
45     'reprint_last' : function() {
46         try {
47             var obj = this; obj.data.init({'via':'stash'});
48             if (!obj.data.last_print) {
49                 alert(
50                     document.getElementById('offlineStrings').getString('printing.nothing_to_reprint')
51                 );
52                 return;
53             }
54             if(obj.data.last_print.context) this.set_context(obj.data.last_print.context);
55             var msg = obj.data.last_print.msg;
56             var params = obj.data.last_print.params; params.no_prompt = false;
57             obj.simple( msg, params );
58         } catch(E) {
59             this.error.standard_unexpected_error_alert('util.print.reprint_last',E);
60         }
61         if(this.context != this.default_context) this.set_context(this.default_context);
62     },
63
64     'html2txt' : function(html) {
65         JSAN.use('util.text');
66         //dump('html2txt, before:\n' + html + '\n');
67         var lines = html.split(/\n/);
68         var new_lines = [];
69         for (var i = 0; i < lines.length; i++) {
70             var line = lines[i];
71             if (line) {
72                 // This undoes the util.text.preserve_string_in_html call that spine_label.js does
73                 line = util.text.reverse_preserve_string_in_html(line);
74                 // This looks for @hex attributes containing 2-digit hex codes, and converts them into real characters
75                 line = line.replace(/(<.+?)hex=['"](.+?)['"](.*?>)/gi, function(str,p1,p2,p3,offset,s) {
76                     var raw_chars = '';
77                     var hex_chars = p2.match(/[0-9,a-f,A-F][0-9,a-f,A-F]/g);
78                     for (var j = 0; j < hex_chars.length; j++) {
79                         raw_chars += String.fromCharCode( parseInt(hex_chars[j],16) );
80                     }
81                     return p1 + p3 + raw_chars;
82                 });
83                 line = line.replace(/<head.*?>.*?<\/head>/gi, '');
84                 line = line.replace(/<br.*?>/gi,'\r\n');
85                 line = line.replace(/<table.*?>/gi,'');
86                 line = line.replace(/<tr.*?>/gi,'');
87                 line = line.replace(/<hr.*?>/gi,'\r\n');
88                 line = line.replace(/<p.*?>/gi,'');
89                 line = line.replace(/<block.*?>/gi,'');
90                 line = line.replace(/<li.*?>/gi,' * ');
91                 line = line.replace(/<.+?>/gi,'');
92                 line = line.replace(/&lt;/gi,'<');
93                 line = line.replace(/&gt;/gi,'>');
94                 line = line.replace(/&amp;/gi,'&');
95                 if (line) { new_lines.push(line); }
96             } else {
97                 new_lines.push(line);
98             }
99         }
100         var new_html = new_lines.join('\n');
101         //dump('html2txt, after:\n' + new_html + '\nhtml2txt, done.\n');
102         return new_html;
103     },
104
105     'escape_html' : function(data) {
106         if (typeof data == 'object') { return ''; }
107         if (typeof data != 'string') { return data; }
108         return data.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
109     },
110
111     'simple' : function(msg,params) {
112         try {
113             if (!params) params = {};
114             params.msg = msg;
115
116             var obj = this;
117
118             obj.data.last_print = { 'msg' : msg, 'params' : params, 'context' : this.context};
119             obj.data.stash('last_print');
120
121             var silent = false;
122             if ( params && params.no_prompt && (params.no_prompt == true || params.no_prompt == 'true') ) {
123                 silent = true;
124             }
125
126             var content_type;
127             if (params && params.content_type) {
128                 content_type = params.content_type;
129             } else {
130                 content_type = 'text/html';
131             }
132
133             var w;
134
135             obj.data.init({'via':'stash'});
136
137             if (typeof obj.data.print_strategy == 'undefined') {
138                 obj.data.print_strategy = {};
139                 obj.data.stash('print_strategy');
140             }
141
142             if (params.print_strategy || obj.data.print_strategy[obj.context] || obj.data.print_strategy['default']) {
143
144                 switch(params.print_strategy || obj.data.print_strategy[obj.context] || obj.data.print_strategy['default']) {
145                     case 'dos.print':
146                         params.dos_print = true;
147                     case 'custom.print':
148                         /* FIXME - this it a kludge.. we're going to sidestep window-based html rendering for printing */
149                         /* I'm using regexps to mangle the html receipt templates; it'd be nice to use xsl but the */
150                         /* templates aren't guaranteed to be valid xml.  The unadulterated msg is still preserved in */
151                         /* params */
152                         if (content_type=='text/html') {
153                             w = obj.html2txt(msg);
154                         } else {
155                             w = msg;
156                         }
157                         if (! params.no_form_feed) { w = w + '\f'; }
158                         obj.NSPrint(w, silent, params);
159                         return;
160                     break;
161                 }
162             }
163
164             switch(content_type) {
165                 case 'text/html' :
166                     if(!params.type) {
167                         params.type = '';
168                     }
169                     var my_prefix = '/xul/server/';
170                     if(window.location.protocol == "chrome:") {
171                         // Likely in offline interface
172                         my_prefix = 'chrome://open_ils_staff_client/content/';
173                     } else {
174                         if(xulG && xulG.url_prefix) {
175                             my_prefix = xulG.url_prefix(my_prefix);
176                         }
177                     }
178                     var print_url = '<html id="top"><head>'
179                         + '<script src="' + my_prefix + 'util/print_win.js"></script>'
180                         + '<script src="' + my_prefix + 'util/print_custom.js"></script>';
181                     if(this.data.hash.aous['print.custom_js_file']) {
182                         print_url += '<script src="' + this.data.hash.aous['print.custom_js_file'] + '"></script>';
183                     }
184                     print_url += '</head><body onload="try{print_init(\'' + params.type + '\');}catch(E){alert(E);}">' + msg.replace(/<script[^>]*>.*?<\/script>/gi,'') + '</body></html>';
185                     print_url = 'data:text/html;charset=utf-8,' + encodeURIComponent(print_url);
186                     obj.win.openDialog(print_url,'receipt_temp','chrome,resizable,modal', { "data" : params.data, "list" : params.list}, function(w) { 
187                         try {
188                             obj.NSPrint(w, silent, params);
189                         } catch(E) {
190                             obj.error.standard_unexpected_error_alert("Print Error in util.print.simple.  After this dialog we'll try a second print attempt. content_type = " + content_type,E);
191                             w.print();
192                         }
193                         w.close();
194                     });
195                 break;
196                 default:
197                     w = obj.win.open('data:' + content_type + ',' + window.escape(msg),'receipt_temp','chrome,resizable');
198                     w.minimize();
199                     setTimeout(
200                         function() {
201                             try {
202                                 obj.NSPrint(w, silent, params);
203                             } catch(E) {
204                                 obj.error.standard_unexpected_error_alert("Print Error in util.print.simple.  After this dialog we'll try a second print attempt. content_type = " + content_type,E);
205                                 w.print();
206                             }
207                             w.minimize(); w.close();
208                         }, 1000
209                     );
210                 break;
211             }
212
213         } catch(E) {
214             this.error.standard_unexpected_error_alert('util.print.simple',E);
215         }
216     },
217     
218     'tree_list' : function (params) { 
219         try {
220             dump('print.tree_list.params.list = \n' + this.error.pretty_print(js2JSON(params.list)) + '\n');
221             dump('print.tree_list.params.data = \n' + this.error.pretty_print(js2JSON(params.data)) + '\n');
222         } catch(E) {
223             dump(E+'\n');
224         }
225         var cols = [];
226         var s = '';
227         if (params.context) this.set_context(params.context);
228         if (params.header) s += this.template_sub( params.header, cols, params );
229         if (params.list) {
230             // Pre-templating sort
231             // %SORT(field[ AS type][ ASC|DESC][,...])%
232             var sort_blocks = params.line_item.match(/%SORT\([^)]+\)%/g);
233             if(sort_blocks) {
234                 for(var i = 0; i < sort_blocks.length; i++) {
235                     sort_blocks[i] = sort_blocks[i].substring(6,sort_blocks[i].length-2);
236                 }
237                 sort_blocks = sort_blocks.join(',').split(/\s*,\s*/); // Supports %SORT(a,b)% and %SORT(a)% %SORT(b)% methods
238                 for(var i = 0; i < sort_blocks.length; i++) {
239                     sort_blocks[i] = sort_blocks[i].match(/([^ ]+)(?:\s+AS\s+([^ ]+))?(?:\s+(ASC|DESC))?/);
240                     sort_blocks[i].shift(); // Removes the "full match" entry
241                 }
242
243                 function sorter(a, b) {
244                     var return_val = 0;
245                     for(var i = 0; i < sort_blocks.length && return_val == 0; i++) {
246                         var sort = sort_blocks[i];
247                         var a_test = a[sort[0]];
248                         var b_test = b[sort[0]];
249                         sort[1] = sort[1] || '';
250                         sort[2] = sort[2] || 'ASC';
251                         switch(sort[1].toUpperCase()) {
252                             case 'DATE':
253                                 a_test = new Date(a_test);
254                                 b_test = new Date(b_test);
255                                 break;
256                             case 'INT':
257                                 a_test = parseInt(a_test);
258                                 b_test = parseInt(b_test);
259                                 break;
260                             case 'FLOAT':
261                             case 'NUMBER':
262                                 a_test = parseFloat(a_test);
263                                 b_test = parseFloat(b_test);
264                                 break;
265                             case 'LOWER':
266                                 a_test = a_test.toLowerCase();
267                                 b_test = b_test.toLowerCase();
268                                 break;
269                             case 'UPPER':
270                                 a_test = a_test.toUpperCase();
271                                 b_test = b_test.toUpperCase();
272                                 break;
273                         }
274                         if(a_test > b_test) return_val = 1;
275                         if(a_test < b_test) return_val = -1;
276                         if(sort[2] == 'DESC') return_val *= -1;
277                     }
278                     return return_val;
279                 }
280                 params.list.sort(sorter);
281                 params.line_item = params.line_item.replace(/%SORT\([^)]*\)%/g,'');
282             }
283
284             for (var i = 0; i < params.list.length; i++) {
285                 params.row = params.list[i];
286                 params.row_idx = i;
287                 s += this.template_sub( params.line_item, cols, params );
288             }
289         }
290         if (params.footer) s += this.template_sub( params.footer, cols, params );
291
292         // Sanity check, no javascript in templates
293         // Note: [\s\S] is a workaround for . not including newlines.
294         s=s.replace(/<script[^>]*>[\s\S]*?<\/script[^>]*>/gi,'')
295         s=s.replace(/onload\s*=\s*"[^"]*"/gi,'');
296         s=s.replace(/onload\s*=\s*'[^']*'/gi,'');
297
298         if (params.sample_frame) {
299             var jsrc = 'data:text/javascript,' + encodeURIComponent('var params = { "data" : ' + js2JSON(params.data) + ', "list" : ' + js2JSON(params.list) + '};');
300             params.sample_frame.setAttribute('src','data:text/html;charset=utf-8,' + encodeURIComponent('<html id="top"><head><script src="' + jsrc + '"></script></head><body>' + s + '</body></html>'));
301         } else {
302             this.simple(s,params);
303         }
304         if(this.context != this.default_context) this.set_context(this.default_context);
305     },
306
307     'template_sub' : function( msg, cols, params ) {
308         try {
309             var obj = this;
310             if (!msg) { dump('template sub called with empty string\n'); return; }
311             JSAN.use('util.date');
312             var s = msg; var b;
313
314             // Includes
315             // Note that we keep track of already included settings
316             // This ensures that we don't infinite loop through includes
317             try {
318                 var match;
319                 var include_patt=/%INCLUDE\(\s*([^)]*?)\s*\)%/;
320                 var included = {};
321                 while(match = include_patt.exec(s)) {
322                     if(match[1] == '' || included[match[1]]) {
323                         s = s.replace(match[0], '');
324                     } else {
325                         included[match[1]] = true;
326                         s = s.replace(new RegExp("%INCLUDE\\(\\s*" + match[1].replace(/([.?*+^$[\]\\(){}-])/g, "\\$1") + "\\s*\\)%","g"), obj.data.hash.aous['circ.staff_client.receipt.' + match[1]] || '');
327                     }
328                 }
329             } catch(E) { dump(E+'\n'); }
330
331             try{b = s; s = s.replace(/%LINE_NO%/g,Number(params.row_idx)+1);}
332                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
333
334             try{b = s; s = s.replace(/%patron_barcode%/g,this.escape_html(params.patron_barcode));}
335                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
336
337             try{b = s; s = s.replace(/%LIBRARY%/g,this.escape_html(params.lib.name()));}
338                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
339             try{b = s; s = s.replace(/%PINES_CODE%/g,this.escape_html(params.lib.shortname()));}
340                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
341             try{b = s; s = s.replace(/%SHORTNAME%/g,this.escape_html(params.lib.shortname()));}
342                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
343             try{b = s; s = s.replace(/%STAFF_FIRSTNAME%/g,this.escape_html(params.staff.first_given_name()));}
344                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
345             try{b = s; s = s.replace(/%STAFF_MIDDLENAME%/g,this.escape_html(params.staff.second_given_name() || ''));}
346                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
347             try{b = s; s = s.replace(/%STAFF_LASTNAME%/g,this.escape_html(params.staff.family_name()));}
348                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
349             try{b = s; s = s.replace(/%STAFF_BARCODE%/g,this.escape_html(params.staff.barcode)); }
350                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
351             try{b = s; s = s.replace(/%STAFF_PROFILE%/g,this.escape_html(obj.data.hash.pgt[ params.staff.profile() ].name() )); }
352                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
353             try{b = s; s = s.replace(/%PATRON_ALIAS_OR_FIRSTNAME%/g,this.escape_html((params.patron.alias() == '' || params.patron.alias() == null) ? params.patron.first_given_name() : params.patron.alias()));}
354                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
355             try{b = s; s = s.replace(/%PATRON_ALIAS%/g,this.escape_html((params.patron.alias() == '' || params.patron.alias() == null) ? '' : params.patron.alias()));}
356                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
357             try{b = s; s = s.replace(/%PATRON_FIRSTNAME%/g,this.escape_html(params.patron.first_given_name()));}
358                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
359             try{b = s; s = s.replace(/%PATRON_MIDDLENAME%/g,this.escape_html(params.patron.second_given_name() || ''));}
360                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
361             try{b = s; s = s.replace(/%PATRON_LASTNAME%/g,this.escape_html(params.patron.family_name()));}
362                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
363             try{b = s; s = s.replace(/%PATRON_BARCODE%/g,this.escape_html(typeof params.patron.card() == 'object' ? params.patron.card().barcode() : util.functional.find_id_object_in_list( params.patron.cards(), params.patron.card() ).barcode() )) ;}
364                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
365             try{b = s; s = s.replace(/%PATRON_EXPIRE_DATE%/g,this.escape_html(params.patron.expire_date()));}
366                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
367             try{b = s; s = s.replace(/%PATRON_EXPIRE_DATE_YMD%/g,util.date.formatted_date(params.patron.expire_date(), '%Y-%m-%d'));}
368                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
369
370             try{b = s; s=s.replace(/%TODAY%/g,(new Date()));}
371                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
372             try{b = s; s=s.replace(/%TODAY_m%/g,(util.date.formatted_date(new Date(),'%m')));}
373                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
374             try{b = s; s=s.replace(/%TODAY_TRIM%/g,(util.date.formatted_date(new Date(),'')));}
375                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
376             try{b = s; s=s.replace(/%TODAY_d%/g,(util.date.formatted_date(new Date(),'%d')));}
377                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
378             try{b = s; s=s.replace(/%TODAY_Y%/g,(util.date.formatted_date(new Date(),'%Y')));}
379                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
380             try{b = s; s=s.replace(/%TODAY_H%/g,(util.date.formatted_date(new Date(),'%H')));}
381                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
382             try{b = s; s=s.replace(/%TODAY_I%/g,(util.date.formatted_date(new Date(),'%I')));}
383                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
384             try{b = s; s=s.replace(/%TODAY_M%/g,(util.date.formatted_date(new Date(),'%M')));}
385                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
386             try{b = s; s=s.replace(/%TODAY_D%/g,(util.date.formatted_date(new Date(),'%D')));}
387                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
388             try{b = s; s=s.replace(/%TODAY_F%/g,(util.date.formatted_date(new Date(),'%F')));}
389                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
390
391             try {
392                 if (typeof params.row != 'undefined') {
393                     if (params.row.length >= 0) {
394                         alert('debug - please tell the developers that deprecated template code tried to execute');
395                         for (var i = 0; i < cols.length; i++) {
396                             var re = new RegExp(cols[i],"g");
397                             try{b = s; s=s.replace(re, this.escape_html(params.row[i]));}
398                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 1 string = <' + s + '>',E);}
399                         }
400                     } else { 
401                         /* for dump_with_keys */
402                         for (var i in params.row) {
403                             var re = new RegExp('%'+i+'%',"g");
404                             try{b = s; s=s.replace(re, this.escape_html(params.row[i].toString()));}
405                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 2 string = <' + s + '>',E);}
406                         }
407                     }
408                 }
409
410                 if (typeof params.data != 'undefined') {
411                     for (var i in params.data) {
412                         var re = new RegExp('%'+i+'%',"g");
413                         if (typeof params.data[i] == 'string' || typeof params.data[i] == 'number') {
414                             try{b = s; s=s.replace(re, this.escape_html(params.data[i]));}
415                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 3 string = <' + s + '>',E);}
416                         } else {
417                             /* likely a null, print as an empty string */
418                             try{b = s; s=s.replace(re, '');}
419                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 3 string = <' + s + '>',E);}
420                         }
421                     }
422                 }
423             } catch(E) { dump(E+'\n'); }
424
425             // Date Format
426             try {
427                 var match;
428                 var date_format_patt=/%DATE_FORMAT\(\s*([^,]*?)\s*,\s*([^)]*?)\s*\)%/;
429                 while(match = date_format_patt.exec(s)) {
430                     if(match[1] == '' || match[2] == '')
431                         s = s.replace(match[0], '');
432                     else
433                         s = s.replace(match[0], util.date.formatted_date(match[1], match[2]));
434                 }
435             } catch(E) { dump(E+'\n'); }
436
437             // Substrings
438             try {
439                 var match;
440                 // Pre-trim inside of substrings, and only inside of them
441                 // This keeps the trim commands from being truncated
442                 var substr_trim_patt=/(%SUBSTR\(-?\d+,?\s*(-?\d+)?\)%.*?)(\s*%-TRIM%|%TRIM-%\s*)(.*?%SUBSTR_END%)/;
443                 while(match = substr_trim_patt.exec(s))
444                     s = s.replace(match[0], match[1] + match[4]);
445                 // Then do the substrings themselves
446                 var substr_patt=/%SUBSTR\((-?\d+),?\s*(-?\d+)?\)%(.*?)%SUBSTR_END%/;
447                 while(match = substr_patt.exec(s)) {
448                     var substring_start = parseInt(match[1]);
449                     if(substring_start < 0) substring_start = match[3].length + substring_start;
450                     var substring_length = parseInt(match[2]);
451                     if(substring_length > 0)
452                         s = s.replace(match[0], match[3].substring(substring_start, substring_start + substring_length));
453                     else if(substring_length < 0)
454                         s = s.replace(match[0], match[3].substring(substring_start + substring_length, substring_start));
455                     else
456                         s = s.replace(match[0], match[3].substring(substring_start));
457                 }
458             } catch(E) { dump(E+'\n'); }
459
460             // Cleanup unwanted whitespace
461             try {
462                 s = s.replace(/%TRIM-%\s*/g,'');
463                 s = s.replace(/\s*%-TRIM%/g,'');
464             } catch(E) { dump(E+'\n'); }
465
466             return s;
467         } catch(E) {
468             alert('Error in print.js, template_sub(): ' + E);
469         }
470     },
471
472
473     'NSPrint' : function(w,silent,params) {
474         if (!w) w = window;
475         var obj = this;
476         try {
477             if (!params) params = {};
478
479             obj.data.init({'via':'stash'});
480
481             if (params.print_strategy || obj.data.print_strategy[obj.context] || obj.data.print_strategy['default']) {
482
483                 dump('params.print_strategy = ' + params.print_strategy
484                     + ' || obj.data.print_strategy[' + obj.context + '] = ' + obj.data.print_strategy[obj.context] 
485                     + ' || obj.data.print_strategy[default] = ' + obj.data.print_strategy['default'] 
486                     + ' => ' + ( params.print_strategy || obj.data.print_strategy[obj.context] || obj.data.print_strategy['default'] ) + '\n');
487                 switch(params.print_strategy || obj.data.print_strategy[obj.context] || obj.data.print_strategy['default']) {
488                     case 'dos.print':
489                         params.dos_print = true;
490                     case 'custom.print':
491                         if (typeof w != 'string') {
492                             try {
493                                 var temp_w = params.msg || w.document.firstChild.innerHTML;
494                                 if (!params.msg) { params.msg = temp_w; }
495                                 if (typeof temp_w != 'string') { throw(temp_w); }
496                                 w = obj.html2txt(temp_w);
497                             } catch(E) {
498                                 dump('util.print: Could not use w.document.firstChild.innerHTML with ' + w + ': ' + E + '\n');
499                                 w.getSelection().selectAllChildren(w.document.firstChild);
500                                 w = w.getSelection().toString();
501                             }
502                         }
503                         obj._NSPrint_custom_print(w,silent,params);
504                     break;    
505                     case 'window.print':
506                         var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces['nsIPrefBranch']);
507                         var originalPrinter = false;
508                         if (prefs.prefHasUserValue('print.print_printer')) {
509                             // This is for restoring print.print_printer after any print dialog, so that when
510                             // window.print gets used again, it uses the configured printer for the right context
511                             // (which should only be default--window.print is a kludge and is in limited use),
512                             // rather than the printer last used.
513                             originalPrinter = prefs.getCharPref('print.print_printer');
514                         }
515                         if (typeof w == 'object') {
516                             w.print();
517                             if (originalPrinter) {
518                                 prefs.setCharPref('print.print_printer',originalPrinter);
519                             }
520                         } else {
521                             if (params.content_type == 'text/plain') {
522                                 w = window.open('data:text/plain,'+escape(params.msg),'','chrome');
523                             } else {
524                                 w = window.open('data:text/html,'+escape(params.msg),'','chrome');
525                             }
526                             setTimeout(
527                                 function() {
528                                     w.print();
529                                     if (originalPrinter) {
530                                         prefs.setCharPref('print.print_printer',originalPrinter);
531                                     }
532                                     setTimeout(
533                                         function() {
534                                             w.close(); 
535                                         }, 2000
536                                     );
537                                 }, 0
538                             );
539                         }
540                     break;    
541                     case 'webBrowserPrint':
542                     default:
543                         if (typeof w == 'object') {
544                             obj._NSPrint_webBrowserPrint(w,silent,params);
545                         } else {
546                             if (params.content_type == 'text/plain') {
547                                 w = window.open('data:text/plain,'+escape(params.msg),'','chrome');
548                             } else {
549                                 w = window.open('data:text/html,'+escape(params.msg),'','chrome');
550                             }
551                             setTimeout(
552                                 function() {
553                                     obj._NSPrint_webBrowserPrint(w,silent,params);
554                                     setTimeout(
555                                         function() {
556                                             w.close(); 
557                                         }, 2000
558                                     );
559                                 }, 0
560                             );
561                         }
562                     break;    
563                 }
564
565             } else {
566                 //w.print();
567                 obj._NSPrint_webBrowserPrint(w,silent,params);
568             }
569
570         } catch (e) {
571             alert('Probably not printing: ' + e);
572             this.error.sdump('D_ERROR','PRINT EXCEPTION: ' + js2JSON(e) + '\n');
573         }
574
575     },
576
577     '_NSPrint_custom_print' : function(w,silent,params) {
578         var obj = this;
579         try {
580
581             var text = w;
582             var html = params.msg || w;
583
584             var txt_file = new util.file('receipt.txt');
585             txt_file.write_content('truncate',text); 
586             var text_path = '"' + txt_file._file.path + '"';
587             txt_file.close();
588
589             var html_file = new util.file('receipt.html');
590             html_file.write_content('truncate',html); 
591             var html_path = '"' + html_file._file.path + '"';
592             html_file.close();
593             
594             var cmd = params.dos_print ?
595                 'copy ' + text_path + ' lpt1 /b\n'
596                 : obj.oils_printer_external_cmd.replace('%receipt.txt%',text_path).replace('%receipt.html%',html_path)
597             ;
598
599             file = new util.file('receipt.bat');
600             file.write_content('truncate+exec',cmd);
601             file.close();
602             file = new util.file('receipt.bat');
603
604             dump('print exec: ' + cmd + '\n');
605             var process = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);
606             process.init(file._file);
607
608             var args = [];
609
610             dump('process.run = ' + process.run(true, args, args.length) + '\n');
611
612             file.close();
613
614         } catch (e) {
615             //alert('Probably not printing: ' + e);
616             this.error.sdump('D_ERROR','_NSPrint_custom_print PRINT EXCEPTION: ' + js2JSON(e) + '\n');
617         }
618     },
619
620     '_NSPrint_webBrowserPrint' : function(w,silent,params) {
621         var obj = this;
622         try {
623             var webBrowserPrint = w
624                 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
625                 .getInterface(Components.interfaces.nsIWebBrowserPrint);
626             this.error.sdump('D_PRINT','webBrowserPrint = ' + webBrowserPrint);
627             if (webBrowserPrint) {
628                 var gPrintSettings = obj.GetPrintSettings();
629                 if (silent) gPrintSettings.printSilent = true;
630                 else gPrintSettings.printSilent = false;
631                 if (params) {
632                     if (params.marginLeft) gPrintSettings.marginLeft = params.marginLeft;
633                 }
634                 webBrowserPrint.print(gPrintSettings, null);
635                 this.error.sdump('D_PRINT','Should be printing\n');
636             } else {
637                 this.error.sdump('D_ERROR','Should not be printing\n');
638             }
639         } catch (e) {
640             //alert('Probably not printing: ' + e);
641             // Pressing cancel is expressed as an NS_ERROR_ABORT return value,
642             // causing an exception to be thrown which we catch here.
643             // Unfortunately this will also consume helpful failures
644             this.error.sdump('D_ERROR','_NSPrint_webBrowserPrint PRINT EXCEPTION: ' + js2JSON(e) + '\n');
645         }
646     },
647
648     'GetPrintSettings' : function() {
649         try {
650             //alert('entering GetPrintSettings');
651             var pref = Components.classes["@mozilla.org/preferences-service;1"]
652                 .getService(Components.interfaces.nsIPrefBranch);
653             //alert('pref = ' + pref);
654             if (pref) {
655                 this.gPrintSettingsAreGlobal = pref.getBoolPref("print.use_global_printsettings", false);
656                 this.gSavePrintSettings = pref.getBoolPref("print.save_print_settings", false);
657                 //alert('gPrintSettingsAreGlobal = ' + this.gPrintSettingsAreGlobal + '  gSavePrintSettings = ' + this.gSavePrintSettings);
658             }
659  
660             var printService = Components.classes["@mozilla.org/gfx/printsettings-service;1"]
661                 .getService(Components.interfaces.nsIPrintSettingsService);
662             if (this.gPrintSettingsAreGlobal) {
663                 this.gPrintSettings = printService.globalPrintSettings;
664                 //alert('called setPrinterDefaultsForSelectedPrinter');
665                 this.setPrinterDefaultsForSelectedPrinter(printService);
666             } else {
667                 this.gPrintSettings = printService.newPrintSettings;
668                 //alert('used printService.newPrintSettings');
669             }
670         } catch (e) {
671             this.error.sdump('D_ERROR',"GetPrintSettings() "+e+"\n");
672             //alert("GetPrintSettings() "+e+"\n");
673         }
674  
675         return this.gPrintSettings;
676     },
677
678     'setPrinterDefaultsForSelectedPrinter' : function (aPrintService) {
679         try {
680             if (this.gPrintSettings.printerName == "") {
681                 this.gPrintSettings.printerName = aPrintService.defaultPrinterName;
682                 //alert('used .defaultPrinterName');
683             }
684             //alert('printerName = ' + this.gPrintSettings.printerName);
685      
686             // First get any defaults from the printer 
687             aPrintService.initPrintSettingsFromPrinter(this.gPrintSettings.printerName, this.gPrintSettings);
688      
689             // now augment them with any values from last time
690             aPrintService.initPrintSettingsFromPrefs(this.gPrintSettings, true, this.gPrintSettings.kInitSaveAll);
691
692             // now augment from our own saved settings if they exist
693             this.load_settings();
694
695         } catch(E) {
696             this.error.sdump('D_ERROR',"setPrinterDefaultsForSelectedPrinter() "+E+"\n");
697         }
698     },
699
700     'page_settings' : function() {
701         try {
702             this.GetPrintSettings();
703             var PO = Components.classes["@mozilla.org/gfx/printsettings-service;1"].getService(Components.interfaces.nsIPrintOptions);
704             PO.ShowPrintSetupDialog(this.gPrintSettings);
705         } catch(E) {
706             this.error.standard_unexpected_error_alert("page_settings()",E);
707         }
708     },
709
710     'load_settings' : function() {
711         try {
712             var error_msg = '';
713             var file = new util.file('gPrintSettings.' + this.context);
714             if (file._file.exists()) {
715                 temp = file.get_object(); file.close();
716                 for (var i in temp) {
717                     try { this.gPrintSettings[i] = temp[i]; } catch(E) { error_msg += 'Error trying to set gPrintSettings.'+i+'='+temp[i]+' : ' + js2JSON(E) + '\n'; }
718                 }
719             }  else if (this.context != 'default') {
720                 var file = new util.file('gPrintSettings.default');
721                 if (file._file.exists()) {
722                     temp = file.get_object(); file.close();
723                     for (var i in temp) {
724                         try { this.gPrintSettings[i] = temp[i]; } catch(E) { error_msg += 'Error trying to set gPrintSettings.'+i+'='+temp[i]+' : ' + js2JSON(E) + '\n'; }
725                     }
726                 } else {
727                     this.gPrintSettings.marginTop = 0;
728                     this.gPrintSettings.marginLeft = 0;
729                     this.gPrintSettings.marginBottom = 0;
730                     this.gPrintSettings.marginRight = 0;
731                     this.gPrintSettings.headerStrLeft = '';
732                     this.gPrintSettings.headerStrCenter = '';
733                     this.gPrintSettings.headerStrRight = '';
734                     this.gPrintSettings.footerStrLeft = '';
735                     this.gPrintSettings.footerStrCenter = '';
736                     this.gPrintSettings.footerStrRight = '';
737                 }
738             }
739             if (error_msg) {
740                 this.error.sdump('D_PRINT',error_msg);
741                 this.error.yns_alert(
742                     document.getElementById('offlineStrings').getString('load_printer_settings_error_description'),
743                     document.getElementById('offlineStrings').getString('load_printer_settings_error_title'),
744                     document.getElementById('offlineStrings').getString('common.ok'),
745                     null,
746                     null,
747                     null
748                 );
749             }
750         } catch(E) {
751             this.error.standard_unexpected_error_alert("load_settings()",E);
752         }
753     },
754
755     'save_settings' : function() {
756         try {
757             var obj = this;
758             var file = new util.file('gPrintSettings.' + this.context);
759             if (typeof obj.gPrintSettings == 'undefined') obj.GetPrintSettings();
760             if (obj.gPrintSettings) file.set_object(obj.gPrintSettings); 
761             file.close();
762             if (this.context == 'default') {
763                 // print.print_printer gets used by bare window.print()'s.  We sometimes use window.print for the
764                 // WebBrowserPrint strategy to workaround bugs with the NSPrint xpcom, and only in the default context.
765                 var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces['nsIPrefBranch']);
766                 prefs.setCharPref('print.print_printer',obj.gPrintSettings.printerName);
767             }
768         } catch(E) {
769             this.error.standard_unexpected_error_alert("save_settings()",E);
770         }
771     }
772 }
773
774 dump('exiting util/print.js\n');