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