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