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