]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/xul/staff_client/chrome/content/util/print.js
Fix foreign character display in receipts
[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_LASTNAME%/g,this.escape_html(params.staff.family_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_BARCODE%/g,this.escape_html(params.staff.barcode)); }
348                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
349             try{b = s; s = s.replace(/%STAFF_PROFILE%/g,this.escape_html(obj.data.hash.pgt[ params.staff.profile() ].name() )); }
350                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
351             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()));}
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%/g,this.escape_html((params.patron.alias() == '' || params.patron.alias() == null) ? '' : 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_FIRSTNAME%/g,this.escape_html(params.patron.first_given_name()));}
356                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
357             try{b = s; s = s.replace(/%PATRON_LASTNAME%/g,this.escape_html(params.patron.family_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_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() )) ;}
360                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
361
362             try{b = s; s=s.replace(/%TODAY%/g,(new Date()));}
363                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
364             try{b = s; s=s.replace(/%TODAY_m%/g,(util.date.formatted_date(new Date(),'%m')));}
365                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
366             try{b = s; s=s.replace(/%TODAY_TRIM%/g,(util.date.formatted_date(new Date(),'')));}
367                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
368             try{b = s; s=s.replace(/%TODAY_d%/g,(util.date.formatted_date(new Date(),'%d')));}
369                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
370             try{b = s; s=s.replace(/%TODAY_Y%/g,(util.date.formatted_date(new Date(),'%Y')));}
371                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
372             try{b = s; s=s.replace(/%TODAY_H%/g,(util.date.formatted_date(new Date(),'%H')));}
373                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
374             try{b = s; s=s.replace(/%TODAY_I%/g,(util.date.formatted_date(new Date(),'%I')));}
375                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
376             try{b = s; s=s.replace(/%TODAY_M%/g,(util.date.formatted_date(new Date(),'%M')));}
377                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
378             try{b = s; s=s.replace(/%TODAY_D%/g,(util.date.formatted_date(new Date(),'%D')));}
379                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
380             try{b = s; s=s.replace(/%TODAY_F%/g,(util.date.formatted_date(new Date(),'%F')));}
381                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
382
383             try {
384                 if (typeof params.row != 'undefined') {
385                     if (params.row.length >= 0) {
386                         alert('debug - please tell the developers that deprecated template code tried to execute');
387                         for (var i = 0; i < cols.length; i++) {
388                             var re = new RegExp(cols[i],"g");
389                             try{b = s; s=s.replace(re, this.escape_html(params.row[i]));}
390                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 1 string = <' + s + '>',E);}
391                         }
392                     } else { 
393                         /* for dump_with_keys */
394                         for (var i in params.row) {
395                             var re = new RegExp('%'+i+'%',"g");
396                             try{b = s; s=s.replace(re, this.escape_html(params.row[i].toString()));}
397                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 2 string = <' + s + '>',E);}
398                         }
399                     }
400                 }
401
402                 if (typeof params.data != 'undefined') {
403                     for (var i in params.data) {
404                         var re = new RegExp('%'+i+'%',"g");
405                         if (typeof params.data[i] == 'string' || typeof params.data[i] == 'number') {
406                             try{b = s; s=s.replace(re, this.escape_html(params.data[i]));}
407                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 3 string = <' + s + '>',E);}
408                         } else {
409                             /* likely a null, print as an empty string */
410                             try{b = s; s=s.replace(re, '');}
411                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 3 string = <' + s + '>',E);}
412                         }
413                     }
414                 }
415             } catch(E) { dump(E+'\n'); }
416
417             // Date Format
418             try {
419                 var match;
420                 var date_format_patt=/%DATE_FORMAT\(\s*([^,]*?)\s*,\s*([^)]*?)\s*\)%/;
421                 while(match = date_format_patt.exec(s)) {
422                     if(match[1] == '' || match[2] == '')
423                         s = s.replace(match[0], '');
424                     else
425                         s = s.replace(match[0], util.date.formatted_date(match[1], match[2]));
426                 }
427             } catch(E) { dump(E+'\n'); }
428
429             // Substrings
430             try {
431                 var match;
432                 // Pre-trim inside of substrings, and only inside of them
433                 // This keeps the trim commands from being truncated
434                 var substr_trim_patt=/(%SUBSTR\(-?\d+,?\s*(-?\d+)?\)%.*?)(\s*%-TRIM%|%TRIM-%\s*)(.*?%SUBSTR_END%)/;
435                 while(match = substr_trim_patt.exec(s))
436                     s = s.replace(match[0], match[1] + match[4]);
437                 // Then do the substrings themselves
438                 var substr_patt=/%SUBSTR\((-?\d+),?\s*(-?\d+)?\)%(.*?)%SUBSTR_END%/;
439                 while(match = substr_patt.exec(s)) {
440                     var substring_start = parseInt(match[1]);
441                     if(substring_start < 0) substring_start = match[3].length + substring_start;
442                     var substring_length = parseInt(match[2]);
443                     if(substring_length > 0)
444                         s = s.replace(match[0], match[3].substring(substring_start, substring_start + substring_length));
445                     else if(substring_length < 0)
446                         s = s.replace(match[0], match[3].substring(substring_start + substring_length, substring_start));
447                     else
448                         s = s.replace(match[0], match[3].substring(substring_start));
449                 }
450             } catch(E) { dump(E+'\n'); }
451
452             // Cleanup unwanted whitespace
453             try {
454                 s = s.replace(/%TRIM-%\s*/g,'');
455                 s = s.replace(/\s*%-TRIM%/g,'');
456             } catch(E) { dump(E+'\n'); }
457
458             return s;
459         } catch(E) {
460             alert('Error in print.js, template_sub(): ' + E);
461         }
462     },
463
464
465     'NSPrint' : function(w,silent,params) {
466         if (!w) w = window;
467         var obj = this;
468         try {
469             if (!params) params = {};
470
471             obj.data.init({'via':'stash'});
472
473             if (params.print_strategy || obj.data.print_strategy[obj.context] || obj.data.print_strategy['default']) {
474
475                 dump('params.print_strategy = ' + params.print_strategy
476                     + ' || obj.data.print_strategy[' + obj.context + '] = ' + obj.data.print_strategy[obj.context] 
477                     + ' || obj.data.print_strategy[default] = ' + obj.data.print_strategy['default'] 
478                     + ' => ' + ( params.print_strategy || obj.data.print_strategy[obj.context] || obj.data.print_strategy['default'] ) + '\n');
479                 switch(params.print_strategy || obj.data.print_strategy[obj.context] || obj.data.print_strategy['default']) {
480                     case 'dos.print':
481                         params.dos_print = true;
482                     case 'custom.print':
483                         if (typeof w != 'string') {
484                             try {
485                                 var temp_w = params.msg || w.document.firstChild.innerHTML;
486                                 if (!params.msg) { params.msg = temp_w; }
487                                 if (typeof temp_w != 'string') { throw(temp_w); }
488                                 w = obj.html2txt(temp_w);
489                             } catch(E) {
490                                 dump('util.print: Could not use w.document.firstChild.innerHTML with ' + w + ': ' + E + '\n');
491                                 w.getSelection().selectAllChildren(w.document.firstChild);
492                                 w = w.getSelection().toString();
493                             }
494                         }
495                         obj._NSPrint_custom_print(w,silent,params);
496                     break;    
497                     case 'window.print':
498                         var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces['nsIPrefBranch']);
499                         var originalPrinter = false;
500                         if (prefs.prefHasUserValue('print.print_printer')) {
501                             // This is for restoring print.print_printer after any print dialog, so that when
502                             // window.print gets used again, it uses the configured printer for the right context
503                             // (which should only be default--window.print is a kludge and is in limited use),
504                             // rather than the printer last used.
505                             originalPrinter = prefs.getCharPref('print.print_printer');
506                         }
507                         if (typeof w == 'object') {
508                             w.print();
509                             if (originalPrinter) {
510                                 prefs.setCharPref('print.print_printer',originalPrinter);
511                             }
512                         } else {
513                             if (params.content_type == 'text/plain') {
514                                 w = window.open('data:text/plain,'+escape(params.msg),'','chrome');
515                             } else {
516                                 w = window.open('data:text/html,'+escape(params.msg),'','chrome');
517                             }
518                             setTimeout(
519                                 function() {
520                                     w.print();
521                                     if (originalPrinter) {
522                                         prefs.setCharPref('print.print_printer',originalPrinter);
523                                     }
524                                     setTimeout(
525                                         function() {
526                                             w.close(); 
527                                         }, 2000
528                                     );
529                                 }, 0
530                             );
531                         }
532                     break;    
533                     case 'webBrowserPrint':
534                     default:
535                         if (typeof w == 'object') {
536                             obj._NSPrint_webBrowserPrint(w,silent,params);
537                         } else {
538                             if (params.content_type == 'text/plain') {
539                                 w = window.open('data:text/plain,'+escape(params.msg),'','chrome');
540                             } else {
541                                 w = window.open('data:text/html,'+escape(params.msg),'','chrome');
542                             }
543                             setTimeout(
544                                 function() {
545                                     obj._NSPrint_webBrowserPrint(w,silent,params);
546                                     setTimeout(
547                                         function() {
548                                             w.close(); 
549                                         }, 2000
550                                     );
551                                 }, 0
552                             );
553                         }
554                     break;    
555                 }
556
557             } else {
558                 //w.print();
559                 obj._NSPrint_webBrowserPrint(w,silent,params);
560             }
561
562         } catch (e) {
563             alert('Probably not printing: ' + e);
564             this.error.sdump('D_ERROR','PRINT EXCEPTION: ' + js2JSON(e) + '\n');
565         }
566
567     },
568
569     '_NSPrint_custom_print' : function(w,silent,params) {
570         var obj = this;
571         try {
572
573             var text = w;
574             var html = params.msg || w;
575
576             var txt_file = new util.file('receipt.txt');
577             txt_file.write_content('truncate',text); 
578             var text_path = '"' + txt_file._file.path + '"';
579             txt_file.close();
580
581             var html_file = new util.file('receipt.html');
582             html_file.write_content('truncate',html); 
583             var html_path = '"' + html_file._file.path + '"';
584             html_file.close();
585             
586             var cmd = params.dos_print ?
587                 'copy ' + text_path + ' lpt1 /b\n'
588                 : obj.oils_printer_external_cmd.replace('%receipt.txt%',text_path).replace('%receipt.html%',html_path)
589             ;
590
591             file = new util.file('receipt.bat');
592             file.write_content('truncate+exec',cmd);
593             file.close();
594             file = new util.file('receipt.bat');
595
596             dump('print exec: ' + cmd + '\n');
597             var process = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);
598             process.init(file._file);
599
600             var args = [];
601
602             dump('process.run = ' + process.run(true, args, args.length) + '\n');
603
604             file.close();
605
606         } catch (e) {
607             //alert('Probably not printing: ' + e);
608             this.error.sdump('D_ERROR','_NSPrint_custom_print PRINT EXCEPTION: ' + js2JSON(e) + '\n');
609         }
610     },
611
612     '_NSPrint_webBrowserPrint' : function(w,silent,params) {
613         var obj = this;
614         try {
615             var webBrowserPrint = w
616                 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
617                 .getInterface(Components.interfaces.nsIWebBrowserPrint);
618             this.error.sdump('D_PRINT','webBrowserPrint = ' + webBrowserPrint);
619             if (webBrowserPrint) {
620                 var gPrintSettings = obj.GetPrintSettings();
621                 if (silent) gPrintSettings.printSilent = true;
622                 else gPrintSettings.printSilent = false;
623                 if (params) {
624                     if (params.marginLeft) gPrintSettings.marginLeft = params.marginLeft;
625                 }
626                 webBrowserPrint.print(gPrintSettings, null);
627                 this.error.sdump('D_PRINT','Should be printing\n');
628             } else {
629                 this.error.sdump('D_ERROR','Should not be printing\n');
630             }
631         } catch (e) {
632             //alert('Probably not printing: ' + e);
633             // Pressing cancel is expressed as an NS_ERROR_ABORT return value,
634             // causing an exception to be thrown which we catch here.
635             // Unfortunately this will also consume helpful failures
636             this.error.sdump('D_ERROR','_NSPrint_webBrowserPrint PRINT EXCEPTION: ' + js2JSON(e) + '\n');
637         }
638     },
639
640     'GetPrintSettings' : function() {
641         try {
642             //alert('entering GetPrintSettings');
643             var pref = Components.classes["@mozilla.org/preferences-service;1"]
644                 .getService(Components.interfaces.nsIPrefBranch);
645             //alert('pref = ' + pref);
646             if (pref) {
647                 this.gPrintSettingsAreGlobal = pref.getBoolPref("print.use_global_printsettings", false);
648                 this.gSavePrintSettings = pref.getBoolPref("print.save_print_settings", false);
649                 //alert('gPrintSettingsAreGlobal = ' + this.gPrintSettingsAreGlobal + '  gSavePrintSettings = ' + this.gSavePrintSettings);
650             }
651  
652             var printService = Components.classes["@mozilla.org/gfx/printsettings-service;1"]
653                 .getService(Components.interfaces.nsIPrintSettingsService);
654             if (this.gPrintSettingsAreGlobal) {
655                 this.gPrintSettings = printService.globalPrintSettings;
656                 //alert('called setPrinterDefaultsForSelectedPrinter');
657                 this.setPrinterDefaultsForSelectedPrinter(printService);
658             } else {
659                 this.gPrintSettings = printService.newPrintSettings;
660                 //alert('used printService.newPrintSettings');
661             }
662         } catch (e) {
663             this.error.sdump('D_ERROR',"GetPrintSettings() "+e+"\n");
664             //alert("GetPrintSettings() "+e+"\n");
665         }
666  
667         return this.gPrintSettings;
668     },
669
670     'setPrinterDefaultsForSelectedPrinter' : function (aPrintService) {
671         try {
672             if (this.gPrintSettings.printerName == "") {
673                 this.gPrintSettings.printerName = aPrintService.defaultPrinterName;
674                 //alert('used .defaultPrinterName');
675             }
676             //alert('printerName = ' + this.gPrintSettings.printerName);
677      
678             // First get any defaults from the printer 
679             aPrintService.initPrintSettingsFromPrinter(this.gPrintSettings.printerName, this.gPrintSettings);
680      
681             // now augment them with any values from last time
682             aPrintService.initPrintSettingsFromPrefs(this.gPrintSettings, true, this.gPrintSettings.kInitSaveAll);
683
684             // now augment from our own saved settings if they exist
685             this.load_settings();
686
687         } catch(E) {
688             this.error.sdump('D_ERROR',"setPrinterDefaultsForSelectedPrinter() "+E+"\n");
689         }
690     },
691
692     'page_settings' : function() {
693         try {
694             this.GetPrintSettings();
695             var PO = Components.classes["@mozilla.org/gfx/printsettings-service;1"].getService(Components.interfaces.nsIPrintOptions);
696             PO.ShowPrintSetupDialog(this.gPrintSettings);
697         } catch(E) {
698             this.error.standard_unexpected_error_alert("page_settings()",E);
699         }
700     },
701
702     'load_settings' : function() {
703         try {
704             var error_msg = '';
705             var file = new util.file('gPrintSettings.' + this.context);
706             if (file._file.exists()) {
707                 temp = file.get_object(); file.close();
708                 for (var i in temp) {
709                     try { this.gPrintSettings[i] = temp[i]; } catch(E) { error_msg += 'Error trying to set gPrintSettings.'+i+'='+temp[i]+' : ' + js2JSON(E) + '\n'; }
710                 }
711             }  else if (this.context != 'default') {
712                 var file = new util.file('gPrintSettings.default');
713                 if (file._file.exists()) {
714                     temp = file.get_object(); file.close();
715                     for (var i in temp) {
716                         try { this.gPrintSettings[i] = temp[i]; } catch(E) { error_msg += 'Error trying to set gPrintSettings.'+i+'='+temp[i]+' : ' + js2JSON(E) + '\n'; }
717                     }
718                 } else {
719                     this.gPrintSettings.marginTop = 0;
720                     this.gPrintSettings.marginLeft = 0;
721                     this.gPrintSettings.marginBottom = 0;
722                     this.gPrintSettings.marginRight = 0;
723                     this.gPrintSettings.headerStrLeft = '';
724                     this.gPrintSettings.headerStrCenter = '';
725                     this.gPrintSettings.headerStrRight = '';
726                     this.gPrintSettings.footerStrLeft = '';
727                     this.gPrintSettings.footerStrCenter = '';
728                     this.gPrintSettings.footerStrRight = '';
729                 }
730             }
731             if (error_msg) {
732                 this.error.sdump('D_PRINT',error_msg);
733                 this.error.yns_alert(
734                     document.getElementById('offlineStrings').getString('load_printer_settings_error_description'),
735                     document.getElementById('offlineStrings').getString('load_printer_settings_error_title'),
736                     document.getElementById('offlineStrings').getString('common.ok'),
737                     null,
738                     null,
739                     null
740                 );
741             }
742         } catch(E) {
743             this.error.standard_unexpected_error_alert("load_settings()",E);
744         }
745     },
746
747     'save_settings' : function() {
748         try {
749             var obj = this;
750             var file = new util.file('gPrintSettings.' + this.context);
751             if (typeof obj.gPrintSettings == 'undefined') obj.GetPrintSettings();
752             if (obj.gPrintSettings) file.set_object(obj.gPrintSettings); 
753             file.close();
754             if (this.context == 'default') {
755                 // print.print_printer gets used by bare window.print()'s.  We sometimes use window.print for the
756                 // WebBrowserPrint strategy to workaround bugs with the NSPrint xpcom, and only in the default context.
757                 var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces['nsIPrefBranch']);
758                 prefs.setCharPref('print.print_printer',obj.gPrintSettings.printerName);
759             }
760         } catch(E) {
761             this.error.standard_unexpected_error_alert("save_settings()",E);
762         }
763     }
764 }
765
766 dump('exiting util/print.js\n');