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