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