]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/xul/staff_client/chrome/content/main/main.js
augment the useragent for the xulrunner staff client
[working/Evergreen.git] / Open-ILS / xul / staff_client / chrome / content / main / main.js
1 dump('entering main/main.js\n');
2 // vim:noet:sw=4:ts=4:
3
4 var xulG;
5 var offlineStrings;
6 var authStrings;
7 var openTabs = new Array();
8 var tempWindow = null;
9 var tempFocusWindow = null;
10
11 function grant_perms(url) {
12     var perms = "UniversalXPConnect UniversalPreferencesWrite UniversalBrowserWrite UniversalPreferencesRead UniversalBrowserRead UniversalFileRead";
13     dump('Granting ' + perms + ' to ' + url + '\n');
14     if (G.pref) {
15         G.pref.setCharPref("capability.principal.codebase.p0.granted", perms);
16         G.pref.setCharPref("capability.principal.codebase.p0.id", url);
17         G.pref.setCharPref("capability.principal.codebase.p1.granted", perms);
18         G.pref.setCharPref("capability.principal.codebase.p1.id", url.replace('http:','https:'));
19         G.pref.setBoolPref("dom.disable_open_during_load",false);
20         G.pref.setBoolPref("browser.popups.showPopupBlocker",false);
21     }
22
23 }
24
25 function clear_the_cache() {
26     try {
27         var cacheClass         = Components.classes["@mozilla.org/network/cache-service;1"];
28         var cacheService    = cacheClass.getService(Components.interfaces.nsICacheService);
29         cacheService.evictEntries(Components.interfaces.nsICache.STORE_ON_DISK);
30         cacheService.evictEntries(Components.interfaces.nsICache.STORE_IN_MEMORY);
31     } catch(E) {
32         dump(E+'\n');alert(E);
33     }
34 }
35
36 function toOpenWindowByType(inType, uri) { /* for Venkman */
37     try {
38         var winopts = "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar";
39         window.open(uri, "_blank", winopts);
40     } catch(E) {
41         alert(E); throw(E);
42     }
43 }
44
45 function start_debugger() {
46     setTimeout(
47         function() {
48             try { start_venkman(); } catch(E) { alert(E); }
49         }, 0
50     );
51 };
52
53 function start_inspector() {
54     setTimeout(
55         function() {
56             try { inspectDOMDocument(); } catch(E) { alert(E); }
57         }, 0
58     );
59 };
60
61 function start_chrome_list() {
62     setTimeout(
63         function() {
64             try { startChromeList(); } catch(E) { alert(E); }
65         }, 0
66     );
67 };
68
69 function start_js_shell() {
70     setTimeout(
71         function() {
72             try { window.open('chrome://open_ils_staff_client/content/util/shell.html','shell','chrome,resizable,scrollbars'); } catch(E) { alert(E); }
73         }, 0
74     );
75 };
76
77 function new_tabs(aTabList, aContinue) {
78     if(aTabList != null) {
79         openTabs = openTabs.concat(aTabList);
80     }
81     if(G.data.session) { // Just add to the list of stuff to open unless we are logged in
82         netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
83         var targetwindow = null;
84         var focuswindow = null;
85         var focustab = {'focus' : true};
86         if(aContinue == true && tempWindow.closed == false) {
87             if(tempWindow.g == undefined || tempWindow.g.menu == undefined) {
88                 setTimeout(
89                     function() {
90                         new_tabs(null, true);
91                     }, 300);
92                 return null;
93             }
94             targetwindow = tempWindow;
95             tempWindow = null;
96             focuswindow = tempFocusWindow;
97             tempFocusWindow = null;
98             focustab = {'nofocus' : true};
99         }
100         else if(tempWindow != null) { // In theory, we are waiting on a setTimeout
101             if(tempWindow.closed == true) // But someone closed our window?
102             {
103                 tempWindow = null;
104                 tempFocusWindow = null;
105             }
106             else
107             {
108                 return null;
109             }
110         }
111         var newTab;
112         var firstURL;
113         var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].
114             getService(Components.interfaces.nsIWindowMediator);
115             // This may look out of place, but this is so we can continue this loop from down below
116 opentabs:
117             while(openTabs.length > 0) {
118             newTab = openTabs.shift();
119             if(newTab == 'new' || newTab == 'init') {
120                 if(newTab != 'init' && openTabs.length > 0 && openTabs[0] != 'new') {
121                     firstURL = openTabs.shift();
122                     if(firstURL != 'tab') { // 'new' followed by 'tab' should be equal to 'init' in functionality, this should do that
123                         if(urls[firstURL]) {
124                             firstURL = urls[firstURL];
125                         }
126                         firstURL = '&firstURL=' + window.escape(firstURL);
127                     }
128                     else {
129                         firstURL = '';
130                     }
131                 }
132                 else {
133                     firstURL = '';
134                 }
135                 targetwindow = xulG.window.open(urls.XUL_MENU_FRAME
136                     + '?server='+window.escape(G.data.server) + firstURL,
137                     '_blank','chrome,resizable'
138                 );
139                 targetwindow.xulG = xulG;
140                 if (focuswindow == null) {
141                     focuswindow = targetwindow;
142                 }
143                 tempWindow = targetwindow;
144                 tempFocusWindow = focuswindow;
145                 setTimeout(
146                     function() {
147                         new_tabs(null, true);
148                     }, 300);
149                 return null;
150             }
151             else {
152                 if(newTab == 'tab') {
153                     newTab = null;
154                 }
155                 else if(urls[newTab]) {
156                     newTab = urls[newTab];
157                 }
158                 if(targetwindow != null) { // Already have a previous target window? Use it first.
159                     if(targetwindow.g.menu.new_tab(newTab,focustab,null)) {
160                         focustab = {'nofocus' : true};
161                         continue;
162                     }
163                 }
164                 var enumerator = wm.getEnumerator('eg_menu');
165                 while(enumerator.hasMoreElements()) {
166                     targetwindow = enumerator.getNext();
167                     if(targetwindow.g.menu.new_tab(newTab,focustab,null)) {
168                         focustab = {'nofocus' : true};
169                         if (focuswindow == null) {
170                             focuswindow = targetwindow;
171                         }
172                         continue opentabs;
173                     }
174                 }
175                 // No windows found to add the tab to? Make a new one.
176                 if(newTab == null) { // Were we making a "default" tab?
177                     openTabs.unshift('init'); // 'init' does that for us!
178                 }
179                 else {
180                     openTabs.unshift('new',newTab);
181                 }
182             }
183         }
184         if(focuswindow != null) {
185             focuswindow.focus();
186         }
187     }
188 }
189
190 function main_init() {
191     dump('entering main_init()\n');
192     try {
193         clear_the_cache();
194         if("arguments" in window && window.arguments.length > 0 && window.arguments[0].wrappedJSObject != undefined && window.arguments[0].wrappedJSObject.openTabs != undefined) {
195             openTabs = openTabs.concat(window.arguments[0].wrappedJSObject.openTabs);
196         }
197
198         // Now we can safely load the strings without the cache getting wiped
199         offlineStrings = document.getElementById('offlineStrings');
200         authStrings = document.getElementById('authStrings');
201
202         if (typeof JSAN == 'undefined') {
203             throw(
204                 offlineStrings.getString('common.jsan.missing')
205             );
206         }
207         /////////////////////////////////////////////////////////////////////////////
208
209         JSAN.errorLevel = "die"; // none, warn, or die
210         JSAN.addRepository('..');
211
212         //JSAN.use('test.test'); test.test.hello_world();
213
214         var mw = self;
215         G =  {};
216         
217         G.pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
218         if (! G.pref.prefHasUserValue('general.useragent.override')) {
219             G.pref.setCharPref('general.useragent.override',navigator.userAgent + ' oils_xulrunner /xul/server/');
220         }
221
222         JSAN.use('util.error');
223         G.error = new util.error();
224         G.error.sdump('D_ERROR', offlineStrings.getString('main.testing'));
225
226         JSAN.use('util.window');
227         G.window = new util.window();
228
229         JSAN.use('auth.controller');
230         G.auth = new auth.controller( { 'window' : mw } );
231
232         JSAN.use('OpenILS.data');
233         G.data = new OpenILS.data();
234         G.data.on_error = G.auth.logoff;
235
236         JSAN.use('util.file');
237         G.file = new util.file();
238         try {
239             G.file.get('ws_info');
240             G.ws_info = G.file.get_object(); G.file.close();
241         } catch(E) {
242             G.ws_info = {};
243         }
244         G.data.ws_info = G.ws_info; G.data.stash('ws_info');
245
246         G.auth.on_login = function() {
247
248             var url = G.auth.controller.view.server_prompt.value || urls.remote;
249
250             G.data.server_unadorned = url; G.data.stash('server_unadorned'); G.data.stash_retrieve();
251
252             if (! url.match( '^http://' ) ) { url = 'http://' + url; }
253
254             G.data.server = url; G.data.stash('server'); 
255             G.data.session = { 'key' : G.auth.session.key, 'auth' : G.auth.session.authtime }; G.data.stash('session');
256             G.data.stash_retrieve();
257             try {
258                 var ios = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
259                 var cookieUri = ios.newURI("http://" + G.data.server_unadorned, null, null);
260                 var cookieUriSSL = ios.newURI("https://" + G.data.server_unadorned, null, null);
261                 var cookieSvc = Components.classes["@mozilla.org/cookieService;1"].getService(Components.interfaces.nsICookieService);
262
263                 cookieSvc.setCookieString(cookieUri, null, "ses="+G.data.session.key, null);
264                 cookieSvc.setCookieString(cookieUriSSL, null, "ses="+G.data.session.key, null);
265                 cookieSvc.setCookieString(cookieUri, null, "xul=1", null);
266                 cookieSvc.setCookieString(cookieUriSSL, null, "xul=1", null);
267
268             } catch(E) {
269                 alert(offlineStrings.getFormattedString(main.session_cookie.error, [E]));
270             }
271
272             grant_perms(url);
273
274             xulG = {
275                 'auth' : G.auth,
276                 'url' : url,
277                 'window' : G.window,
278                 'data' : G.data,
279                 'pref' : G.pref
280             };
281
282             if (G.data.ws_info && G.data.ws_info[G.auth.controller.view.server_prompt.value]) {
283                 JSAN.use('util.widgets');
284                 var deck = document.getElementById('progress_space');
285                 util.widgets.remove_children( deck );
286                 var iframe = document.createElement('iframe'); deck.appendChild(iframe);
287                 iframe.setAttribute( 'src', url + urls.XUL_LOGIN_DATA );
288                 iframe.contentWindow.xulG = xulG;
289                 G.data_xul = iframe.contentWindow;
290             } else {
291                 xulG.file = G.file;
292                 var deck = G.auth.controller.view.ws_deck;
293                 JSAN.use('util.widgets'); util.widgets.remove_children('ws_deck');
294                 var iframe = document.createElement('iframe'); deck.appendChild(iframe);
295                 iframe.setAttribute( 'src', url + urls.XUL_WORKSTATION_INFO );
296                 iframe.contentWindow.xulG = xulG;
297                 deck.selectedIndex = deck.childNodes.length - 1;
298             }
299         };
300
301         G.auth.on_standalone = function() {
302             try {
303                 G.window.open(urls.XUL_STANDALONE,'Offline','chrome,resizable');
304             } catch(E) {
305                 alert(E);
306             }
307         };
308
309         G.auth.on_standalone_export = function() {
310             try {
311                 JSAN.use('util.file'); var file = new util.file('pending_xacts');
312                 if (file._file.exists()) {
313                     var file2 = new util.file('');
314                     var f = file2.pick_file( { 'mode' : 'save', 'title' : offlineStrings.getString('main.transaction_export.title') } );
315                     if (f) {
316                         if (f.exists()) {
317                             var r = G.error.yns_alert(
318                                 offlineStrings.getFormattedString('main.transaction_export.prompt', [f.leafName]),
319                                 offlineStrings.getString('main.transaction_export.prompt.title'),
320                                 offlineStrings.getString('common.yes'),
321                                 offlineStrings.getString('common.no'),
322                                 null,
323                                 offlineStrings.getString('common.confirm')
324                             );
325                             if (r != 0) { file.close(); return; }
326                         }
327                         var e_file = new util.file(''); e_file._file = f;
328                         e_file.write_content( 'truncate', file.get_content() );
329                         e_file.close();
330                         var r = G.error.yns_alert(
331                             offlineStrings.getFormattedString('main.transaction_export.success.prompt', [f.leafName]),
332                             offlineStrings.getString('main.transaction_export.success.title'),
333                             offlineStrings.getString('common.yes'),
334                             offlineStrings.getString('common.no'),
335                             null,
336                             offlineStrings.getString('common.confirm')
337                         );
338                         if (r == 0) {
339                             var count = 0;
340                             var filename = 'pending_xacts_exported_' + new Date().getTime();
341                             var t_file = new util.file(filename);
342                             while (t_file._file.exists()) {
343                                 filename = 'pending_xacts_' + new Date().getTime() + '.exported';
344                                 t_file = new util.file(filename);
345                                 if (count++ > 100) {
346                                     throw(offlineStrings.getString('main.transaction_export.filename.error'));
347                                 }
348                             }
349                             file.close(); file = new util.file('pending_xacts'); // prevents a bug with .moveTo below
350                             file._file.moveTo(null,filename);
351                         } else {
352                             alert(offlineStrings.getString('main.transaction_export.duplicate.warning'));
353                         }
354                     } else {
355                         alert(offlineStrings.getString('main.transaction_export.no_filename.error'));
356                     }
357                 } else {
358                     alert(offlineStrings.getString('main.transaction_export.no_transactions.error'));
359                 }
360                 file.close();
361             } catch(E) {
362                 alert(E);
363             }
364         };
365
366         G.auth.on_standalone_import = function() {
367             try {
368                 JSAN.use('util.file'); var file = new util.file('pending_xacts');
369                 if (file._file.exists()) {
370                     alert(offlineStrings.getString('main.transaction_import.outstanding.error'));
371                 } else {
372                     var file2 = new util.file('');
373                     var f = file2.pick_file( { 'mode' : 'open', 'title' : offlineStrings.getString('main.transaction_import.title')} );
374                     if (f && f.exists()) {
375                         var i_file = new util.file(''); i_file._file = f;
376                         file.write_content( 'truncate', i_file.get_content() );
377                         i_file.close();
378                         var r = G.error.yns_alert(
379                             offlineStrings.getFormattedString('main.transaction_import.delete.prompt', [f.leafName]),
380                             offlineStrings.getString('main.transaction_import.success'),
381                             offlineStrings.getString('common.yes'),
382                             offlineStrings.getString('common.no'),
383                             null,
384                             offlineStrings.getString('common.confirm')
385                         );
386                         if (r == 0) {
387                             f.remove(false);
388                         }
389                     }
390                 }
391                 file.close();
392             } catch(E) {
393                 alert(E);
394             }
395         };
396
397         G.auth.on_debug = function(action) {
398             switch(action) {
399                 case 'js_console' :
400                     G.window.open(urls.XUL_DEBUG_CONSOLE,'testconsole','chrome,resizable');
401                 break;
402                 case 'clear_cache' :
403                     clear_the_cache();
404                     alert(offlineStrings.getString('main.on_debug.clear_cache'));
405                 break;
406                 default:
407                     alert(offlineStrings.getString('main.on_debug.debug'));
408                 break;
409             }
410         };
411
412         G.auth.init();
413         // XML_HTTP_SERVER will get reset to G.auth.controller.view.server_prompt.value
414
415         /////////////////////////////////////////////////////////////////////////////
416
417         var version = CLIENT_VERSION;
418         if (CLIENT_STAMP.length == 0) {
419             version = 'versionless debug build';
420             document.getElementById('debug_gb').hidden = false;
421         }
422
423         try {
424             if (G.pref && G.pref.getBoolPref('open-ils.debug_options')) {
425                 document.getElementById('debug_gb').hidden = false;
426             }
427         } catch(E) {
428         }
429
430         var appInfo = Components.classes["@mozilla.org/xre/app-info;1"] 
431             .getService(Components.interfaces.nsIXULAppInfo); 
432
433         if (appInfo.ID == "staff-client@open-ils.org")
434         {
435             try {
436                 if (G.pref && G.pref.getBoolPref('app.update.enabled')) {
437                     document.getElementById('check_upgrade_sep').hidden = false;
438                     var upgrademenu = document.getElementById('check_upgrade');
439                     upgrademenu.hidden = false;
440                     G.upgradeCheck = function () {
441                         var um = Components.classes["@mozilla.org/updates/update-manager;1"]
442                             .getService(Components.interfaces.nsIUpdateManager);
443                         var prompter = Components.classes["@mozilla.org/updates/update-prompt;1"]
444                             .createInstance(Components.interfaces.nsIUpdatePrompt);
445
446                         if (um.activeUpdate && um.activeUpdate.state == "pending")
447                             prompter.showUpdateDownloaded(um.activeUpdate);
448                         else
449                             prompter.checkForUpdates();
450                     }
451                     upgrademenu.addEventListener(
452                         'command',
453                         G.upgradeCheck,
454                         false
455                     );
456                 }
457             } catch(E) {
458             }
459         }
460
461         window.title = authStrings.getFormattedString('staff.auth.titlebar.label', version);
462         var x = document.getElementById('about_btn');
463         x.addEventListener(
464             'command',
465             function() {
466                 try { 
467                     G.window.open('about.html','about','chrome,resizable,width=800,height=600');
468                 } catch(E) { alert(E); }
469             }, 
470             false
471         );
472
473         var y = document.getElementById('new_window_btn');
474         y.addEventListener(
475             'command',
476             function() {
477                 if (G.data.session) {
478                     new_tabs(Array('new'), null, null);
479                 } else {
480                     alert ( offlineStrings.getString('main.new_window_btn.login_first_warning') );
481                 }
482             },
483             false
484         );
485
486         JSAN.use('util.mozilla');
487         var z = document.getElementById('locale_menupopup');
488         if (z) {
489             while (z.lastChild) z.removeChild(z.lastChild);
490             var locales = util.mozilla.chromeRegistry().getLocalesForPackage( String( location.href ).split(/\//)[2] );
491             var current_locale = util.mozilla.prefs().getCharPref('general.useragent.locale');
492             while (locales.hasMore()) {
493                 var locale = locales.getNext();
494                 var parts = locale.split(/-/);
495                 var label;
496                 try {
497                     label = locale + ' : ' + util.mozilla.languages().GetStringFromName(parts[0]);
498                     if (parts.length > 1) {
499                         try {
500                             label += ' (' + util.mozilla.regions().GetStringFromName(parts[1].toLowerCase()) + ')';
501                         } catch(E) {
502                             label += ' (' + parts[1] + ')';
503                         }
504                     }
505                 } catch(E) {
506                     label = locale;
507                 }
508                 var mi = document.createElement('menuitem');
509                 mi.setAttribute('label',label);
510                 mi.setAttribute('value',locale);
511                 if (locale == current_locale) {
512                     if (z.parentNode.tagName == 'menulist') {
513                         mi.setAttribute('selected','true');
514                         z.parentNode.setAttribute('label',label);
515                         z.parentNode.setAttribute('value',locale);
516                     }
517                 }
518                 z.appendChild( mi );
519             }
520         }
521         var xx = document.getElementById('apply_locale_btn');
522         xx.addEventListener(
523             'command',
524             function() {
525                 util.mozilla.change_locale(z.parentNode.value);
526             },
527             false
528         );
529
530         if ( found_ws_info_in_Achrome() && G.pref && G.pref.getBoolPref("open-ils.write_in_user_chrome_directory") ) {
531             //var hbox = x.parentNode; var b = document.createElement('button'); 
532             //b.setAttribute('label','Migrate legacy settings'); hbox.appendChild(b);
533             //b.addEventListener(
534             //    'command',
535             //    function() {
536             //        try {
537             //            handle_migration();
538             //        } catch(E) { alert(E); }
539             //    },
540             //    false
541             //);
542             if (window.confirm(offlineStrings.getString('main.settings.migrate'))) {
543                 setTimeout( function() { handle_migration(); }, 0 );
544             }
545         }
546
547         window.addEventListener(
548             'close',
549             function(ev) {
550
551                 G.data.stash_retrieve();
552                 if (typeof G.data.unsaved_data != 'undefined') {
553                     if (G.data.unsaved_data > 0) {
554                         var confirmation = window.confirm(offlineStrings.getString('menu.shutdown.unsaved_data_warning'));
555                         if (!confirmation) {
556                             ev.preventDefault();
557                             return false;
558                         }
559                     }
560                 }
561                 G.data.unsaved_data = 0;
562                 G.data.stash('unsaved_data');
563
564                 return true;
565
566             },
567             false
568         );
569
570
571     } catch(E) {
572         var error = offlineStrings.getFormattedString('common.exception', [E, '']);
573         try { G.error.sdump('D_ERROR',error); } catch(E) { dump(error); }
574         alert(error);
575     }
576     dump('exiting main_init()\n');
577 }
578
579 function found_ws_info_in_Achrome() {
580     JSAN.use('util.file');
581     var f = new util.file();
582     var f_in_chrome = f.get('ws_info','chrome');
583     var path = f_in_chrome.exists() ? f_in_chrome.path : false;
584     f.close();
585     return path;
586 }
587
588 function found_ws_info_in_Uchrome() {
589     JSAN.use('util.file');
590     var f = new util.file();
591     var f_in_uchrome = f.get('ws_info','uchrome');
592     var path = f_in_uchrome.exists() ? f_in_uchrome.path : false;
593     f.close();
594     return path;
595 }
596
597 function handle_migration() {
598     if ( found_ws_info_in_Uchrome() ) {
599         alert(offlineStrings.getFormattedString('main.settings.migrate.failed', [found_ws_info_in_Uchrome(), found_ws_info_in_Achrome()])
600         );
601     } else {
602         var dirService = Components.classes["@mozilla.org/file/directory_service;1"].getService( Components.interfaces.nsIProperties );
603         var f_new = dirService.get( "UChrm", Components.interfaces.nsIFile );
604         var f_old = dirService.get( "AChrom", Components.interfaces.nsIFile );
605         f_old.append(myPackageDir); f_old.append("content"); f_old.append("conf"); 
606         if (window.confirm(offlineStrings.getFormattedString("main.settings.migrate.confirm", [f_old.path, f_new.path]))) {
607             var files = f_old.directoryEntries;
608             while (files.hasMoreElements()) {
609                 var file = files.getNext();
610                 var file2 = file.QueryInterface( Components.interfaces.nsILocalFile );
611                 try {
612                     file2.moveTo( f_new, '' );
613                 } catch(E) {
614                     alert(offlineStrings.getFormattedString('main.settings.migrate.error', [file2.path, f_new.path]) + '\n');
615                 }
616             }
617             location.href = location.href; // huh?
618         }
619     }
620 }
621
622 dump('exiting main/main.js\n');