c3ff12b1d00c217b86ea75d97e597311e965e653
[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 = 'data:text/html,<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);}">' + window.escape(msg.replace(/<script[^>]*>.*?<\/script>/gi,'')) + '</body></html>';
185                     obj.win.openDialog(print_url,'receipt_temp','chrome,resizable,modal', null, { "data" : params.data, "list" : params.list}, function(w) { 
186                         try {
187                             obj.NSPrint(w, silent, params);
188                         } catch(E) {
189                             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);
190                             w.print();
191                         }
192                         w.close();
193                     });
194                 break;
195                 default:
196                     w = obj.win.open('data:' + content_type + ',' + window.escape(msg),'receipt_temp','chrome,resizable');
197                     w.minimize();
198                     setTimeout(
199                         function() {
200                             try {
201                                 obj.NSPrint(w, silent, params);
202                             } catch(E) {
203                                 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);
204                                 w.print();
205                             }
206                             w.minimize(); w.close();
207                         }, 1000
208                     );
209                 break;
210             }
211
212         } catch(E) {
213             this.error.standard_unexpected_error_alert('util.print.simple',E);
214         }
215     },
216     
217     'tree_list' : function (params) { 
218         try {
219             dump('print.tree_list.params.list = \n' + this.error.pretty_print(js2JSON(params.list)) + '\n');
220             dump('print.tree_list.params.data = \n' + this.error.pretty_print(js2JSON(params.data)) + '\n');
221         } catch(E) {
222             dump(E+'\n');
223         }
224         var cols = [];
225         var s = '';
226         if (params.context) this.set_context(params.context);
227         if (params.header) s += this.template_sub( params.header, cols, params );
228         if (params.list) {
229             // Pre-templating sort
230             // %SORT(field[ AS type][ ASC|DESC][,...])%
231             var sort_blocks = params.line_item.match(/%SORT\([^)]+\)%/g);
232             if(sort_blocks) {
233                 for(var i = 0; i < sort_blocks.length; i++) {
234                     sort_blocks[i] = sort_blocks[i].substring(6,sort_blocks[i].length-2);
235                 }
236                 sort_blocks = sort_blocks.join(',').split(/\s*,\s*/); // Supports %SORT(a,b)% and %SORT(a)% %SORT(b)% methods
237                 for(var i = 0; i < sort_blocks.length; i++) {
238                     sort_blocks[i] = sort_blocks[i].match(/([^ ]+)(?:\s+AS\s+([^ ]+))?(?:\s+(ASC|DESC))?/);
239                     sort_blocks[i].shift(); // Removes the "full match" entry
240                 }
241
242                 function sorter(a, b) {
243                     var return_val = 0;
244                     for(var i = 0; i < sort_blocks.length && return_val == 0; i++) {
245                         var sort = sort_blocks[i];
246                         var a_test = a[sort[0]];
247                         var b_test = b[sort[0]];
248                         sort[1] = sort[1] || '';
249                         sort[2] = sort[2] || 'ASC';
250                         switch(sort[1].toUpperCase()) {
251                             case 'DATE':
252                                 a_test = new Date(a_test);
253                                 b_test = new Date(b_test);
254                                 break;
255                             case 'INT':
256                                 a_test = parseInt(a_test);
257                                 b_test = parseInt(b_test);
258                                 break;
259                             case 'FLOAT':
260                             case 'NUMBER':
261                                 a_test = parseFloat(a_test);
262                                 b_test = parseFloat(b_test);
263                                 break;
264                             case 'LOWER':
265                                 a_test = a_test.toLowerCase();
266                                 b_test = b_test.toLowerCase();
267                                 break;
268                             case 'UPPER':
269                                 a_test = a_test.toUpperCase();
270                                 b_test = b_test.toUpperCase();
271                                 break;
272                         }
273                         if(a_test > b_test) return_val = 1;
274                         if(a_test < b_test) return_val = -1;
275                         if(sort[2] == 'DESC') return_val *= -1;
276                     }
277                     return return_val;
278                 }
279                 params.list.sort(sorter);
280                 params.line_item = params.line_item.replace(/%SORT\([^)]*\)%/g,'');
281             }
282
283             for (var i = 0; i < params.list.length; i++) {
284                 params.row = params.list[i];
285                 params.row_idx = i;
286                 s += this.template_sub( params.line_item, cols, params );
287             }
288         }
289         if (params.footer) s += this.template_sub( params.footer, cols, params );
290
291         // Sanity check, no javascript in templates
292         // Note: [\s\S] is a workaround for . not including newlines.
293         s=s.replace(/<script[^>]*>[\s\S]*?<\/script[^>]*>/gi,'')
294         s=s.replace(/onload\s*=\s*"[^"]*"/gi,'');
295         s=s.replace(/onload\s*=\s*'[^']*'/gi,'');
296
297         if (params.sample_frame) {
298             var jsrc = 'data:text/javascript,' + window.escape('var params = { "data" : ' + js2JSON(params.data) + ', "list" : ' + js2JSON(params.list) + '};');
299             params.sample_frame.setAttribute('src','data:text/html,<html id="top"><head><script src="' + window.escape(jsrc) + '"></script></head><body>' + window.escape(s) + '</body></html>');
300         } else {
301             this.simple(s,params);
302         }
303         if(this.context != this.default_context) this.set_context(this.default_context);
304     },
305
306     'template_sub' : function( msg, cols, params ) {
307         try {
308             var obj = this;
309             if (!msg) { dump('template sub called with empty string\n'); return; }
310             JSAN.use('util.date');
311             var s = msg; var b;
312
313             // Includes
314             // Note that we keep track of already included settings
315             // This ensures that we don't infinite loop through includes
316             try {
317                 var match;
318                 var include_patt=/%INCLUDE\(\s*([^)]*?)\s*\)%/;
319                 var included = {};
320                 while(match = include_patt.exec(s)) {
321                     if(match[1] == '' || included[match[1]]) {
322                         s = s.replace(match[0], '');
323                     } else {
324                         included[match[1]] = true;
325                         s = s.replace(new RegExp("%INCLUDE\\(\\s*" + match[1].replace(/([.?*+^$[\]\\(){}-])/g, "\\$1") + "\\s*\\)%","g"), obj.data.hash.aous['circ.staff_client.receipt.' + match[1]] || '');
326                     }
327                 }
328             } catch(E) { dump(E+'\n'); }
329
330             try{b = s; s = s.replace(/%LINE_NO%/g,Number(params.row_idx)+1);}
331                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
332
333             try{b = s; s = s.replace(/%patron_barcode%/g,this.escape_html(params.patron_barcode));}
334                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
335
336             try{b = s; s = s.replace(/%LIBRARY%/g,this.escape_html(params.lib.name()));}
337                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
338             try{b = s; s = s.replace(/%PINES_CODE%/g,this.escape_html(params.lib.shortname()));}
339                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
340             try{b = s; s = s.replace(/%SHORTNAME%/g,this.escape_html(params.lib.shortname()));}
341                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
342             try{b = s; s = s.replace(/%STAFF_FIRSTNAME%/g,this.escape_html(params.staff.first_given_name()));}
343                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
344             try{b = s; s = s.replace(/%STAFF_LASTNAME%/g,this.escape_html(params.staff.family_name()));}
345                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
346             try{b = s; s = s.replace(/%STAFF_BARCODE%/g,this.escape_html(params.staff.barcode)); }
347                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
348             try{b = s; s = s.replace(/%STAFF_PROFILE%/g,this.escape_html(obj.data.hash.pgt[ params.staff.profile() ].name() )); }
349                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
350             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()));}
351                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
352             try{b = s; s = s.replace(/%PATRON_ALIAS%/g,this.escape_html((params.patron.alias() == '' || params.patron.alias() == null) ? '' : params.patron.alias()));}
353                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
354             try{b = s; s = s.replace(/%PATRON_FIRSTNAME%/g,this.escape_html(params.patron.first_given_name()));}
355                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
356             try{b = s; s = s.replace(/%PATRON_LASTNAME%/g,this.escape_html(params.patron.family_name()));}
357                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
358             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() )) ;}
359                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
360
361             try{b = s; s=s.replace(/%TODAY%/g,(new Date()));}
362                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
363             try{b = s; s=s.replace(/%TODAY_m%/g,(util.date.formatted_date(new Date(),'%m')));}
364                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
365             try{b = s; s=s.replace(/%TODAY_TRIM%/g,(util.date.formatted_date(new Date(),'')));}
366                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
367             try{b = s; s=s.replace(/%TODAY_d%/g,(util.date.formatted_date(new Date(),'%d')));}
368                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
369             try{b = s; s=s.replace(/%TODAY_Y%/g,(util.date.formatted_date(new Date(),'%Y')));}
370                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
371             try{b = s; s=s.replace(/%TODAY_H%/g,(util.date.formatted_date(new Date(),'%H')));}
372                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
373             try{b = s; s=s.replace(/%TODAY_I%/g,(util.date.formatted_date(new Date(),'%I')));}
374                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
375             try{b = s; s=s.replace(/%TODAY_M%/g,(util.date.formatted_date(new Date(),'%M')));}
376                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
377             try{b = s; s=s.replace(/%TODAY_D%/g,(util.date.formatted_date(new Date(),'%D')));}
378                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
379             try{b = s; s=s.replace(/%TODAY_F%/g,(util.date.formatted_date(new Date(),'%F')));}
380                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
381
382             try {
383                 if (typeof params.row != 'undefined') {
384                     if (params.row.length >= 0) {
385                         alert('debug - please tell the developers that deprecated template code tried to execute');
386                         for (var i = 0; i < cols.length; i++) {
387                             var re = new RegExp(cols[i],"g");
388                             try{b = s; s=s.replace(re, this.escape_html(params.row[i]));}
389                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 1 string = <' + s + '>',E);}
390                         }
391                     } else { 
392                         /* for dump_with_keys */
393                         for (var i in params.row) {
394                             var re = new RegExp('%'+i+'%',"g");
395                             try{b = s; s=s.replace(re, this.escape_html(params.row[i].toString()));}
396                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 2 string = <' + s + '>',E);}
397                         }
398                     }
399                 }
400
401                 if (typeof params.data != 'undefined') {
402                     for (var i in params.data) {
403                         var re = new RegExp('%'+i+'%',"g");
404                         if (typeof params.data[i] == 'string' || typeof params.data[i] == 'number') {
405                             try{b = s; s=s.replace(re, this.escape_html(params.data[i]));}
406                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 3 string = <' + s + '>',E);}
407                         } else {
408                             /* likely a null, print as an empty string */
409                             try{b = s; s=s.replace(re, '');}
410                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 3 string = <' + s + '>',E);}
411                         }
412                     }
413                 }
414             } catch(E) { dump(E+'\n'); }
415
416             // Date Format
417             try {
418                 var match;
419                 var date_format_patt=/%DATE_FORMAT\(\s*([^,]*?)\s*,\s*([^)]*?)\s*\)%/;
420                 while(match = date_format_patt.exec(s)) {
421                     if(match[1] == '' || match[2] == '')
422                         s = s.replace(match[0], '');
423                     else
424                         s = s.replace(match[0], util.date.formatted_date(match[1], match[2]));
425                 }
426             } catch(E) { dump(E+'\n'); }
427
428             // Substrings
429             try {
430                 var match;
431                 // Pre-trim inside of substrings, and only inside of them
432                 // This keeps the trim commands from being truncated
433                 var substr_trim_patt=/(%SUBSTR\(-?\d+,?\s*(-?\d+)?\)%.*?)(\s*%-TRIM%|%TRIM-%\s*)(.*?%SUBSTR_END%)/;
434                 while(match = substr_trim_patt.exec(s))
435                     s = s.replace(match[0], match[1] + match[4]);
436                 // Then do the substrings themselves
437                 var substr_patt=/%SUBSTR\((-?\d+),?\s*(-?\d+)?\)%(.*?)%SUBSTR_END%/;
438                 while(match = substr_patt.exec(s)) {
439                     var substring_start = parseInt(match[1]);
440                     if(substring_start < 0) substring_start = match[3].length + substring_start;
441                     var substring_length = parseInt(match[2]);
442                     if(substring_length > 0)
443                         s = s.replace(match[0], match[3].substring(substring_start, substring_start + substring_length));
444                     else if(substring_length < 0)
445                         s = s.replace(match[0], match[3].substring(substring_start + substring_length, substring_start));
446                     else
447                         s = s.replace(match[0], match[3].substring(substring_start));
448                 }
449             } catch(E) { dump(E+'\n'); }
450
451             // Cleanup unwanted whitespace
452             try {
453                 s = s.replace(/%TRIM-%\s*/g,'');
454                 s = s.replace(/\s*%-TRIM%/g,'');
455             } catch(E) { dump(E+'\n'); }
456
457             return s;
458         } catch(E) {
459             alert('Error in print.js, template_sub(): ' + E);
460         }
461     },
462
463
464     'NSPrint' : function(w,silent,params) {
465         if (!w) w = window;
466         var obj = this;
467         try {
468             if (!params) params = {};
469
470             obj.data.init({'via':'stash'});
471
472             if (params.print_strategy || obj.data.print_strategy[obj.context] || obj.data.print_strategy['default']) {
473
474                 dump('params.print_strategy = ' + params.print_strategy
475                     + ' || obj.data.print_strategy[' + obj.context + '] = ' + obj.data.print_strategy[obj.context] 
476                     + ' || obj.data.print_strategy[default] = ' + obj.data.print_strategy['default'] 
477                     + ' => ' + ( params.print_strategy || obj.data.print_strategy[obj.context] || obj.data.print_strategy['default'] ) + '\n');
478                 switch(params.print_strategy || obj.data.print_strategy[obj.context] || obj.data.print_strategy['default']) {
479                     case 'dos.print':
480                         params.dos_print = true;
481                     case 'custom.print':
482                         if (typeof w != 'string') {
483                             try {
484                                 var temp_w = params.msg || w.document.firstChild.innerHTML;
485                                 if (!params.msg) { params.msg = temp_w; }
486                                 if (typeof temp_w != 'string') { throw(temp_w); }
487                                 w = obj.html2txt(temp_w);
488                             } catch(E) {
489                                 dump('util.print: Could not use w.document.firstChild.innerHTML with ' + w + ': ' + E + '\n');
490                                 w.getSelection().selectAllChildren(w.document.firstChild);
491                                 w = w.getSelection().toString();
492                             }
493                         }
494                         obj._NSPrint_custom_print(w,silent,params);
495                     break;    
496                     case 'window.print':
497                         var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces['nsIPrefBranch']);
498                         var originalPrinter = false;
499                         if (prefs.prefHasUserValue('print.print_printer')) {
500                             // This is for restoring print.print_printer after any print dialog, so that when
501                             // window.print gets used again, it uses the configured printer for the right context
502                             // (which should only be default--window.print is a kludge and is in limited use),
503                             // rather than the printer last used.
504                             originalPrinter = prefs.getCharPref('print.print_printer');
505                         }
506                         if (typeof w == 'object') {
507                             w.print();
508                             if (originalPrinter) {
509                                 prefs.setCharPref('print.print_printer',originalPrinter);
510                             }
511                         } else {
512                             if (params.content_type == 'text/plain') {
513                                 w = window.open('data:text/plain,'+escape(params.msg));
514                             } else {
515                                 w = window.open('data:text/html,'+escape(params.msg));
516                             }
517                             setTimeout(
518                                 function() {
519                                     w.print();
520                                     if (originalPrinter) {
521                                         prefs.setCharPref('print.print_printer',originalPrinter);
522                                     }
523                                     setTimeout(
524                                         function() {
525                                             w.close(); 
526                                         }, 2000
527                                     );
528                                 }, 0
529                             );
530                         }
531                     break;    
532                     case 'webBrowserPrint':
533                     default:
534                         if (typeof w == 'object') {
535                             obj._NSPrint_webBrowserPrint(w,silent,params);
536                         } else {
537                             if (params.content_type == 'text/plain') {
538                                 w = window.open('data:text/plain,'+escape(params.msg));
539                             } else {
540                                 w = window.open('data:text/html,'+escape(params.msg));
541                             }
542                             setTimeout(
543                                 function() {
544                                     obj._NSPrint_webBrowserPrint(w,silent,params);
545                                     setTimeout(
546                                         function() {
547                                             w.close(); 
548                                         }, 2000
549                                     );
550                                 }, 0
551                             );
552                         }
553                     break;    
554                 }
555
556             } else {
557                 //w.print();
558                 obj._NSPrint_webBrowserPrint(w,silent,params);
559             }
560
561         } catch (e) {
562             alert('Probably not printing: ' + e);
563             this.error.sdump('D_ERROR','PRINT EXCEPTION: ' + js2JSON(e) + '\n');
564         }
565
566     },
567
568     '_NSPrint_custom_print' : function(w,silent,params) {
569         var obj = this;
570         try {
571
572             var text = w;
573             var html = params.msg || w;
574
575             var txt_file = new util.file('receipt.txt');
576             txt_file.write_content('truncate',text); 
577             var text_path = '"' + txt_file._file.path + '"';
578             txt_file.close();
579
580             var html_file = new util.file('receipt.html');
581             html_file.write_content('truncate',html); 
582             var html_path = '"' + html_file._file.path + '"';
583             html_file.close();
584             
585             var cmd = params.dos_print ?
586                 'copy ' + text_path + ' lpt1 /b\n'
587                 : obj.oils_printer_external_cmd.replace('%receipt.txt%',text_path).replace('%receipt.html%',html_path)
588             ;
589
590             file = new util.file('receipt.bat');
591             file.write_content('truncate+exec',cmd);
592             file.close();
593             file = new util.file('receipt.bat');
594
595             dump('print exec: ' + cmd + '\n');
596             var process = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);
597             process.init(file._file);
598
599             var args = [];
600
601             dump('process.run = ' + process.run(true, args, args.length) + '\n');
602
603             file.close();
604
605         } catch (e) {
606             //alert('Probably not printing: ' + e);
607             this.error.sdump('D_ERROR','_NSPrint_custom_print PRINT EXCEPTION: ' + js2JSON(e) + '\n');
608         }
609     },
610
611     '_NSPrint_webBrowserPrint' : function(w,silent,params) {
612         var obj = this;
613         try {
614             var webBrowserPrint = w
615                 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
616                 .getInterface(Components.interfaces.nsIWebBrowserPrint);
617             this.error.sdump('D_PRINT','webBrowserPrint = ' + webBrowserPrint);
618             if (webBrowserPrint) {
619                 var gPrintSettings = obj.GetPrintSettings();
620                 if (silent) gPrintSettings.printSilent = true;
621                 else gPrintSettings.printSilent = false;
622                 if (params) {
623                     if (params.marginLeft) gPrintSettings.marginLeft = params.marginLeft;
624                 }
625                 webBrowserPrint.print(gPrintSettings, null);
626                 this.error.sdump('D_PRINT','Should be printing\n');
627             } else {
628                 this.error.sdump('D_ERROR','Should not be printing\n');
629             }
630         } catch (e) {
631             //alert('Probably not printing: ' + e);
632             // Pressing cancel is expressed as an NS_ERROR_ABORT return value,
633             // causing an exception to be thrown which we catch here.
634             // Unfortunately this will also consume helpful failures
635             this.error.sdump('D_ERROR','_NSPrint_webBrowserPrint PRINT EXCEPTION: ' + js2JSON(e) + '\n');
636         }
637     },
638
639     'GetPrintSettings' : function() {
640         try {
641             //alert('entering GetPrintSettings');
642             var pref = Components.classes["@mozilla.org/preferences-service;1"]
643                 .getService(Components.interfaces.nsIPrefBranch);
644             //alert('pref = ' + pref);
645             if (pref) {
646                 this.gPrintSettingsAreGlobal = pref.getBoolPref("print.use_global_printsettings", false);
647                 this.gSavePrintSettings = pref.getBoolPref("print.save_print_settings", false);
648                 //alert('gPrintSettingsAreGlobal = ' + this.gPrintSettingsAreGlobal + '  gSavePrintSettings = ' + this.gSavePrintSettings);
649             }
650  
651             var printService = Components.classes["@mozilla.org/gfx/printsettings-service;1"]
652                 .getService(Components.interfaces.nsIPrintSettingsService);
653             if (this.gPrintSettingsAreGlobal) {
654                 this.gPrintSettings = printService.globalPrintSettings;
655                 //alert('called setPrinterDefaultsForSelectedPrinter');
656                 this.setPrinterDefaultsForSelectedPrinter(printService);
657             } else {
658                 this.gPrintSettings = printService.newPrintSettings;
659                 //alert('used printService.newPrintSettings');
660             }
661         } catch (e) {
662             this.error.sdump('D_ERROR',"GetPrintSettings() "+e+"\n");
663             //alert("GetPrintSettings() "+e+"\n");
664         }
665  
666         return this.gPrintSettings;
667     },
668
669     'setPrinterDefaultsForSelectedPrinter' : function (aPrintService) {
670         try {
671             if (this.gPrintSettings.printerName == "") {
672                 this.gPrintSettings.printerName = aPrintService.defaultPrinterName;
673                 //alert('used .defaultPrinterName');
674             }
675             //alert('printerName = ' + this.gPrintSettings.printerName);
676      
677             // First get any defaults from the printer 
678             aPrintService.initPrintSettingsFromPrinter(this.gPrintSettings.printerName, this.gPrintSettings);
679      
680             // now augment them with any values from last time
681             aPrintService.initPrintSettingsFromPrefs(this.gPrintSettings, true, this.gPrintSettings.kInitSaveAll);
682
683             // now augment from our own saved settings if they exist
684             this.load_settings();
685
686         } catch(E) {
687             this.error.sdump('D_ERROR',"setPrinterDefaultsForSelectedPrinter() "+E+"\n");
688         }
689     },
690
691     'page_settings' : function() {
692         try {
693             this.GetPrintSettings();
694             var PO = Components.classes["@mozilla.org/gfx/printsettings-service;1"].getService(Components.interfaces.nsIPrintOptions);
695             PO.ShowPrintSetupDialog(this.gPrintSettings);
696         } catch(E) {
697             this.error.standard_unexpected_error_alert("page_settings()",E);
698         }
699     },
700
701     'load_settings' : function() {
702         try {
703             var error_msg = '';
704             var file = new util.file('gPrintSettings.' + this.context);
705             if (file._file.exists()) {
706                 temp = file.get_object(); file.close();
707                 for (var i in temp) {
708                     try { this.gPrintSettings[i] = temp[i]; } catch(E) { error_msg += 'Error trying to set gPrintSettings.'+i+'='+temp[i]+' : ' + js2JSON(E) + '\n'; }
709                 }
710             }  else if (this.context != 'default') {
711                 var file = new util.file('gPrintSettings.default');
712                 if (file._file.exists()) {
713                     temp = file.get_object(); file.close();
714                     for (var i in temp) {
715                         try { this.gPrintSettings[i] = temp[i]; } catch(E) { error_msg += 'Error trying to set gPrintSettings.'+i+'='+temp[i]+' : ' + js2JSON(E) + '\n'; }
716                     }
717                 } else {
718                     this.gPrintSettings.marginTop = 0;
719                     this.gPrintSettings.marginLeft = 0;
720                     this.gPrintSettings.marginBottom = 0;
721                     this.gPrintSettings.marginRight = 0;
722                     this.gPrintSettings.headerStrLeft = '';
723                     this.gPrintSettings.headerStrCenter = '';
724                     this.gPrintSettings.headerStrRight = '';
725                     this.gPrintSettings.footerStrLeft = '';
726                     this.gPrintSettings.footerStrCenter = '';
727                     this.gPrintSettings.footerStrRight = '';
728                 }
729             }
730             if (error_msg) {
731                 this.error.sdump('D_PRINT',error_msg);
732                 this.error.yns_alert(
733                     document.getElementById('offlineStrings').getString('load_printer_settings_error_description'),
734                     document.getElementById('offlineStrings').getString('load_printer_settings_error_title'),
735                     document.getElementById('offlineStrings').getString('common.ok'),
736                     null,
737                     null,
738                     null
739                 );
740             }
741         } catch(E) {
742             this.error.standard_unexpected_error_alert("load_settings()",E);
743         }
744     },
745
746     'save_settings' : function() {
747         try {
748             var obj = this;
749             var file = new util.file('gPrintSettings.' + this.context);
750             if (typeof obj.gPrintSettings == 'undefined') obj.GetPrintSettings();
751             if (obj.gPrintSettings) file.set_object(obj.gPrintSettings); 
752             file.close();
753             if (this.context == 'default') {
754                 // print.print_printer gets used by bare window.print()'s.  We sometimes use window.print for the
755                 // WebBrowserPrint strategy to workaround bugs with the NSPrint xpcom, and only in the default context.
756                 var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces['nsIPrefBranch']);
757                 prefs.setCharPref('print.print_printer',obj.gPrintSettings.printerName);
758             }
759         } catch(E) {
760             this.error.standard_unexpected_error_alert("save_settings()",E);
761         }
762     }
763 }
764
765 dump('exiting util/print.js\n');