]> 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             return s;
296         } catch(E) {
297             alert('Error in print.js, template_sub(): ' + E);
298         }
299     },
300
301
302     'NSPrint' : function(w,silent,params) {
303         if (!w) w = window;
304         var obj = this;
305         try {
306             if (!params) params = {};
307
308             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
309             obj.data.init({'via':'stash'});
310
311             if (params.print_strategy || obj.data.print_strategy[obj.context] || obj.data.print_strategy['default']) {
312
313                 dump('params.print_strategy = ' + params.print_strategy
314                     + ' || obj.data.print_strategy[' + obj.context + '] = ' + obj.data.print_strategy[obj.context] 
315                     + ' || obj.data.print_strategy[default] = ' + obj.data.print_strategy['default'] 
316                     + ' => ' + ( params.print_strategy || obj.data.print_strategy[obj.context] || obj.data.print_strategy['default'] ) + '\n');
317                 switch(params.print_strategy || obj.data.print_strategy[obj.context] || obj.data.print_strategy['default']) {
318                     case 'dos.print':
319                     case 'custom.print':
320                         if (typeof w != 'string') {
321                             try {
322                                 var temp_w = params.msg || w.document.firstChild.innerHTML;
323                                 if (!params.msg) { params.msg = temp_w; }
324                                 if (typeof temp_w != 'string') { throw(temp_w); }
325                                 w = obj.html2txt(temp_w);
326                             } catch(E) {
327                                 dump('util.print: Could not use w.document.firstChild.innerHTML with ' + w + ': ' + E + '\n');
328                                 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
329                                 w.getSelection().selectAllChildren(w.document.firstChild);
330                                 w = w.getSelection().toString();
331                             }
332                         }
333                         obj._NSPrint_custom_print(w,silent,params);
334                     break;    
335                     case 'window.print':
336                         netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
337                         var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces['nsIPrefBranch']);
338                         var originalPrinter = false;
339                         if (prefs.prefHasUserValue('print.print_printer')) {
340                             // This is for restoring print.print_printer after any print dialog, so that when
341                             // window.print gets used again, it uses the configured printer for the right context
342                             // (which should only be default--window.print is a kludge and is in limited use),
343                             // rather than the printer last used.
344                             originalPrinter = prefs.getCharPref('print.print_printer');
345                         }
346                         if (typeof w == 'object') {
347                             w.print();
348                             if (originalPrinter) {
349                                 prefs.setCharPref('print.print_printer',originalPrinter);
350                             }
351                         } else {
352                             if (params.content_type == 'text/plain') {
353                                 w = window.open('data:text/plain,'+escape(params.msg));
354                             } else {
355                                 w = window.open('data:text/html,'+escape(params.msg));
356                             }
357                             setTimeout(
358                                 function() {
359                                     w.print();
360                                     if (originalPrinter) {
361                                         prefs.setCharPref('print.print_printer',originalPrinter);
362                                     }
363                                     setTimeout(
364                                         function() {
365                                             w.close(); 
366                                         }, 2000
367                                     );
368                                 }, 0
369                             );
370                         }
371                     break;    
372                     case 'webBrowserPrint':
373                     default:
374                         if (typeof w == 'object') {
375                             obj._NSPrint_webBrowserPrint(w,silent,params);
376                         } else {
377                             if (params.content_type == 'text/plain') {
378                                 w = window.open('data:text/plain,'+escape(params.msg));
379                             } else {
380                                 w = window.open('data:text/html,'+escape(params.msg));
381                             }
382                             setTimeout(
383                                 function() {
384                                     obj._NSPrint_webBrowserPrint(w,silent,params);
385                                     setTimeout(
386                                         function() {
387                                             w.close(); 
388                                         }, 2000
389                                     );
390                                 }, 0
391                             );
392                         }
393                     break;    
394                 }
395
396             } else {
397                 //w.print();
398                 obj._NSPrint_webBrowserPrint(w,silent,params);
399             }
400
401         } catch (e) {
402             alert('Probably not printing: ' + e);
403             this.error.sdump('D_ERROR','PRINT EXCEPTION: ' + js2JSON(e) + '\n');
404         }
405
406     },
407
408     '_NSPrint_custom_print' : function(w,silent,params) {
409         var obj = this;
410         try {
411
412             var text = w;
413             var html = params.msg || w;
414
415             var txt_file = new util.file('receipt.txt');
416             txt_file.write_content('truncate',text); 
417             var text_path = '"' + txt_file._file.path + '"';
418             txt_file.close();
419
420             var html_file = new util.file('receipt.html');
421             html_file.write_content('truncate',html); 
422             var html_path = '"' + html_file._file.path + '"';
423             html_file.close();
424             
425             var cmd = params.dos_print ?
426                 'copy ' + text_path + ' lpt1 /b\n'
427                 : obj.oils_printer_external_cmd.replace('%receipt.txt%',text_path).replace('%receipt.html%',html_path)
428             ;
429
430             file = new util.file('receipt.bat');
431             file.write_content('truncate+exec',cmd);
432             file.close();
433             file = new util.file('receipt.bat');
434
435             dump('print exec: ' + cmd + '\n');
436             var process = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);
437             process.init(file._file);
438
439             var args = [];
440
441             dump('process.run = ' + process.run(true, args, args.length) + '\n');
442
443             file.close();
444
445         } catch (e) {
446             //alert('Probably not printing: ' + e);
447             this.error.sdump('D_ERROR','_NSPrint_custom_print PRINT EXCEPTION: ' + js2JSON(e) + '\n');
448         }
449     },
450
451     '_NSPrint_webBrowserPrint' : function(w,silent,params) {
452         var obj = this;
453         try {
454             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
455             var webBrowserPrint = w
456                 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
457                 .getInterface(Components.interfaces.nsIWebBrowserPrint);
458             this.error.sdump('D_PRINT','webBrowserPrint = ' + webBrowserPrint);
459             if (webBrowserPrint) {
460                 var gPrintSettings = obj.GetPrintSettings();
461                 if (silent) gPrintSettings.printSilent = true;
462                 else gPrintSettings.printSilent = false;
463                 if (params) {
464                     if (params.marginLeft) gPrintSettings.marginLeft = params.marginLeft;
465                 }
466                 webBrowserPrint.print(gPrintSettings, null);
467                 this.error.sdump('D_PRINT','Should be printing\n');
468             } else {
469                 this.error.sdump('D_ERROR','Should not be printing\n');
470             }
471         } catch (e) {
472             //alert('Probably not printing: ' + e);
473             // Pressing cancel is expressed as an NS_ERROR_ABORT return value,
474             // causing an exception to be thrown which we catch here.
475             // Unfortunately this will also consume helpful failures
476             this.error.sdump('D_ERROR','_NSPrint_webBrowserPrint PRINT EXCEPTION: ' + js2JSON(e) + '\n');
477         }
478     },
479
480     'GetPrintSettings' : function() {
481         try {
482             //alert('entering GetPrintSettings');
483             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
484             var pref = Components.classes["@mozilla.org/preferences-service;1"]
485                 .getService(Components.interfaces.nsIPrefBranch);
486             //alert('pref = ' + pref);
487             if (pref) {
488                 this.gPrintSettingsAreGlobal = pref.getBoolPref("print.use_global_printsettings", false);
489                 this.gSavePrintSettings = pref.getBoolPref("print.save_print_settings", false);
490                 //alert('gPrintSettingsAreGlobal = ' + this.gPrintSettingsAreGlobal + '  gSavePrintSettings = ' + this.gSavePrintSettings);
491             }
492  
493             var printService = Components.classes["@mozilla.org/gfx/printsettings-service;1"]
494                 .getService(Components.interfaces.nsIPrintSettingsService);
495             if (this.gPrintSettingsAreGlobal) {
496                 this.gPrintSettings = printService.globalPrintSettings;
497                 //alert('called setPrinterDefaultsForSelectedPrinter');
498                 this.setPrinterDefaultsForSelectedPrinter(printService);
499             } else {
500                 this.gPrintSettings = printService.newPrintSettings;
501                 //alert('used printService.newPrintSettings');
502             }
503         } catch (e) {
504             this.error.sdump('D_ERROR',"GetPrintSettings() "+e+"\n");
505             //alert("GetPrintSettings() "+e+"\n");
506         }
507  
508         return this.gPrintSettings;
509     },
510
511     'setPrinterDefaultsForSelectedPrinter' : function (aPrintService) {
512         try {
513             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
514             if (this.gPrintSettings.printerName == "") {
515                 this.gPrintSettings.printerName = aPrintService.defaultPrinterName;
516                 //alert('used .defaultPrinterName');
517             }
518             //alert('printerName = ' + this.gPrintSettings.printerName);
519      
520             // First get any defaults from the printer 
521             aPrintService.initPrintSettingsFromPrinter(this.gPrintSettings.printerName, this.gPrintSettings);
522      
523             // now augment them with any values from last time
524             aPrintService.initPrintSettingsFromPrefs(this.gPrintSettings, true, this.gPrintSettings.kInitSaveAll);
525
526             // now augment from our own saved settings if they exist
527             this.load_settings();
528
529         } catch(E) {
530             this.error.sdump('D_ERROR',"setPrinterDefaultsForSelectedPrinter() "+E+"\n");
531         }
532     },
533
534     'page_settings' : function() {
535         try {
536             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
537             this.GetPrintSettings();
538             var PO = Components.classes["@mozilla.org/gfx/printsettings-service;1"].getService(Components.interfaces.nsIPrintOptions);
539             PO.ShowPrintSetupDialog(this.gPrintSettings);
540         } catch(E) {
541             this.error.standard_unexpected_error_alert("page_settings()",E);
542         }
543     },
544
545     'load_settings' : function() {
546         try {
547             var error_msg = '';
548             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
549             var file = new util.file('gPrintSettings.' + this.context);
550             if (file._file.exists()) {
551                 temp = file.get_object(); file.close();
552                 for (var i in temp) {
553                     try { this.gPrintSettings[i] = temp[i]; } catch(E) { error_msg += 'Error trying to set gPrintSettings.'+i+'='+temp[i]+' : ' + js2JSON(E) + '\n'; }
554                 }
555             }  else if (this.context != 'default') {
556                 var file = new util.file('gPrintSettings.default');
557                 if (file._file.exists()) {
558                     temp = file.get_object(); file.close();
559                     for (var i in temp) {
560                         try { this.gPrintSettings[i] = temp[i]; } catch(E) { error_msg += 'Error trying to set gPrintSettings.'+i+'='+temp[i]+' : ' + js2JSON(E) + '\n'; }
561                     }
562                 } else {
563                     this.gPrintSettings.marginTop = 0;
564                     this.gPrintSettings.marginLeft = 0;
565                     this.gPrintSettings.marginBottom = 0;
566                     this.gPrintSettings.marginRight = 0;
567                     this.gPrintSettings.headerStrLeft = '';
568                     this.gPrintSettings.headerStrCenter = '';
569                     this.gPrintSettings.headerStrRight = '';
570                     this.gPrintSettings.footerStrLeft = '';
571                     this.gPrintSettings.footerStrCenter = '';
572                     this.gPrintSettings.footerStrRight = '';
573                 }
574             }
575             if (error_msg) {
576                 this.error.sdump('D_PRINT',error_msg);
577                 this.error.yns_alert(
578                     document.getElementById('offlineStrings').getString('load_printer_settings_error_description'),
579                     document.getElementById('offlineStrings').getString('load_printer_settings_error_title'),
580                     document.getElementById('offlineStrings').getString('common.ok'),
581                     null,
582                     null,
583                     null
584                 );
585             }
586         } catch(E) {
587             this.error.standard_unexpected_error_alert("load_settings()",E);
588         }
589     },
590
591     'save_settings' : function() {
592         try {
593             var obj = this;
594             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
595             var file = new util.file('gPrintSettings.' + this.context);
596             if (typeof obj.gPrintSettings == 'undefined') obj.GetPrintSettings();
597             if (obj.gPrintSettings) file.set_object(obj.gPrintSettings); 
598             file.close();
599             if (this.context == 'default') {
600                 // print.print_printer gets used by bare window.print()'s.  We sometimes use window.print for the
601                 // WebBrowserPrint strategy to workaround bugs with the NSPrint xpcom, and only in the default context.
602                 var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces['nsIPrefBranch']);
603                 prefs.setCharPref('print.print_printer',obj.gPrintSettings.printerName);
604             }
605         } catch(E) {
606             this.error.standard_unexpected_error_alert("save_settings()",E);
607         }
608     }
609 }
610
611 dump('exiting util/print.js\n');