]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/xul/staff_client/chrome/content/OpenILS/global_util.js
oils_lock_page() and oils_unlock_page() for xul interfaces that wraps xulG.lock_tab...
[Evergreen.git] / Open-ILS / xul / staff_client / chrome / content / OpenILS / global_util.js
1     function $(id) { return document.getElementById(id); }
2
3     function oils_lock_page(params) {
4         if (!params) { params = {}; }
5         if (window.oils_lock) {
6             if (!params.allow_multiple_locks) {
7                 return 'already locked';
8             }
9         }
10         window.oils_lock = true;
11         if (typeof xulG != 'undefined') {
12             if (typeof xulG.unlock_tab == 'function') {
13                 xulG.lock_tab();
14             }
15         }
16         return 'locked';
17     }
18
19     function oils_unlock_page(params) {
20         window.oils_lock = false;
21         if (typeof xulG != 'undefined') {
22             if (typeof xulG.unlock_tab == 'function') {
23                 xulG.unlock_tab();
24             }
25         }
26         return 'unlocked';
27     }
28
29     window.addEventListener(
30         'close',
31         function(ev) {
32
33                 if (window.oils_lock) {
34                     var confirmation = window.confirm($('offlineStrings').getString('menu.close_window.unsaved_data_warning'));
35                     if (!confirmation) {
36                         ev.preventDefault();
37                         return false;
38                     }
39                 }
40
41                 window.oils_lock = false;
42                 if (typeof xulG != 'undefined') {
43                     if (typeof xulG.unlock_tab == 'function') {
44                         xulG.unlock_tab();
45                     }
46                 }
47
48                 return true;
49         },
50         false
51     );
52
53     function ses(a,params) {
54         try {
55             if (!params) params = {};
56             var data;
57             if (params.data) {
58                 data = params.data; data.stash_retrieve();
59             } else {
60                 // This has been breaking in certain contexts, with an internal instantiation of util.error failing because of util.error being an object instead of the constructor function it should be
61                 JSAN.use('OpenILS.data'); data = new OpenILS.data(); data.stash_retrieve();
62             }
63
64             switch(a) {
65                 case 'staff' : return data.list.au[0]; break;
66                 case 'staff_id' : return data.list.au[0].id(); break;
67                 case 'staff_usrname' : return data.list.au[0].usrname(); break;
68                 case 'ws_ou' :
69                     return data.list.au[0].ws_ou();
70                 break;
71                 case 'ws_ou_shortname' :
72                     return data.hash.aou[ data.list.au[0].ws_ou() ].shortname();
73                 break;
74                 case 'authtime' :
75                     return data.session.authtime;
76                 break;
77                 case 'key':
78                 default:
79                     return data.session.key;
80                 break;
81             }
82         } catch(E) {
83             alert(location.href + '\nError in global_utils.js, ses(): ' + E);
84             throw(E);
85         }
86     }
87
88     function font_helper() {
89         try {
90             JSAN.use('OpenILS.data'); var data = new OpenILS.data(); data.init({'via':'stash'});
91             removeCSSClass(document.documentElement,'ALL_FONTS_LARGER');
92             removeCSSClass(document.documentElement,'ALL_FONTS_SMALLER');
93             removeCSSClass(document.documentElement,'ALL_FONTS_XX_SMALL');
94             removeCSSClass(document.documentElement,'ALL_FONTS_X_SMALL');
95             removeCSSClass(document.documentElement,'ALL_FONTS_SMALL');
96             removeCSSClass(document.documentElement,'ALL_FONTS_MEDIUM');
97             removeCSSClass(document.documentElement,'ALL_FONTS_LARGE');
98             removeCSSClass(document.documentElement,'ALL_FONTS_X_LARGE');
99             removeCSSClass(document.documentElement,'ALL_FONTS_XX_LARGE');
100             addCSSClass(document.documentElement,data.global_font_adjust);
101         } catch(E) {
102             var Strings = $('offlineStrings') || $('commonStrings');
103             alert(Strings.getFormattedString('openils.global_util.font_size.error', [E]));
104         }
105     }
106
107     function oils_persist(e,cancelable) {
108         try {
109             if (!e) { return; }
110             if (typeof cancelable == 'undefined') { cancelable = false; } 
111             var evt = document.createEvent("Events");
112             evt.initEvent( 'oils_persist', false, cancelable ); // event name, bubbles, cancelable
113             e.dispatchEvent(evt);
114         } catch(E) {
115             alert('Error with oils_persist():' + E);
116         }
117     }
118
119     function persist_helper(base_key_suffix) {
120         try {
121             if (base_key_suffix) {
122                 base_key_suffix = base_key_suffix.replace(/[^A-Za-z]/g,'_') + '_';
123             } else {
124                 base_key_suffix = '';
125             }
126
127             function gen_event_handler(etype,node) {
128                 return function(ev) {
129                     try {
130                         oils_persist(ev.target);
131                     } catch(E) {
132                         alert('Error in persist_helper, firing virtual event oils_persist after ' + etype + ' event on ' + node.nodeName + '.id = ' + node.id + ': ' + E);
133                     }
134                 };
135             };
136
137             function gen_oils_persist_handler(bk,node) {
138                 return function(ev) {
139                     try {
140                         netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
141                         var target;
142                         if (ev.target.nodeName == 'command') {
143                             target = node;
144                             if (ev.explicitOriginalTarget != node) return;
145                         } else {
146                             target = ev.target;
147                             if (target == window) {
148                                 target = window.document.documentElement;
149                             }
150                         }
151                         var filename = location.pathname.split('/')[ location.pathname.split('/').length - 1 ];
152                         var base_key = 'oils_persist_' + String(location.hostname + '_' + filename + '_' + target.getAttribute('id')).replace('/','_','g') + '_' + base_key_suffix;
153                         var attribute_list = target.getAttribute('oils_persist').split(' ');
154                         dump('on_oils_persist: <<< ' + target.nodeName + '.id = ' + target.id + '\t' + bk + '\n');
155                         for (var j = 0; j < attribute_list.length; j++) {
156                             var key = base_key + attribute_list[j];
157                             var value = target.getAttribute( attribute_list[j] );
158                             if ( attribute_list[j] == 'checked' && ['checkbox','toolbarbutton'].indexOf( target.nodeName ) > -1 ) {
159                                 value = target.checked;
160                                 dump('\t' + value + ' <== .' + attribute_list[j] + '\n');
161                             } else if ( attribute_list[j] == 'value' && ['textbox'].indexOf( target.nodeName ) > -1 ) {
162                                 value = target.value;
163                                 dump('\t' + value + ' <== .' + attribute_list[j] + '\n');
164                             } else if ( attribute_list[j] == 'sizemode' && ['window'].indexOf( target.nodeName ) > -1 ) {
165                                 value = window.windowState;
166                                 dump('\t' + value + ' <== window.windowState, @' + attribute_list[j] + '\n');
167                             } else if ( attribute_list[j] == 'height' && ['window'].indexOf( target.nodeName ) > -1 ) {
168                                 value = window.outerHeight;
169                                 dump('\t' + value + ' <== window.outerHeight, @' + attribute_list[j] + '\n');
170                             } else if ( attribute_list[j] == 'width' && ['window'].indexOf( target.nodeName ) > -1 ) {
171                                 value = window.outerWidth;
172                                 dump('\t' + value + ' <== window.outerWidth, @' + attribute_list[j] + '\n');
173                             } else {
174                                 dump('\t' + value + ' <== @' + attribute_list[j] + '\n');
175                             }
176                             prefs.setCharPref( key, value );
177                             // TODO: Need to add logic for splitter repositioning, grippy state, etc.
178                             // NOTE: oils_persist_peers and oils_persist="width" on those peers can help with the elements adjacent to a splitter
179                         }
180                         if (target.hasAttribute('oils_persist_peers') && ! ev.cancelable) { // We abuse the .cancelable field on the oils_persist event to prevent looping
181                             var peer_list = target.getAttribute('oils_persist_peers').split(' ');
182                             for (var j = 0; j < peer_list.length; j++) {
183                                 dump('on_oils_persist: dispatching oils_persist to peer ' + peer_list[j] + '\n');
184                                 oils_persist( document.getElementById( peer_list[j] ), true );
185                             } 
186                         }
187                     } catch(E) {
188                         alert('Error in persist_helper() event listener for ' + bk + ': ' + E);
189                     }
190                 };
191             }
192
193             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
194             var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces['nsIPrefBranch']);
195             var nodes = document.getElementsByAttribute('oils_persist','*');
196             for (var i = 0; i < nodes.length; i++) {
197                 var filename = location.pathname.split('/')[ location.pathname.split('/').length - 1 ];
198                 var base_key = 'oils_persist_' + String(location.hostname + '_' + filename + '_' + nodes[i].getAttribute('id')).replace('/','_','g') + '_' + base_key_suffix;
199                 var attribute_list = nodes[i].getAttribute('oils_persist').split(' ');
200                 dump('persist_helper: >>> ' + nodes[i].nodeName + '.id = ' + nodes[i].id + '\t' + base_key + '\n');
201                 for (var j = 0; j < attribute_list.length; j++) {
202                     var key = base_key + attribute_list[j];
203                     var has_key = prefs.prefHasUserValue(key);
204                     var value = has_key ? prefs.getCharPref(key) : null;
205                     if (value == 'true') { value = true; }
206                     if (value == 'false') { value = false; }
207                     if (has_key) {
208                         if ( attribute_list[j] == 'checked' && ['checkbox','toolbarbutton'].indexOf( nodes[i].nodeName ) > -1 ) {
209                             nodes[i].checked = value; 
210                             dump('\t' + value + ' ==> .' + attribute_list[j] + '\n');
211                             if (!value) {
212                                 nodes[i].removeAttribute('checked');
213                                 dump('\tremoving @checked\n');
214                             }
215                         } else if ( attribute_list[j] == 'value' && ['textbox'].indexOf( nodes[i].nodeName ) > -1 ) {
216                             nodes[i].value = value;
217                             dump('\t' + value + ' ==> .' + attribute_list[j] + '\n');
218                         } else if ( attribute_list[j] == 'sizemode' && ['window'].indexOf( nodes[i].nodeName ) > -1 ) {
219                             switch(value) {
220                                 case window.STATE_MAXIMIZED:
221                                     window.maximize();
222                                     break;
223                                 case window.STATE_MINIMIZED:
224                                     window.minimize();
225                                     break;
226                             };
227                             dump('\t' + value + ' ==> window.windowState, @' + attribute_list[j] + '\n');
228                         } else if ( attribute_list[j] == 'height' && ['window'].indexOf( nodes[i].nodeName ) > -1 ) {
229                             window.outerHeight = value;
230                             dump('\t' + value + ' ==> window.outerHeight, @' + attribute_list[j] + '\n');
231                         } else if ( attribute_list[j] == 'width' && ['window'].indexOf( nodes[i].nodeName ) > -1 ) {
232                             window.outerWidth = value;
233                             dump('\t' + value + ' ==> window.outerWidth, @' + attribute_list[j] + '\n');
234                         } else {
235                             nodes[i].setAttribute( attribute_list[j], value);
236                             dump('\t' + value + ' ==> @' + attribute_list[j] + '\n');
237                         }
238                     }
239                 }
240                 var cmd = nodes[i].getAttribute('command');
241                 var cmd_el = document.getElementById(cmd);
242                 if (nodes[i].disabled == false && nodes[i].hidden == false) {
243                     var no_poke = nodes[i].getAttribute('oils_persist_no_poke');
244                     if (no_poke && no_poke == 'true') {
245                         // Timing issue for some checkboxes; don't poke them with an event
246                         dump('\tnot poking\n');
247                     } else {
248                         if (cmd_el) {
249                             dump('\tpoking @command\n');
250                             var evt = document.createEvent("Events");
251                             evt.initEvent( 'command', true, true );
252                             cmd_el.dispatchEvent(evt);
253                         } else {
254                             dump('\tpoking\n');
255                             var evt = document.createEvent("Events");
256                             evt.initEvent( 'command', true, true );
257                             nodes[i].dispatchEvent(evt);
258                         }
259                     }
260                 }
261                 if (cmd_el) {
262                     cmd_el.addEventListener(
263                         'command',
264                         gen_event_handler('command',cmd_el),
265                         false
266                     );
267                     cmd_el.addEventListener(
268                         'oils_persist',
269                         gen_oils_persist_handler( base_key, nodes[i] ),
270                         false
271                     );
272                 } else {
273                     var node = nodes[i];
274                     var event_types = [];
275                     if (node.hasAttribute('oils_persist_events')) {
276                         var event_type_list = node.getAttribute('oils_persist_events').split(' ');
277                         for (var j = 0; j < event_type_list.length; j++) {
278                             event_types.push( event_type_list[j] );
279                         }
280                     } else {
281                         if (node.nodeName == 'textbox') { 
282                             event_types.push('change'); 
283                         } else if (node.nodeName == 'window') {
284                             event_types.push('resize'); 
285                             node = window; // xul window is an element of window.document
286                         } else {
287                             event_types.push('command'); 
288                         }
289                     }
290                     for (var j = 0; j < event_types.length; j++) {
291                         node.addEventListener(
292                             event_types[j],
293                             gen_event_handler(event_types[j],node),
294                             false
295                         );
296                     }
297                     node.addEventListener(
298                         'oils_persist',
299                         gen_oils_persist_handler( base_key, node ),
300                         false
301                     );
302                 }
303             }
304         } catch(E) {
305             alert('Error in persist_helper(): ' + E);
306         }
307     }
308
309     function getKeys(o) {
310         var keys = [];
311         for (var k in o) keys.push(k);
312         return keys;
313     }
314
315     function get_contentWindow(frame) {
316         try {
317             netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
318             if (frame && frame.contentWindow) {
319                 try {
320                     if (typeof frame.contentWindow.wrappedJSObject != 'undefined') {
321                                      return frame.contentWindow.wrappedJSObject;
322                           }
323                 } catch(E) {
324                     var Strings = $('offlineStrings') || $('commonStrings');
325                     alert(Strings.getFormattedString('openils.global_util.content_window_jsobject.error', [frame, E]));
326                 }
327                 return frame.contentWindow;
328             } else {
329                 return null;
330             }
331         } catch(E) {
332             var Strings = $('offlineStrings') || $('commonStrings');
333             alert(Strings.getFormattedString('openils.global_util.content_window.error', [frame, E]));
334         }
335     }
336
337     function update_modal_xulG(v) {
338         try {
339             JSAN.use('OpenILS.data'); var data = new OpenILS.data(); data.init({'via':'stash'});
340             var key = location.pathname + location.search + location.hash;
341             if (typeof data.modal_xulG_stack != 'undefined' && typeof data.modal_xulG_stack[key] != 'undefined') {
342                 data.modal_xulG_stack[key][ data.modal_xulG_stack[key].length - 1 ] = v;
343                 data.stash('modal_xulG_stack');
344             }
345         } catch(E) {
346             alert('FIXME: update_modal_xulG => ' + E);
347         }
348     }
349
350     function xul_param(param_name,_params) {
351         /* By default, this function looks for a CGI-style query param identified by param_name.  If one isn't found, it then looks in xulG.  If one still isn't found, and _params.stash_name is true, it looks in the global xpcom stash for the field identified by stash_name.  If _params.concat is true, then it looks in all these places and concatenates the results.  There are also options for converting JSON to javascript objects, and clearing the xpcom stash_name field after retrieval.  Also added, ability to search a specific spot in the xpcom stash that implements a stack to hold xulG's for modal windows */
352         try {
353             //dump('xul_param('+param_name+','+js2JSON(_params)+')\n');
354             var value = undefined; if (!_params) _params = {};
355             if (typeof _params.no_cgi == 'undefined') {
356                 var cgi = new CGI();
357                 if (cgi.param(param_name)) {
358                     var x = cgi.param(param_name);
359                     //dump('\tfound via location.href = ' + x + '\n');
360                     if (typeof _params.JSON2js_if_cgi != 'undefined') {
361                         x = JSON2js( x );
362                         //dump('\tJSON2js = ' + x + '\n');
363                     }
364                     if (typeof _params.concat == 'undefined') {
365                         //alert(param_name + ' x = ' + x);
366                         return x; // value
367                     } else {
368                         if (value) {
369                             if (value.constructor != Array) value = [ value ];
370                             value = value.concat(x);
371                         } else {
372                             value = x;
373                         }
374                     }
375                 }
376             }
377             if (typeof _params.no_xulG == 'undefined') {
378                 if (typeof _params.modal_xulG != 'undefined') {
379                     JSAN.use('OpenILS.data'); var data = new OpenILS.data(); data.init({'via':'stash'});
380                     var key = location.pathname + location.search + location.hash;
381                     //dump('xul_param, considering modal key = ' + key + '\n');
382                     if (typeof data.modal_xulG_stack != 'undefined' && typeof data.modal_xulG_stack[key] != 'undefined') {
383                         xulG = data.modal_xulG_stack[key][ data.modal_xulG_stack[key].length - 1 ];
384                     }
385                 }
386                 if (typeof xulG == 'object' && typeof xulG[ param_name ] != 'undefined') {
387                     var x = xulG[ param_name ];
388                     //dump('\tfound via xulG = ' + x + '\n');
389                     if (typeof _params.JSON2js_if_xulG != 'undefined') {
390                         x = JSON2js( x );
391                         //dump('\tJSON2js = ' + x + '\n');
392                     }
393                     if (typeof _params.concat == 'undefined') {
394                         //alert(param_name + ' x = ' + x);
395                         return x; // value
396                     } else {
397                         if (value) {
398                             if (value.constructor != Array) value = [ value ];
399                             value = value.concat(x);
400                         } else {
401                             value = x;
402                         }
403                     }
404                 }
405             }
406             if (typeof _params.no_xpcom == 'undefined') {
407                 /* the field names used for temp variables in the global stash tend to be more unique than xuLG or CGI param names, to avoid collisions */
408                 if (typeof _params.stash_name != 'undefined') { 
409                     JSAN.use('OpenILS.data'); var data = new OpenILS.data(); data.init({'via':'stash'});
410                     if (typeof data[ _params.stash_name ] != 'undefined') {
411                         var x = data[ _params.stash_name ];
412                         //dump('\tfound via xpcom = ' + x + '\n');
413                         if (typeof _params.JSON2js_if_xpcom != 'undefined') {
414                             x = JSON2js( x );
415                             //dump('\tJSON2js = ' + x + '\n');
416                         }
417                         if (_params.clear_xpcom) { 
418                             data[ _params.stash_name ] = undefined; data.stash( _params.stash_name ); 
419                         }
420                         if (typeof _params.concat == 'undefined') {
421                             //alert(param_name + ' x = ' + x);
422                             return x; // value
423                         } else {
424                             if (value) {
425                                 if (value.constructor != Array) value = [ value ];
426                                 value = value.concat(x);
427                             } else {
428                                 value = x;
429                             }
430                         }
431                     }
432                 }
433             }
434             //alert(param_name + ' value = ' + value);
435             return value;
436         } catch(E) {
437             dump('xul_param error: ' + E + '\n');
438         }
439     }
440
441     function get_bool(a) {
442         // Normal javascript interpretation except 'f' == false, per postgres, and 'F' == false, and '0' == false (newer JSON is returning '0' instead of 0 in cases)
443         // So false includes 'f', '', '0', 0, null, and undefined
444         if (a == 'f') return false;
445         if (a == 'F') return false;
446         if (a == '0') return false;
447         if (a) return true; else return false;
448     }
449
450     function get_localized_bool(a) {
451         var Strings = $('offlineStrings') || $('commonStrings');
452         return get_bool(a) ? Strings.getString('common.yes') : Strings.getString('common.no');
453     }
454
455     function get_db_true() {
456         return 't';
457     }
458
459     function get_db_false() {
460         return 'f';
461     }
462
463     function copy_to_clipboard(ev) {
464         try {
465             netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
466             var text;
467             if (typeof ev == 'object') {
468                 if (typeof ev.target != 'undefined') {
469                     if (typeof ev.target.textContent != 'undefined') if (ev.target.textContent) text = ev.target.textContent;
470                     if (typeof ev.target.value != 'undefined') if (ev.target.value) text = ev.target.value;
471                 }
472             } else if (typeof ev == 'string') {
473                 text = ev;
474             }
475             const gClipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"]
476                 .getService(Components.interfaces.nsIClipboardHelper);
477             gClipboardHelper.copyString(text);
478             var Strings = $('offlineStrings') || $('commonStrings');
479             alert(Strings.getFormattedString('openils.global_util.clipboard', [text]));
480         } catch(E) {
481             var Strings = $('offlineStrings') || $('commonStrings');
482             alert(Strings.getFormattedString('openils.global_util.clipboard.error', [E]));    
483         }
484     }
485
486     function clear_the_cache() {
487         try {
488             netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
489             var cacheClass         = Components.classes["@mozilla.org/network/cache-service;1"];
490             var cacheService    = cacheClass.getService(Components.interfaces.nsICacheService);
491             cacheService.evictEntries(Components.interfaces.nsICache.STORE_ON_DISK);
492             cacheService.evictEntries(Components.interfaces.nsICache.STORE_IN_MEMORY);
493         } catch(E) {
494             var Strings = $('offlineStrings') || $('commonStrings');
495             alert(Strings.getFormattedString('openils.global_util.clear_cache.error', [E]));
496         }
497     }
498
499     function toOpenWindowByType(inType, uri) {
500         var winopts = "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar";
501         window.open(uri, "_blank", winopts);
502     }
503
504     function url_prefix(url) {
505         if (url.match(/^\//)) url = urls.remote + url;
506         if (! url.match(/^(http|chrome):\/\//) && ! url.match(/^data:/) ) url = 'http://' + url;
507         dump('url_prefix = ' + url + '\n');
508         return url;
509     }
510