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