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