]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/xul/staff_client/chrome/content/util/print.js
Merged esi/template-toolkit-opac and repaired some merge conflicts
[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             for (var i = 0; i < params.list.length; i++) {
207                 params.row = params.list[i];
208                 params.row_idx = i;
209                 s += this.template_sub( params.line_item, cols, params );
210             }
211         }
212         if (params.footer) s += this.template_sub( params.footer, cols, params );
213
214         if (params.sample_frame) {
215             var jsrc = 'data:text/javascript,' + window.escape('var params = { "data" : ' + js2JSON(params.data) + ', "list" : ' + js2JSON(params.list) + '};');
216             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>');
217         } else {
218             this.simple(s,params);
219         }
220     },
221
222     'template_sub' : function( msg, cols, params ) {
223         try {
224             var obj = this;
225             if (!msg) { dump('template sub called with empty string\n'); return; }
226             JSAN.use('util.date');
227             var s = msg; var b;
228
229             try{b = s; s = s.replace(/%LINE_NO%/g,Number(params.row_idx)+1);}
230                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
231
232             try{b = s; s = s.replace(/%patron_barcode%/g,this.escape_html(params.patron_barcode));}
233                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
234
235             try{b = s; s = s.replace(/%LIBRARY%/g,this.escape_html(params.lib.name()));}
236                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
237             try{b = s; s = s.replace(/%PINES_CODE%/g,this.escape_html(params.lib.shortname()));}
238                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
239             try{b = s; s = s.replace(/%SHORTNAME%/g,this.escape_html(params.lib.shortname()));}
240                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
241             try{b = s; s = s.replace(/%STAFF_FIRSTNAME%/g,this.escape_html(params.staff.first_given_name()));}
242                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
243             try{b = s; s = s.replace(/%STAFF_LASTNAME%/g,this.escape_html(params.staff.family_name()));}
244                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
245             try{b = s; s = s.replace(/%STAFF_BARCODE%/g,this.escape_html(params.staff.barcode)); }
246                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
247             try{b = s; s = s.replace(/%STAFF_PROFILE%/g,this.escape_html(obj.data.hash.pgt[ params.staff.profile() ].name() )); }
248                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
249             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()));}
250                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
251             try{b = s; s = s.replace(/%PATRON_ALIAS%/g,this.escape_html((params.patron.alias() == '' || params.patron.alias() == null) ? '' : params.patron.alias()));}
252                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
253             try{b = s; s = s.replace(/%PATRON_FIRSTNAME%/g,this.escape_html(params.patron.first_given_name()));}
254                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
255             try{b = s; s = s.replace(/%PATRON_LASTNAME%/g,this.escape_html(params.patron.family_name()));}
256                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
257             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() )) ;}
258                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
259
260             try{b = s; s=s.replace(/%TODAY%/g,(new Date()));}
261                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
262             try{b = s; s=s.replace(/%TODAY_m%/g,(util.date.formatted_date(new Date(),'%m')));}
263                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
264             try{b = s; s=s.replace(/%TODAY_TRIM%/g,(util.date.formatted_date(new Date(),'')));}
265                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
266             try{b = s; s=s.replace(/%TODAY_d%/g,(util.date.formatted_date(new Date(),'%d')));}
267                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
268             try{b = s; s=s.replace(/%TODAY_Y%/g,(util.date.formatted_date(new Date(),'%Y')));}
269                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
270             try{b = s; s=s.replace(/%TODAY_H%/g,(util.date.formatted_date(new Date(),'%H')));}
271                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
272             try{b = s; s=s.replace(/%TODAY_I%/g,(util.date.formatted_date(new Date(),'%I')));}
273                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
274             try{b = s; s=s.replace(/%TODAY_M%/g,(util.date.formatted_date(new Date(),'%M')));}
275                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
276             try{b = s; s=s.replace(/%TODAY_D%/g,(util.date.formatted_date(new Date(),'%D')));}
277                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
278             try{b = s; s=s.replace(/%TODAY_F%/g,(util.date.formatted_date(new Date(),'%F')));}
279                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
280
281             try {
282                 if (typeof params.row != 'undefined') {
283                     if (params.row.length >= 0) {
284                         alert('debug - please tell the developers that deprecated template code tried to execute');
285                         for (var i = 0; i < cols.length; i++) {
286                             var re = new RegExp(cols[i],"g");
287                             try{b = s; s=s.replace(re, this.escape_html(params.row[i]));}
288                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 1 string = <' + s + '>',E);}
289                         }
290                     } else { 
291                         /* for dump_with_keys */
292                         for (var i in params.row) {
293                             var re = new RegExp('%'+i+'%',"g");
294                             try{b = s; s=s.replace(re, this.escape_html(params.row[i]));}
295                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 2 string = <' + s + '>',E);}
296                         }
297                     }
298                 }
299
300                 if (typeof params.data != 'undefined') {
301                     for (var i in params.data) {
302                         var re = new RegExp('%'+i+'%',"g");
303                         if (typeof params.data[i] == 'string' || typeof params.data[i] == 'number') {
304                             try{b = s; s=s.replace(re, (typeof params.data[i] == 'string' ? this.escape_html(params.data[i]) : params.data[i]));}
305                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 3 string = <' + s + '>',E);}
306                         } else {
307                             /* likely a null, print as an empty string */
308                             try{b = s; s=s.replace(re, '');}
309                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 3 string = <' + s + '>',E);}
310                         }
311                     }
312                 }
313             } catch(E) { dump(E+'\n'); }
314
315             // Date Format
316             try {
317                 var match;
318                 var date_format_patt=/%DATE_FORMAT\(\s*([^,]*?)\s*,\s*([^)]*?)\s*\)%/
319                 while(match = date_format_patt.exec(s)) {
320                     if(match[1] == '' || match[2] == '')
321                         s = s.replace(match[0], '');
322                     else
323                         s = s.replace(match[0], util.date.formatted_date(match[1], match[2]));
324                 }
325             } catch(E) { dump(E+'\n'); }
326
327             // Substrings
328             try {
329                 var match;
330                 // Pre-trim inside of substrings, and only inside of them
331                 // This keeps the trim commands from being truncated
332                 var substr_trim_patt=/(%SUBSTR\(-?\d+,?\s*(-?\d+)?\)%.*?)(\s*%-TRIM%|%TRIM-%\s*)(.*?%SUBSTR_END%)/;
333                 while(match = substr_trim_patt.exec(s))
334                     s = s.replace(match[0], match[1] + match[4]);
335                 // Then do the substrings themselves
336                 var substr_patt=/%SUBSTR\((-?\d+),?\s*(-?\d+)?\)%(.*?)%SUBSTR_END%/;
337                 while(match = substr_patt.exec(s)) {
338                     var substring_start = parseInt(match[1]);
339                     if(substring_start < 0) substring_start = match[3].length + substring_start;
340                     var substring_length = parseInt(match[2]);
341                     if(substring_length > 0)
342                         s = s.replace(match[0], match[3].substring(substring_start, substring_start + substring_length));
343                     else if(substring_length < 0)
344                         s = s.replace(match[0], match[3].substring(substring_start + substring_length, substring_start));
345                     else
346                         s = s.replace(match[0], match[3].substring(substring_start));
347                 }
348             } catch(E) { dump(E+'\n'); }
349
350             // Cleanup unwanted whitespace
351             try {
352                 s = s.replace(/%TRIM-%\s*/g,'');
353                 s = s.replace(/\s*%-TRIM%/g,'');
354             } catch(E) { dump(E+'\n'); }
355
356             return s;
357         } catch(E) {
358             alert('Error in print.js, template_sub(): ' + E);
359         }
360     },
361
362
363     'NSPrint' : function(w,silent,params) {
364         if (!w) w = window;
365         var obj = this;
366         try {
367             if (!params) params = {};
368
369             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
370             obj.data.init({'via':'stash'});
371
372             if (params.print_strategy || obj.data.print_strategy[obj.context] || obj.data.print_strategy['default']) {
373
374                 dump('params.print_strategy = ' + params.print_strategy
375                     + ' || obj.data.print_strategy[' + obj.context + '] = ' + obj.data.print_strategy[obj.context] 
376                     + ' || obj.data.print_strategy[default] = ' + obj.data.print_strategy['default'] 
377                     + ' => ' + ( params.print_strategy || obj.data.print_strategy[obj.context] || obj.data.print_strategy['default'] ) + '\n');
378                 switch(params.print_strategy || obj.data.print_strategy[obj.context] || obj.data.print_strategy['default']) {
379                     case 'dos.print':
380                     case 'custom.print':
381                         if (typeof w != 'string') {
382                             try {
383                                 var temp_w = params.msg || w.document.firstChild.innerHTML;
384                                 if (!params.msg) { params.msg = temp_w; }
385                                 if (typeof temp_w != 'string') { throw(temp_w); }
386                                 w = obj.html2txt(temp_w);
387                             } catch(E) {
388                                 dump('util.print: Could not use w.document.firstChild.innerHTML with ' + w + ': ' + E + '\n');
389                                 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
390                                 w.getSelection().selectAllChildren(w.document.firstChild);
391                                 w = w.getSelection().toString();
392                             }
393                         }
394                         obj._NSPrint_custom_print(w,silent,params);
395                     break;    
396                     case 'window.print':
397                         netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
398                         var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces['nsIPrefBranch']);
399                         var originalPrinter = false;
400                         if (prefs.prefHasUserValue('print.print_printer')) {
401                             // This is for restoring print.print_printer after any print dialog, so that when
402                             // window.print gets used again, it uses the configured printer for the right context
403                             // (which should only be default--window.print is a kludge and is in limited use),
404                             // rather than the printer last used.
405                             originalPrinter = prefs.getCharPref('print.print_printer');
406                         }
407                         if (typeof w == 'object') {
408                             w.print();
409                             if (originalPrinter) {
410                                 prefs.setCharPref('print.print_printer',originalPrinter);
411                             }
412                         } else {
413                             if (params.content_type == 'text/plain') {
414                                 w = window.open('data:text/plain,'+escape(params.msg));
415                             } else {
416                                 w = window.open('data:text/html,'+escape(params.msg));
417                             }
418                             setTimeout(
419                                 function() {
420                                     w.print();
421                                     if (originalPrinter) {
422                                         prefs.setCharPref('print.print_printer',originalPrinter);
423                                     }
424                                     setTimeout(
425                                         function() {
426                                             w.close(); 
427                                         }, 2000
428                                     );
429                                 }, 0
430                             );
431                         }
432                     break;    
433                     case 'webBrowserPrint':
434                     default:
435                         if (typeof w == 'object') {
436                             obj._NSPrint_webBrowserPrint(w,silent,params);
437                         } else {
438                             if (params.content_type == 'text/plain') {
439                                 w = window.open('data:text/plain,'+escape(params.msg));
440                             } else {
441                                 w = window.open('data:text/html,'+escape(params.msg));
442                             }
443                             setTimeout(
444                                 function() {
445                                     obj._NSPrint_webBrowserPrint(w,silent,params);
446                                     setTimeout(
447                                         function() {
448                                             w.close(); 
449                                         }, 2000
450                                     );
451                                 }, 0
452                             );
453                         }
454                     break;    
455                 }
456
457             } else {
458                 //w.print();
459                 obj._NSPrint_webBrowserPrint(w,silent,params);
460             }
461
462         } catch (e) {
463             alert('Probably not printing: ' + e);
464             this.error.sdump('D_ERROR','PRINT EXCEPTION: ' + js2JSON(e) + '\n');
465         }
466
467     },
468
469     '_NSPrint_custom_print' : function(w,silent,params) {
470         var obj = this;
471         try {
472
473             var text = w;
474             var html = params.msg || w;
475
476             var txt_file = new util.file('receipt.txt');
477             txt_file.write_content('truncate',text); 
478             var text_path = '"' + txt_file._file.path + '"';
479             txt_file.close();
480
481             var html_file = new util.file('receipt.html');
482             html_file.write_content('truncate',html); 
483             var html_path = '"' + html_file._file.path + '"';
484             html_file.close();
485             
486             var cmd = params.dos_print ?
487                 'copy ' + text_path + ' lpt1 /b\n'
488                 : obj.oils_printer_external_cmd.replace('%receipt.txt%',text_path).replace('%receipt.html%',html_path)
489             ;
490
491             file = new util.file('receipt.bat');
492             file.write_content('truncate+exec',cmd);
493             file.close();
494             file = new util.file('receipt.bat');
495
496             dump('print exec: ' + cmd + '\n');
497             var process = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);
498             process.init(file._file);
499
500             var args = [];
501
502             dump('process.run = ' + process.run(true, args, args.length) + '\n');
503
504             file.close();
505
506         } catch (e) {
507             //alert('Probably not printing: ' + e);
508             this.error.sdump('D_ERROR','_NSPrint_custom_print PRINT EXCEPTION: ' + js2JSON(e) + '\n');
509         }
510     },
511
512     '_NSPrint_webBrowserPrint' : function(w,silent,params) {
513         var obj = this;
514         try {
515             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
516             var webBrowserPrint = w
517                 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
518                 .getInterface(Components.interfaces.nsIWebBrowserPrint);
519             this.error.sdump('D_PRINT','webBrowserPrint = ' + webBrowserPrint);
520             if (webBrowserPrint) {
521                 var gPrintSettings = obj.GetPrintSettings();
522                 if (silent) gPrintSettings.printSilent = true;
523                 else gPrintSettings.printSilent = false;
524                 if (params) {
525                     if (params.marginLeft) gPrintSettings.marginLeft = params.marginLeft;
526                 }
527                 webBrowserPrint.print(gPrintSettings, null);
528                 this.error.sdump('D_PRINT','Should be printing\n');
529             } else {
530                 this.error.sdump('D_ERROR','Should not be printing\n');
531             }
532         } catch (e) {
533             //alert('Probably not printing: ' + e);
534             // Pressing cancel is expressed as an NS_ERROR_ABORT return value,
535             // causing an exception to be thrown which we catch here.
536             // Unfortunately this will also consume helpful failures
537             this.error.sdump('D_ERROR','_NSPrint_webBrowserPrint PRINT EXCEPTION: ' + js2JSON(e) + '\n');
538         }
539     },
540
541     'GetPrintSettings' : function() {
542         try {
543             //alert('entering GetPrintSettings');
544             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
545             var pref = Components.classes["@mozilla.org/preferences-service;1"]
546                 .getService(Components.interfaces.nsIPrefBranch);
547             //alert('pref = ' + pref);
548             if (pref) {
549                 this.gPrintSettingsAreGlobal = pref.getBoolPref("print.use_global_printsettings", false);
550                 this.gSavePrintSettings = pref.getBoolPref("print.save_print_settings", false);
551                 //alert('gPrintSettingsAreGlobal = ' + this.gPrintSettingsAreGlobal + '  gSavePrintSettings = ' + this.gSavePrintSettings);
552             }
553  
554             var printService = Components.classes["@mozilla.org/gfx/printsettings-service;1"]
555                 .getService(Components.interfaces.nsIPrintSettingsService);
556             if (this.gPrintSettingsAreGlobal) {
557                 this.gPrintSettings = printService.globalPrintSettings;
558                 //alert('called setPrinterDefaultsForSelectedPrinter');
559                 this.setPrinterDefaultsForSelectedPrinter(printService);
560             } else {
561                 this.gPrintSettings = printService.newPrintSettings;
562                 //alert('used printService.newPrintSettings');
563             }
564         } catch (e) {
565             this.error.sdump('D_ERROR',"GetPrintSettings() "+e+"\n");
566             //alert("GetPrintSettings() "+e+"\n");
567         }
568  
569         return this.gPrintSettings;
570     },
571
572     'setPrinterDefaultsForSelectedPrinter' : function (aPrintService) {
573         try {
574             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
575             if (this.gPrintSettings.printerName == "") {
576                 this.gPrintSettings.printerName = aPrintService.defaultPrinterName;
577                 //alert('used .defaultPrinterName');
578             }
579             //alert('printerName = ' + this.gPrintSettings.printerName);
580      
581             // First get any defaults from the printer 
582             aPrintService.initPrintSettingsFromPrinter(this.gPrintSettings.printerName, this.gPrintSettings);
583      
584             // now augment them with any values from last time
585             aPrintService.initPrintSettingsFromPrefs(this.gPrintSettings, true, this.gPrintSettings.kInitSaveAll);
586
587             // now augment from our own saved settings if they exist
588             this.load_settings();
589
590         } catch(E) {
591             this.error.sdump('D_ERROR',"setPrinterDefaultsForSelectedPrinter() "+E+"\n");
592         }
593     },
594
595     'page_settings' : function() {
596         try {
597             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
598             this.GetPrintSettings();
599             var PO = Components.classes["@mozilla.org/gfx/printsettings-service;1"].getService(Components.interfaces.nsIPrintOptions);
600             PO.ShowPrintSetupDialog(this.gPrintSettings);
601         } catch(E) {
602             this.error.standard_unexpected_error_alert("page_settings()",E);
603         }
604     },
605
606     'load_settings' : function() {
607         try {
608             var error_msg = '';
609             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
610             var file = new util.file('gPrintSettings.' + this.context);
611             if (file._file.exists()) {
612                 temp = file.get_object(); file.close();
613                 for (var i in temp) {
614                     try { this.gPrintSettings[i] = temp[i]; } catch(E) { error_msg += 'Error trying to set gPrintSettings.'+i+'='+temp[i]+' : ' + js2JSON(E) + '\n'; }
615                 }
616             }  else if (this.context != 'default') {
617                 var file = new util.file('gPrintSettings.default');
618                 if (file._file.exists()) {
619                     temp = file.get_object(); file.close();
620                     for (var i in temp) {
621                         try { this.gPrintSettings[i] = temp[i]; } catch(E) { error_msg += 'Error trying to set gPrintSettings.'+i+'='+temp[i]+' : ' + js2JSON(E) + '\n'; }
622                     }
623                 } else {
624                     this.gPrintSettings.marginTop = 0;
625                     this.gPrintSettings.marginLeft = 0;
626                     this.gPrintSettings.marginBottom = 0;
627                     this.gPrintSettings.marginRight = 0;
628                     this.gPrintSettings.headerStrLeft = '';
629                     this.gPrintSettings.headerStrCenter = '';
630                     this.gPrintSettings.headerStrRight = '';
631                     this.gPrintSettings.footerStrLeft = '';
632                     this.gPrintSettings.footerStrCenter = '';
633                     this.gPrintSettings.footerStrRight = '';
634                 }
635             }
636             if (error_msg) {
637                 this.error.sdump('D_PRINT',error_msg);
638                 this.error.yns_alert(
639                     document.getElementById('offlineStrings').getString('load_printer_settings_error_description'),
640                     document.getElementById('offlineStrings').getString('load_printer_settings_error_title'),
641                     document.getElementById('offlineStrings').getString('common.ok'),
642                     null,
643                     null,
644                     null
645                 );
646             }
647         } catch(E) {
648             this.error.standard_unexpected_error_alert("load_settings()",E);
649         }
650     },
651
652     'save_settings' : function() {
653         try {
654             var obj = this;
655             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
656             var file = new util.file('gPrintSettings.' + this.context);
657             if (typeof obj.gPrintSettings == 'undefined') obj.GetPrintSettings();
658             if (obj.gPrintSettings) file.set_object(obj.gPrintSettings); 
659             file.close();
660             if (this.context == 'default') {
661                 // print.print_printer gets used by bare window.print()'s.  We sometimes use window.print for the
662                 // WebBrowserPrint strategy to workaround bugs with the NSPrint xpcom, and only in the default context.
663                 var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces['nsIPrefBranch']);
664                 prefs.setCharPref('print.print_printer',obj.gPrintSettings.printerName);
665             }
666         } catch(E) {
667             this.error.standard_unexpected_error_alert("save_settings()",E);
668         }
669     }
670 }
671
672 dump('exiting util/print.js\n');