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