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