]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/xul/staff_client/chrome/content/util/print.js
define obj for this method
[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 () {
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     return this;
15 };
16
17 util.print.prototype = {
18
19     'reprint_last' : function() {
20         try {
21             var obj = this; obj.data.init({'via':'stash'});
22             if (!obj.data.last_print) {
23                 alert('Nothing to re-print');
24                 return;
25             }
26             var msg = obj.data.last_print.msg;
27             var params = obj.data.last_print.params; params.no_prompt = false;
28             obj.simple( msg, params );
29         } catch(E) {
30             this.error.standard_unexpected_error_alert('util.print.reprint_last',E);
31         }
32     },
33
34     'simple' : function(msg,params) {
35         try {
36             if (!params) params = {};
37
38             var obj = this;
39
40             obj.data.last_print = { 'msg' : msg, 'params' : params}; obj.data.stash('last_print');
41
42             var silent = false;
43             if ( params && params.no_prompt && (params.no_prompt == true || params.no_prompt == 'true') ) {
44                 silent = true;
45             }
46
47             var content_type;
48             if (params && params.content_type) {
49                 content_type = params.content_type;
50             } else {
51                 content_type = 'text/html';
52             }
53
54             var w;
55
56             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
57             obj.data.init({'via':'stash'});
58
59             if (params.print_strategy || obj.data.print_strategy) {
60
61                 switch(params.print_strategy || obj.data.print_strategy) {
62                     case 'dos.print':
63                         /* FIXME - this it a kludge.. we're going to sidestep window-based html rendering for printing */
64                         /* I'm using regexps to mangle the html receipt templates; it'd be nice to use xsl but the */
65                         /* templates aren't guaranteed to be valid xml */
66                         if (content_type=='text/html') {
67                             w = msg.replace(/<br.*?>/gi,'\r\n').replace(/<table.*?>/gi,'\r\n').replace(/<tr.*?>/gi,'\r\n').replace(/<hr.*?>/gi,'\r\n').replace(/<p.*?>/gi,'\r\n').replace(/<block.*?>/gi,'\r\n').replace(/<li.*?>/gi,'\r\n * ').replace(/<.+?>/gi,'');
68                         } else {
69                             w = msg;
70                         }
71                         if (! params.no_form_feed) { w = w + '\r\n\r\n\r\n\r\n\r\n\r\n\f'; }
72                         obj.NSPrint(w, silent, params);
73                         return;
74                     break;
75                 }
76             }
77
78             switch(content_type) {
79                 case 'text/html' :
80                     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 */ }');
81                     w = obj.win.open('data:text/html,<html id="top"><head><script src="/xul/server/main/JSAN.js"></script><script src="' + window.escape(jsrc) + '"></script></head><body onload="try{my_init();}catch(E){alert(E);}">' + window.escape(msg) + '</body></html>','receipt_temp','chrome,resizable');
82                     w.minimize();
83                     w.go_print = function() { 
84                         try {
85                             obj.NSPrint(w, silent, params);
86                         } catch(E) {
87                             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);
88                             w.print();
89                         }
90                         w.minimize(); w.close();
91                     }
92                 break;
93                 default:
94                     w = obj.win.open('data:' + content_type + ',' + window.escape(msg),'receipt_temp','chrome,resizable');
95                     w.minimize();
96                     setTimeout(
97                         function() {
98                             try {
99                                 obj.NSPrint(w, silent, params);
100                             } catch(E) {
101                                 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);
102                                 w.print();
103                             }
104                             w.minimize(); w.close();
105                         }, 1000
106                     );
107                 break;
108             }
109
110         } catch(E) {
111             this.error.standard_unexpected_error_alert('util.print.simple',E);
112         }
113     },
114     
115     'tree_list' : function (params) { 
116         try {
117             dump('print.tree_list.params.list = \n' + this.error.pretty_print(js2JSON(params.list)) + '\n');
118             dump('print.tree_list.params.data = \n' + this.error.pretty_print(js2JSON(params.data)) + '\n');
119         } catch(E) {
120             dump(E+'\n');
121         }
122         var cols = [];
123         var s = '';
124         if (params.header) s += this.template_sub( params.header, cols, params );
125         if (params.list) {
126             for (var i = 0; i < params.list.length; i++) {
127                 params.row = params.list[i];
128                 params.row_idx = i;
129                 s += this.template_sub( params.line_item, cols, params );
130             }
131         }
132         if (params.footer) s += this.template_sub( params.footer, cols, params );
133
134         if (params.sample_frame) {
135             var jsrc = 'data:text/javascript,' + window.escape('var params = { "data" : ' + js2JSON(params.data) + ', "list" : ' + js2JSON(params.list) + '};');
136             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>');
137         } else {
138             this.simple(s,params);
139         }
140     },
141
142     'template_sub' : function( msg, cols, params ) {
143         try {
144             var obj = this;
145             if (!msg) { dump('template sub called with empty string\n'); return; }
146             JSAN.use('util.date');
147             var s = msg; var b;
148
149             try{b = s; s = s.replace(/%LINE_NO%/,Number(params.row_idx)+1);}
150                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
151
152             try{b = s; s = s.replace(/%patron_barcode%/,params.patron_barcode);}
153                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
154
155             try{b = s; s = s.replace(/%LIBRARY%/,params.lib.name());}
156                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
157             try{b = s; s = s.replace(/%PINES_CODE%/,params.lib.shortname());}
158                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
159             try{b = s; s = s.replace(/%SHORTNAME%/,params.lib.shortname());}
160                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
161             try{b = s; s = s.replace(/%STAFF_FIRSTNAME%/,params.staff.first_given_name());}
162                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
163             try{b = s; s = s.replace(/%STAFF_LASTNAME%/,params.staff.family_name());}
164                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
165             try{b = s; s = s.replace(/%STAFF_BARCODE%/,params.staff.barcode); }
166                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
167             try{b = s; s = s.replace(/%STAFF_PROFILE%/,obj.data.hash.pgt[ params.staff.profile() ].name() ); }
168                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
169             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());}
170                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
171             try{b = s; s = s.replace(/%PATRON_ALIAS%/,(params.patron.alias() == '' || params.patron.alias() == null) ? '' : params.patron.alias());}
172                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
173             try{b = s; s = s.replace(/%PATRON_FIRSTNAME%/,params.patron.first_given_name());}
174                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
175             try{b = s; s = s.replace(/%PATRON_LASTNAME%/,params.patron.family_name());}
176                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
177             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() ) ;}
178                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
179
180             try{b = s; s=s.replace(/%TODAY%/g,(new Date()));}
181                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
182             try{b = s; s=s.replace(/%TODAY_m%/g,(util.date.formatted_date(new Date(),'%m')));}
183                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
184             try{b = s; s=s.replace(/%TODAY_TRIM%/g,(util.date.formatted_date(new Date(),'')));}
185                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
186             try{b = s; s=s.replace(/%TODAY_d%/g,(util.date.formatted_date(new Date(),'%d')));}
187                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
188             try{b = s; s=s.replace(/%TODAY_Y%/g,(util.date.formatted_date(new Date(),'%Y')));}
189                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
190             try{b = s; s=s.replace(/%TODAY_H%/g,(util.date.formatted_date(new Date(),'%H')));}
191                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
192             try{b = s; s=s.replace(/%TODAY_I%/g,(util.date.formatted_date(new Date(),'%I')));}
193                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
194             try{b = s; s=s.replace(/%TODAY_M%/g,(util.date.formatted_date(new Date(),'%M')));}
195                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
196             try{b = s; s=s.replace(/%TODAY_D%/g,(util.date.formatted_date(new Date(),'%D')));}
197                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
198             try{b = s; s=s.replace(/%TODAY_F%/g,(util.date.formatted_date(new Date(),'%F')));}
199                 catch(E){s = b; this.error.sdump('D_WARN','string = <' + s + '> error = ' + js2JSON(E)+'\n');}
200
201             try {
202                 if (typeof params.row != 'undefined') {
203                     if (params.row.length >= 0) {
204                         alert('debug - please tell the developers that deprecated template code tried to execute');
205                         for (var i = 0; i < cols.length; i++) {
206                             var re = new RegExp(cols[i],"g");
207                             try{b = s; s=s.replace(re, params.row[i]);}
208                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 1 string = <' + s + '>',E);}
209                         }
210                     } else { 
211                         /* for dump_with_keys */
212                         for (var i in params.row) {
213                             var re = new RegExp('%'+i+'%',"g");
214                             try{b = s; s=s.replace(re, params.row[i]);}
215                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 2 string = <' + s + '>',E);}
216                         }
217                     }
218                 }
219
220                 if (typeof params.data != 'undefined') {
221                     for (var i in params.data) {
222                         var re = new RegExp('%'+i+'%',"g");
223                         if (typeof params.data[i] == 'string') {
224                             try{b = s; s=s.replace(re, params.data[i]);}
225                                 catch(E){s = b; this.error.standard_unexpected_error_alert('print.js, template_sub(): 3 string = <' + s + '>',E);}
226                         }
227                     }
228                 }
229             } catch(E) { dump(E+'\n'); }
230
231             return s;
232         } catch(E) {
233             alert('Error in print.js, template_sub(): ' + E);
234         }
235     },
236
237
238     'NSPrint' : function(w,silent,params) {
239         if (!w) w = window;
240         var obj = this;
241         try {
242             if (!params) params = {};
243
244             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
245             obj.data.init({'via':'stash'});
246
247             if (params.print_strategy || obj.data.print_strategy) {
248
249                 switch(params.print_strategy || obj.data.print_strategy) {
250                     case 'dos.print':
251                         if (typeof w != 'string') {
252                             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
253                             w.getSelection().selectAllChildren(w.document.firstChild);
254                             w = w.getSelection().toString();
255                         }
256                         obj._NSPrint_dos_print(w,silent,params);
257                     break;    
258                     case 'window.print':
259                         w.print();
260                     break;    
261                     case 'webBrowserPrint':
262                         obj._NSPrint_webBrowserPrint(w,silent,params);
263                     break;    
264                     default:
265                         //w.print();
266                         obj._NSPrint_webBrowserPrint(w,silent,params);
267                     break;    
268                 }
269
270             } else {
271                 //w.print();
272                 obj._NSPrint_webBrowserPrint(w,silent,params);
273             }
274
275         } catch (e) {
276             alert('Probably not printing: ' + e);
277             this.error.sdump('D_ERROR','PRINT EXCEPTION: ' + js2JSON(e) + '\n');
278         }
279
280     },
281
282     '_NSPrint_dos_print' : function(w,silent,params) {
283         var obj = this;
284         try {
285
286             /* OLD way: This is a kludge/workaround.  webBrowserPrint doesn't always work.  So we're going to let
287                 the html window handle our receipt template rendering, and then force a selection of all
288                 the text nodes and dump that to a file, for printing through a dos utility */
289
290             /* NEW way: we just pass in the text */
291
292             var text = w;
293
294             var file = new util.file('receipt.txt');
295             file.write_content('truncate',text); 
296             var path = file._file.path;
297             file.close();
298             
299             file = new util.file('receipt.bat');
300             file.write_content('truncate+exec','#!/bin/sh\ncopy "' + path + '" lpt1 /b\nlpr ' + path + '\n');
301             file.close();
302             file = new util.file('receipt.bat');
303
304             var process = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);
305             process.init(file._file);
306
307             var args = [];
308
309             dump('process.run = ' + process.run(true, args, args.length) + '\n');
310
311             file.close();
312
313         } catch (e) {
314             //alert('Probably not printing: ' + e);
315             this.error.sdump('D_ERROR','_NSPrint_dos_print PRINT EXCEPTION: ' + js2JSON(e) + '\n');
316         }
317     },
318
319     '_NSPrint_webBrowserPrint' : function(w,silent,params) {
320         var obj = this;
321         try {
322             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
323             var webBrowserPrint = w
324                 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
325                 .getInterface(Components.interfaces.nsIWebBrowserPrint);
326             this.error.sdump('D_PRINT','webBrowserPrint = ' + webBrowserPrint);
327             if (webBrowserPrint) {
328                 var gPrintSettings = obj.GetPrintSettings();
329                 if (silent) gPrintSettings.printSilent = true;
330                 else gPrintSettings.printSilent = false;
331                 if (params) {
332                     if (params.marginLeft) gPrintSettings.marginLeft = params.marginLeft;
333                 }
334                 webBrowserPrint.print(gPrintSettings, null);
335                 this.error.sdump('D_PRINT','Should be printing\n');
336             } else {
337                 this.error.sdump('D_ERROR','Should not be printing\n');
338             }
339         } catch (e) {
340             //alert('Probably not printing: ' + e);
341             // Pressing cancel is expressed as an NS_ERROR_ABORT return value,
342             // causing an exception to be thrown which we catch here.
343             // Unfortunately this will also consume helpful failures
344             this.error.sdump('D_ERROR','_NSPrint_webBrowserPrint PRINT EXCEPTION: ' + js2JSON(e) + '\n');
345         }
346     },
347
348     'GetPrintSettings' : function() {
349         try {
350             //alert('entering GetPrintSettings');
351             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
352             var pref = Components.classes["@mozilla.org/preferences-service;1"]
353                 .getService(Components.interfaces.nsIPrefBranch);
354             //alert('pref = ' + pref);
355             if (pref) {
356                 this.gPrintSettingsAreGlobal = pref.getBoolPref("print.use_global_printsettings", false);
357                 this.gSavePrintSettings = pref.getBoolPref("print.save_print_settings", false);
358                 //alert('gPrintSettingsAreGlobal = ' + this.gPrintSettingsAreGlobal + '  gSavePrintSettings = ' + this.gSavePrintSettings);
359             }
360  
361             var printService = Components.classes["@mozilla.org/gfx/printsettings-service;1"]
362                 .getService(Components.interfaces.nsIPrintSettingsService);
363             if (this.gPrintSettingsAreGlobal) {
364                 this.gPrintSettings = printService.globalPrintSettings;
365                 //alert('called setPrinterDefaultsForSelectedPrinter');
366                 this.setPrinterDefaultsForSelectedPrinter(printService);
367             } else {
368                 this.gPrintSettings = printService.newPrintSettings;
369                 //alert('used printService.newPrintSettings');
370             }
371         } catch (e) {
372             this.error.sdump('D_ERROR',"GetPrintSettings() "+e+"\n");
373             //alert("GetPrintSettings() "+e+"\n");
374         }
375  
376         return this.gPrintSettings;
377     },
378
379     'setPrinterDefaultsForSelectedPrinter' : function (aPrintService) {
380         try {
381             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
382             if (this.gPrintSettings.printerName == "") {
383                 this.gPrintSettings.printerName = aPrintService.defaultPrinterName;
384                 //alert('used .defaultPrinterName');
385             }
386             //alert('printerName = ' + this.gPrintSettings.printerName);
387      
388             // First get any defaults from the printer 
389             aPrintService.initPrintSettingsFromPrinter(this.gPrintSettings.printerName, this.gPrintSettings);
390      
391             // now augment them with any values from last time
392             aPrintService.initPrintSettingsFromPrefs(this.gPrintSettings, true, this.gPrintSettings.kInitSaveAll);
393
394             // now augment from our own saved settings if they exist
395             this.load_settings();
396
397         } catch(E) {
398             this.error.sdump('D_ERROR',"setPrinterDefaultsForSelectedPrinter() "+E+"\n");
399         }
400     },
401
402     'page_settings' : function() {
403         try {
404             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
405             this.GetPrintSettings();
406             var PO = Components.classes["@mozilla.org/gfx/printsettings-service;1"].getService(Components.interfaces.nsIPrintOptions);
407             PO.ShowPrintSetupDialog(this.gPrintSettings);
408         } catch(E) {
409             this.error.standard_unexpected_error_alert("page_settings()",E);
410         }
411     },
412
413     'load_settings' : function() {
414         try {
415             var error_msg = '';
416             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
417             var file = new util.file('gPrintSettings');
418             if (file._file.exists()) {
419                 temp = file.get_object(); file.close();
420                 for (var i in temp) {
421                     try { this.gPrintSettings[i] = temp[i]; } catch(E) { error_msg += 'Error trying to set gPrintSettings.'+i+'='+temp[i]+' : ' + js2JSON(E) + '\n'; }
422                 }
423             } else {
424                 this.gPrintSettings.marginTop = 0;
425                 this.gPrintSettings.marginLeft = 0;
426                 this.gPrintSettings.marginBottom = 0;
427                 this.gPrintSettings.marginRight = 0;
428                 this.gPrintSettings.headerStrLeft = '';
429                 this.gPrintSettings.headerStrCenter = '';
430                 this.gPrintSettings.headerStrRight = '';
431                 this.gPrintSettings.footerStrLeft = '';
432                 this.gPrintSettings.footerStrCenter = '';
433                 this.gPrintSettings.footerStrRight = '';
434             }
435             if (error_msg) {
436                 this.error.sdump('D_PRINT',error_msg);
437                 this.error.yns_alert(
438                     document.getElementById('offlineStrings').getString('load_printer_settings_error_description'),
439                     document.getElementById('offlineStrings').getString('load_printer_settings_error_title'),
440                     document.getElementById('offlineStrings').getString('common.ok'),
441                     null,
442                     null,
443                     null
444                 );
445             }
446         } catch(E) {
447             this.error.standard_unexpected_error_alert("load_settings()",E);
448         }
449     },
450
451     'save_settings' : function() {
452         try {
453             var obj = this;
454             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
455             var file = new util.file('gPrintSettings');
456             if (typeof obj.gPrintSettings == 'undefined') obj.GetPrintSettings();
457             if (obj.gPrintSettings) file.set_object(obj.gPrintSettings); 
458             file.close();
459         } catch(E) {
460             this.error.standard_unexpected_error_alert("save_settings()",E);
461         }
462     }
463 }
464
465 dump('exiting util/print.js\n');